# PHP Manual

2026-04-28

# Copyright

Copyright © 1997 - 2026 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/.

# PHP Manual

# About this manual

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.

This manual includes information covering the two most recent major releases of PHP (versions 7 and 8). Information about extensions that are no longer included with those versions of PHP and changes to functions in earlier versions is not included. Archives of older versions of the manual that document previous releases of PHP are available from the "More documentation" section on the » "Documentation" page of the PHP website.

You can download this manual in several formats at » https://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.

# Authors and Contributors

There is a large number of contributors who currently help in our work or have provided a great amount of help to the project in the past. There are also a lot of unnamed people who help out with user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All of the lists provided below are in alphabetical order.

# Authors and Editors

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

# User Note Maintainers

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

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

# Getting Started

# What is PHP and what can it do?

# What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Nice, but what does that mean? An example:

Example #1 An introductory example

`<!DOCTYPE html>
<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 jumping in 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. A web server can even be configured to process all HTML files with PHP, and then there's no way that users can tell that PHP is being used.

The best part about using PHP is that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid to read the long list of PHP's features. With PHP, almost anyone can get up and running and be writing simple scripts in no time at all.

Although PHP's development is focused on server-side scripting, much more can be done with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial to jump straight to learning about web programming.

# What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so it 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 two main areas where PHP scripts are used.

- Server-side scripting. This is the most widely used and main target field for PHP. Three things are needed to make this work: the PHP parser (CGI or server module), a web server, and a web browser. All these can run on a local machine in order to just experiment with PHP programming. See the installation instructions section for more information.
- Command line scripting. A PHP script can be run without any server or browser, only the PHP parser is needed to use it this way. This type of usage is ideal for scripts regularly executed using cron (on Unix or macOS) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, macOS, RISC OS, and probably others. PHP also has 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, developers have the freedom of choosing an operating system and a web server. Furthermore, they also have the choice of using procedural programming or object-oriented programming (OOP), or a mixture of them both.

PHP is not limited to outputting HTML. PHP's abilities include outputting rich file types, such as images or PDF files, encrypting data, and sending emails. It can also output easily any text, such as JSON or XML. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for 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. It 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.

This page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.

# A simple tutorial

## Table of Contents

- Your first PHP-enabled page
- Something Useful
- Dealing with Forms
- What's next?

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.

# Your first PHP-enabled page

This tutorial assumes PHP is already installed. Installation instructions can be found on the » download page.

Create a file named hello.php with the following content:

Example #1 Our first PHP script: hello.php

`<?php
echo "Hello World!";
?>`

Using your terminal, navigate to the directory containing this file and start a development server with the following command:

    php -S localhost:8000

Use your browser to access the file with your web server's URL, ending with the `/hello.php` file reference. According to the previous command executed, the URL will be `http://localhost:8000/hello.php`. If everything is configured correctly, this file will be parsed by PHP and you will see the "Hello World!" output displayed in your browser.

PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write the PHP statements, as demonstrated in the following example:

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

This will result in the following output:

    <!DOCTYPE html>
    <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.

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.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

Example #2 Get system information from PHP

`<?php
phpinfo();
?>`

# Something Useful

Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].

> Note:

> $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information.

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:

    Mozilla/5.0 (Linux) Firefox/112.0

There are many types of variables available in PHP. In the above example we printed an element from an Array variable. 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 Firefox you can do this:

Example #2 Example using control structures and functions

`<?php
if (str_contains($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
echo 'You are using Firefox.';
}
?>`

A sample output of this script may be:

    You are using Firefox.

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 str_contains() function call. str_contains() is a function built into PHP which determines if a given string contains another string. In this case we are looking for `'Firefox'` (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns true. Otherwise, it returns `false`. If it returns `true`, 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 (str_contains($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
?>
<h3>str_contains() returned true</h3>
<p>You are using Firefox</p>
<?php
} else {
?>
<h3>str_contains() returned false</h3>
<p>You are not using Firefox</p>
<?php
}
?>`

A sample output of this script may be:

    <h3>str_contains() returned true</h3>
    <p>You are using Firefox</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 str_contains(). In other words, it depends on whether the string `Firefox` was found or not.

# Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:

Example #1 A simple HTML form

    <form action="action.php" method="post">
        <label for="name">Your name:</label>
        <input name="name" id="name" type="text">

        <label for="age">Your age:</label>
        <input name="age" id="age" type="number">

        <button type="submit">Submit</button>
    </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 int 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.

# What's next?

With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives.

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

- Introduction — What is PHP and what can it do?
- A simple tutorial
  - Your first PHP-enabled page
  - Something Useful
  - Dealing with Forms
  - What's next?

# Installation and Configuration

# General Installation Considerations

Before starting the installation, first you need to know what do you want to use PHP for. There are two main fields you can use PHP, as described in the What can PHP do? section:

- Websites and web applications (server-side scripting)
- Command line scripting

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; 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. 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 in using 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.

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 » https://www.php.net/downloads.php.

# Installation on Unix systems

## Table of Contents

- Installing from packages on Debian GNU/Linux and related distributions
- Installing from packages on GNU/Linux distributions that use DNF
- Installing from packages or ports on OpenBSD
- Installing from source on Unix and macOS systems
- CGI and command line setups
- Apache 2.x on Unix systems
- Nginx 1.4.x on Unix systems
- Lighttpd 1.4 on Unix systems
- LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
- Solaris specific installation tips

Most Unix (and Linux) operating systems and distributions have a packaged version of PHP and extensions available through their packaging system. There are sections with basic information on installing PHP using those systems.

For some distributions, there are also third-party repositories of packages that generally include a wider variety of available versions and extensions.

PHP can also be installed as a component of some third-party application servers .

Finally, PHP can always be installed from the source distributions, which allows the greatest flexibility in choosing what features, extensions, and server APIs to enable. There are sections with information about compiling and configuring PHP to use with different server APIs in particular.

## Installing from packages on Debian GNU/Linux and related distributions

While PHP can be installed from source, it is also available through packages from » Debian GNU/Linux. This is also true for other distributions based on Debian, such as Ubuntu, Kali Linux, and Linux Mint.

Warning

Builds from third-parties are considered unofficial and not directly supported by the PHP project. Any bugs encountered should be reported to the provider of those unofficial builds unless they can be reproduced using the builds from » the official download area.

The packages can be installed using either the apt or aptitude commands. This manual page uses these two commands interchangeably.

### Using APT

First, note that other related packages may be desired like `libapache-mod-php` 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 update.

Example #1 Debian Install Example with Apache 2

    # apt install php-common libapache2-mod-php php-cli

APT will automatically install the PHP module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:

Example #2 Stopping and starting Apache once PHP is installed

    # /etc/init.d/apache2 stop
    # /etc/init.d/apache2 start

### Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt command.

Example #3 Methods for listing additional PHP packages

    # apt-cache search php
    # apt search php | grep -i mysql
    # aptitude search php

The list of packages will include a large number of packages that includes basic PHP components, such as `php-cgi`, `php-cli`, and `php-dev`, as well as many PHP extensions. When extensions are installed, additional packages will be automatically installed as necessary to satisfy the dependencies of those packages.

Example #4 Install PHP with MySQL, cURL

    # apt install php-mysql php-curl

APT will automatically add the appropriate lines to the different php.ini related files like /etc/php/7.4/php.ini, /etc/php/7.4/conf.d/*.ini, etc. and depending on the extension will add entries similar to `extension=foo.so`. However, restarting the web server (like Apache) is required before these changes take affect.

### Common Problems

- If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
- If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.

## Installing from packages on GNU/Linux distributions that use DNF

While PHP can be installed from source, it is also available through packages on systems that use DNF, such as Red Hat Enterprise Linux, OpenSUSE, Fedora, CentOS, Rocky Linux, and Oracle Enterprise Linux.

Warning

Builds from third-parties are considered unofficial and not directly supported by the PHP project. Any bugs encountered should be reported to the provider of those unofficial builds unless they can be reproduced using the builds from » the official download area.

The packages can be installed using the dnf command.

### Installing packages

First, note that other related packages may be desired like `php-pear` for » PEAR, or `php-mysqlnd` for the MySQL extension.

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

Example #1 DNF Install Example

    # dnf install php php-common

DNF will automatically install the configuration for PHP for the web server, but it may need to be restarted in order for the changes to take effect. For example:

Example #2 Restarting Apache once PHP is installed

    # sudo systemctl restart httpd

### Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the dnf command.

Example #3 Methods for listing additional PHP packages

    # dnf search php

The list of packages will include a large number of packages that includes basic PHP components, such as `php-cli`, `php-fpm`, and `php-devel`, as well as many PHP extensions. When extensions are installed, additional packages will be automatically installed as necessary to satisfy the dependencies of those packages.

Example #4 Install PHP with MySQL, GD

    # dnf install php-mysqlnd php-gd

DNF will automatically add the appropriate lines to the different php.ini related files like /etc/php/8.3/php.ini, /etc/php/8.3/conf.d/*.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.

## Installing from packages or ports on OpenBSD

This section contains notes and hints specific to installing PHP on » OpenBSD.

### Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php, which contains the basic engine (plus fpm, gettext and iconv) and might be available in several versions to choose from. Next, take a look at the module packages, such as php-mysqli or php-imap. 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 php
    # pkg_add php-apache
    # pkg_add php-mysqli
      (install the PEAR libraries)
    # pkg_add pear

    Follow the instructions shown with each package!

      (to remove packages)
    # pkg_delete php
    # pkg_delete php-apache
    # pkg_delete php-mysqli
    # pkg_delete pear

Read the » packages(7) manual page for more information about binary packages on OpenBSD.

### Using Ports

You can also compile up PHP from source using the » ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP port is split into core and extensions. The extensions generate sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.

### Common Problems

- Apache and Nginx are no longer the default server on OpenBSD, but they can both be easily found in ports and packages. The new default server is also called 'httpd'.
- The default install of httpd runs inside a » chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories.
- The OpenBSD package for the » gd extension requires Xorg to be installed. Unless already installed at base install by adding the xbase.tgz file set, this can be added at post-installation (see » OpenBSD FAQ#4).

## Installing from source on Unix and macOS systems

Prerequisite software for compiling:

- » GNU make
- A C compiler (as of PHP 8.0.0, C99 compatibility is required; as of PHP 8.4.0, C11 compatibility is required)
- A web server
- Any module specific components (such as GD, PDF libs, etc.)

When building directly from Git sources or after custom modifications, these additional tools may be necessary:

- » autoconf:
  - PHP 7.3 and later: 2.68+
  - PHP 7.2: 2.64+
  - PHP 7.1 and earlier: 2.59+
- » re2c:
  - PHP 8.3 and later: 1.0.3+
  - PHP 8.2 and earlier: 0.13.4+
- » bison:
  - PHP 7.4 and later: 3.0.0+
  - PHP 7.3 and earlier: 2.4+ (including Bison 3.x)

For more detailed steps for compiling PHP from source, see the » README.md file in the source tarball.

The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. A list of available options along with short explanations can be shown by running ./configure --help. This manual documents the different options separately. The core options can be found in the appendix, while the different extension specific options are described on the reference pages.

After the configuration script was been run, PHP can be built using the make command. The Installation section of the frequently asked questions has further information about how to handle build problems.

> Note: Some Unix systems (such as OpenBSD and SELinux) may disallow mapping pages both writable and executable for security reasons, what is called » PaX MPROTECT or » W^X violation protection. This kind of memory mapping is necessary for PCRE's JIT support, so either PHP has to be built without PCRE's JIT support, or the binary has to be whitelisted by any means provided by the system.

> Note: Cross-compiling for ARM with the Android toolchain is currently not supported.

## CGI and command line setups

By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing. If you are running a web server that PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.

Warning

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

### Testing

If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.

### Using Variables

Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.

## Apache 2.x on Unix systems

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

Warning

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

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

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

There are currently two versions of Apache 2.x - there's 2.4 and 2.2. While there are various reasons for choosing each, 2.4 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.4 or 2.2. Note that Apache httpd 2.2 is officially End Of Life, and no new development or patches are being issued for it.

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

       tar -xzf httpd-2.x.NN.tar.gz

2. Likewise, obtain and unpack the PHP source:

       tar -xzf php-NN.tar.gz

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

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

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

       /usr/local/apache2/bin/apachectl start

   and stop the server to go on with the configuration for PHP:

       /usr/local/apache2/bin/apachectl stop

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

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

       cd ../php-NN
       ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-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.

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

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

   For PHP 8:

       LoadModule php_module modules/libphp.so

   For PHP 7:

       LoadModule php7_module modules/libphp7.so

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

       <FilesMatch \.php$>
           SetHandler application/x-httpd-php
       </FilesMatch>

   Or, if we wanted to allow `.php`, `.php2`, `.php3`, `.php4`, `.php5`, `.php6`, and `.phtml` files to be executed as PHP, but nothing else, we'd use this:

       <FilesMatch "\.ph(p[2-6]?|tml)$">
           SetHandler application/x-httpd-php
       </FilesMatch>

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

       <FilesMatch "\.phps$">
           SetHandler application/x-httpd-php-source
       </FilesMatch>

   `mod_rewrite` may be used to allow any arbitrary `.php` file to be displayed as syntax-highlighted source code, without having to rename or copy it to a `.phps` file:

       RewriteEngine On
       RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

   The php source filter should not be enabled on production systems, where it may expose confidential or otherwise sensitive information embedded in source code.

9. Use your normal procedure for starting the Apache server, e.g.:

       /usr/local/apache2/bin/apachectl start

   OR

       service httpd restart

Following the steps above you will have a running Apache2 web server with support for PHP as a `SAPI` module. Of course, there are many more configuration options available for Apache and PHP. For more information type ./configure --help in the corresponding source tree.

Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 3 above:

    --with-mpm=worker

This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail.

> Note:

> The Apache MultiViews FAQ discusses using multiviews with PHP.

> Note:

> To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module.

## Nginx 1.4.x on Unix systems

This documentation will cover installing and configuring PHP with PHP-FPM for a Nginx 1.4.x HTTP server.

This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at `/usr/local/nginx`. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order to translate this manual to your setup.

This guide will cover the basics of configuring an Nginx server to process PHP applications and serve them on port 80, it is recommended that you study the Nginx and PHP-FPM documentation if you wish to optimise your setup past the scope of this documentation.

Please note that throughout this documentation version numbers have been replaced with an 'x' to ensure this documentation stays correct in the future, please replace these as necessary with the corresponding version numbers.

1. It is recommended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.

2. Obtain and unpack the PHP source:

       tar zxf php-x.x.x

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

       cd ../php-x.x.x
       ./configure --enable-fpm --with-mysqli
       make
       sudo make install

4. Obtain and move configuration files to their correct locations

       cp php.ini-development /usr/local/php/php.ini
       cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
       cp sapi/fpm/php-fpm /usr/local/bin

5. It is important that we prevent Nginx from passing requests to the PHP-FPM backend if the file does not exist, allowing us to prevent arbitrarily script injection.

   We can fix this by setting the cgi.fix_pathinfo directive to `0` within our php.ini file.

   Load up php.ini:

       vim /usr/local/php/php.ini

   Locate `cgi.fix_pathinfo=` and modify it as follows:

       cgi.fix_pathinfo=0

6. php-fpm.conf must be modified to specify that php-fpm must run as the user www-data and the group www-data before we can start the service:

       vim /usr/local/etc/php-fpm.d/www.conf

   Find and modify the following:

       ; Unix user/group of processes
       ; Note: The user is mandatory. If the group is not set, the default user's group
       ;       will be used.
       user = www-data
       group = www-data

   The php-fpm service can now be started:

       /usr/local/bin/php-fpm

   This guide will not configure php-fpm any further, if you are interested in further configuring php-fpm then please consult the documentation.

7. Nginx must now be configured to support the processing of PHP applications:

       vim /usr/local/nginx/conf/nginx.conf

   Modify the default location block to be aware it must attempt to serve .php files:

       location / {
           root   html;
           index  index.php index.html index.htm;
       }

   The next step is to ensure that .php files are passed to the PHP-FPM backend. Below the commented default PHP location block, enter the following:

       location ~* \.php$ {
           fastcgi_index   index.php;
           fastcgi_pass    127.0.0.1:9000;
           include         fastcgi_params;
           fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
           fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
       }

   Restart Nginx.

       sudo /usr/local/nginx/sbin/nginx -s stop
       sudo /usr/local/nginx/sbin/nginx

8. Create a test file

       rm /usr/local/nginx/html/index.html
       echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php

   Now navigate to http://localhost. The phpinfo() should now be shown.

Following the steps above you will have a running Nginx web server with support for PHP as an `FPM` `SAPI` module. Of course there are many more configuration options available for Nginx and PHP. For more information type ./configure --help in the corresponding source tree.

## Lighttpd 1.4 on Unix systems

This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.

Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.

FastCGI is the preferred SAPI to connect PHP and Lighttpd. FastCGI is automagically enabled in php-cgi.

### Letting Lighttpd spawn php processes

To configure Lighttpd to connect to PHP and spawn FastCGI processes, edit lighttpd.conf. Sockets are preferred to connect to FastCGI processes on the local system.

Example #1 Partial lighttpd.conf

    server.modules += ( "mod_fastcgi" )

    fastcgi.server = ( ".php" =>
      ((
        "socket" => "/tmp/php.socket",
        "bin-path" => "/usr/local/bin/php-cgi",
        "bin-environment" => (
          "PHP_FCGI_CHILDREN" => "16",
          "PHP_FCGI_MAX_REQUESTS" => "10000"
        ),
        "min-procs" => 1,
        "max-procs" => 1,
        "idle-timeout" => 20
      ))
    )

The bin-path directive allows lighttpd to spawn FastCGI processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The `bin-environment` directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives `min-procs` and `max-procs` should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If `min-procs` is set to something greater than `1`, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).

### Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to make the process of spawning FastCGI processes easier.

### Spawning php-cgi

It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.

Example #2 Spawning FastCGI Responders

    #!/bin/sh

    # Location of the php-cgi binary
    PHP=/usr/local/bin/php-cgi

    # PID File location
    PHP_PID=/tmp/php.pid

    # Binding to an address
    #FCGI_BIND_ADDRESS=10.0.1.1:10000
    # Binding to a domain socket
    FCGI_BIND_ADDRESS=/tmp/php.sock

    PHP_FCGI_CHILDREN=16
    PHP_FCGI_MAX_REQUESTS=10000

    env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
           PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
           $PHP -b $FCGI_BIND_ADDRESS &

    echo $! > "$PHP_PID"

### Connecting to remote FCGI instances

FastCGI instances can be spawned on multiple remote machines in order to scale applications.

Example #3 Connecting to remote php-fastcgi instances

    fastcgi.server = ( ".php" =>
       (( "host" => "10.0.0.2", "port" => 1030 ),
        ( "host" => "10.0.0.3", "port" => 1030 ))
    )

## LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems

LiteSpeed PHP is an optimized compilation of PHP built to work with LiteSpeed products through the LiteSpeed SAPI. LSPHP runs as its own process and has its own standalone binary, which can be used as a simple command line binary to execute PHP scripts from the command line.

The LSAPI is a highly optimized API that allows communication between LiteSpeed and third party web engines. Its protocol is similar to FCGI, but is more efficient.

This documentation will cover installing and configuring PHP with LSAPI for a LiteSpeed Web Server and OpenLiteSpeed Web Server.

This guide will assume that either LSWS or OLS is installed with their default paths and flags. The default installation directory for both web servers is /usr/local/lsws and both can be run from the bin subdirectory.

Please note that throughout this documentation, version numbers have been replaced with an `x` to ensure this documentation stays correct in the future, please replace these, as necessary, with the corresponding version numbers.

1. To obtain and install either LiteSpeed Web Server or OpenLiteSpeed Web Server, visit the LiteSpeed Web Server documentation » install page or OpenLiteSpeed documentation » install page.

2. Obtain and unpack the php source:

       mkdir /home/php
       cd /home/php
       wget http://us1.php.net/get/php-x.x.x.tar.gz/from/this/mirror
       tar -zxvf php-x.x.x.tar.gz
       cd php-x.x.x

3. Configure and build PHP. This is where PHP can be customized with various options, such as which extensions will be enabled. Run ./configure --help for a list of available options. In the example, we'll use the default recommended configuration options for LiteSpeed Web Server:

       ./configure ... '--with-litespeed'
       make
       sudo make install

4. Checking The LSPHP Installation

   One of the simplest ways to check whether the installation of PHP was successful is to run the following code:

       cd /usr/local/lsws/fcgi-bin/
       ./lsphp5 -v

   This should return information about the new PHP build:

       PHP 5.6.17 (litespeed) (built: Mar 22 2016 11:34:19)
       Copyright (c) 1997-2014 The PHP Group
       Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

   Notice the `litespeed` in parenthesis. This means that the PHP binary has been built with LSAPI support.

Following the steps above, LiteSpeed / OpenLiteSpeed Web Server should now be running with support for PHP as an SAPI extension. There are many more configuration options available for LSWS / OLS and PHP. For more information, check out the LiteSpeed documentation about » PHP.

Using LSPHP from the command line:

LSPHP(LSAPI + PHP) command line mode is used to process PHP scripts running on a remote server that does not necessarily have a web server running. It is used to process PHP scripts residing on a local web server (separate). This setup is suitable for service scalability as PHP processing is offloaded to a remote server.

Start lsphp from the command line on a remote server: LSPHP is an executable and can be started manually and bound to IPv4, IPv6, or Unix domain socket addresses with the command line option -b socket_address

Examples:

Have LSPHP bind to port 3000 on all IPv4 and IPv6 addresses:

    /path/to/lsphp -b [::]:3000

Have LSPHP bind to port 3000 on all IPv4 addresses:

    /path/to/lsphp -b *:3000

Have LSPHP bind to address 192.168.0.2:3000:

    /path/to/lsphp -b 192.168.0.2:3000

Have LSPHP accept requests on Unix domain socket `/tmp/lsphp_manual.sock`:

    /path/to/lsphp -b /tmp/lsphp_manual.sock

Environment variables can be added before the LSPHP executable:

    PHP_LSAPI_MAX_REQUESTS=500 PHP_LSAPI_CHILDREN=35 /path/to/lsphp -b IP_address:port

Currently LiteSpeed PHP can be used with LiteSpeed Web Server, OpenLiteSpeed Web Server, and Apache mod_lsapi. For steps on server-side configuration, visit the documentation pages for » LiteSpeed Web Server and » OpenLiteSpeed.

LSPHP can be installed in several other ways as well.

CentOS: On CentOS, LSPHP can be installed from the LiteSpeed Repository or the Remi Repository using » RPM.

Debian: On Debian, LSPHP can be installed from the LiteSpeed Repository using » apt.

cPanel: Visit the respective » documentation page about how to install LSPHP with cPanel and LSWS/OLS using EasyApache 4.

Plesk: Plesk can be used with LSPHP on CentOS, CloudLinux, Debian, and Ubuntu, for more details on this, visit the respective » documentation page

## Solaris specific installation tips

This section contains notes and hints specific to installing PHP on Solaris systems.

### Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary.

For unpacking the PHP distribution you need

- tar
- gzip or
- bzip2

For compiling PHP you need

- gcc (recommended, other C compilers may work)
- make
- GNU sed

For building extra extensions or hacking the code of PHP you might also need

- re2c
- bison
- m4
- autoconf
- automake

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

### Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components. The Image Packaging System (IPS) for Solaris 11 Express also contains most of the required components for installation using the pkg command.

# Installation on macOS

## Table of Contents

- Installation on macOS using third-party packages
- Compiling PHP on macOS
- Using the bundled PHP prior to macOS Monterey

PHP was bundled with macOS in versions 10 and 11, but is not included in versions since macOS 12 (Monterey). Installation on recent versions either requires using packages from third-party sources, or compilation from source.

## Installation on macOS using third-party packages

There are a few pre-packaged and pre-compiled versions of PHP for macOS. 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.

An easy way to install PHP on macOS is with the » Homebrew packaging manager.

1. Install Homebrew by following the instructions on the website.

2. brew install php

The following alternative resources also offer easy to install packages and precompiled binaries for PHP on macOS:

- » MacPorts
- » Fink

## Compiling PHP on macOS

Use the Unix installation guide to compile PHP on macOS.

## Using the bundled PHP prior to macOS Monterey

PHP is bundled with macOS since macOS X (10.0.0) prior to macOS Monterey (12.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 macOS 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 macOS for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:

1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/httpd.conf Using `Finder` or `Spotlight` to find this file may prove difficult as by default it's private and owned by the `root` user.

   > Note: One way to open this is by using a Unix based text editor in the Terminal, for example `nano`, and because the file is owned by `root` we'll use the `sudo` command to open it (as `root`) so for example type the following into the `Terminal` Application (after, it will prompt for a password): `sudo nano /private/etc/apache2/httpd.conf` Noteworthy nano commands: `^w` (search), `^o` (save), and `^x` (exit) where `^` represents the Ctrl key.

   > Note: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.

2. With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):

       # LoadModule php5_module libexec/httpd/libphp5.so

       # AddModule mod_php5.c

   Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

3. Be sure the desired extensions will parse as PHP (examples: .php, .html and .inc).

   Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.

       <IfModule mod_php5.c>
           # If php is turned on, we respect .php and .phps files.
           AddType application/x-httpd-php .php
           AddType application/x-httpd-php-source .phps

           # Since most users will want index.php to work we
           # also automatically enable index.php
           <IfModule mod_dir.c>
               DirectoryIndex index.html index.php
           </IfModule>
       </IfModule>

   > Note:

   > Before Mac OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.

4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
5. Set the php.ini location or use the default A typical default location on macOS is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
6. Locate or set the `DocumentRoot` This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
7. Create a phpinfo() file

   The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:

   `<?php phpinfo(); ?>`
8. Restart Apache, and load the PHP file created above

   To restart, either execute `sudo apachectl graceful` in the shell or stop/start the "Personal Web Server" option in the macOS 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.

# Installation on Windows systems

## Table of Contents

- Recommended configuration on Windows systems
- Manual installation of pre-built binaries
- Installation for Apache 2.x on Windows systems
- Installation with IIS for Windows
- Third-party tools for installing PHP
- Building from source
- Running PHP on the command line on Windows systems

The official releases of PHP on Windows are recommended for production use, but PHP can also be built from source.

PHP can also be installed on Azure App Services (aka Microsoft Azure, Windows Azure, or (Windows) Azure Web Apps).

The Installation section of the frequently asked questions covers common installation and configuration issues that may be encountered.

## Recommended configuration on Windows systems

### OpCache

It is highly recommended to enable OpCache. This extension is included with PHP for Windows. It compiles and optimizes PHP scripts and caches them in memory so that they aren't compiled every time the page is loaded.

Set the php.ini to:

Example #1 Recommended OpCache configuration

    opcache.enable=On
    opcache.enable_cli=On

And restart the web server. For more info, see: OpCache Configuration

### WinCache

It is recommended to use WinCache if using IIS, especially if in a shared web hosting environment or using networked file storage (NAS). All PHP Applications automatically benefit from WinCache's file cache feature. File system operations are cached in memory. WinCache also can cache user objects in memory and share them between php.exe or php-cgi.exe processes (share objects between requests). Many major web applications have a plugin or extension or configuration option to make use of the WinCache user object cache. If high performance is needed, use the object cache in the applications. See: » https://pecl.php.net/package/WinCache to download a WinCache DLL (or WINCACHE_*.tgz) to the PHP extensions directory (extension_dir in the php.ini). Set the php.ini to:

Example #2 Recommended WinCache configuration

    extension=php_wincache.dll
    wincache.fcenabled=1
    wincache.ocenabled=1 ; removed as of wincache 2.0.0.0

For more info, see: WinCache Configuration

## Manual installation of pre-built binaries

### Installation requirements

PHP is only available for 32-bit x86 or 64-bit x64 systems, and does not currently run on Windows RT or Windows on ARM. As of version 8.3.0, PHP requires Windows 8 or Windows Server 2012. Versions after 7.2.0 required Windows 2008 R2 or Windows 7. Versions before 7.2.0 supported Windows 2008 and Vista.

PHP requires the Visual C runtime (CRT). Many other applications also require it, so it is likely to already be installed, but if it is not the Microsoft Visual C++ Redistributable for Visual Studio 2022 is suitable for use with all PHP versions and can be » downloaded from Microsoft.

The x86 CRT must be downloaded for use with PHP x86 builds and the x64 CRT for PHP x64 builds. If CRT is already installed, the installer will display a message that it was already installed and not make any changes. The CRT installer supports the /quiet and /norestart command-line switches, so the installation can be scripted.

### Where to download PHP binaries

Windows builds can be downloaded from » the PHP Windows website. All builds are optimized (PGO), and QA and GA releases are thoroughly tested.

### Pre-built PECL Extensions

Pre-built Windows versions of PECL extensions are distributed as DLL files on the extension's PECL page.

Binaries are not available for extensions that use features specific to other systems, like Unix, or depend on libraries that are not available on Windows.

### Build types

There are four types of PHP builds:

- Thread-Safe (TS) - for single process web servers, like Apache with mod_php

- Non-Thread-Safe (NTS) - for IIS and other FastCGI web servers (Apache with mod_fastcgi) and recommended for command-line scripts

- x86 - for 32-bit systems.

- x64 - for 64-bit systems.

## Installation for Apache 2.x on Windows systems

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

> Note:

> Please read the manual installation steps first!

It is strongly recommended to consult the » Apache Documentation to get have a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

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. PHP can be run as a handler, as a CGI, or under FastCGI.

> Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext should be converted to forward slashes: c:/directory/file.ext. A trailing slash may also be necessary for directories.

### Installing as an Apache handler

> Note: When using the apache2handler SAPI, the Thread Safe (TS) version of PHP must be used.

To load the PHP module for Apache 2.x, the following lines in the Apache httpd.conf configuration file must be inserted:

Example #1 PHP and Apache 2.x as handler

    # before PHP 8.0.0 the name of the module was php7_module
    LoadModule php_module "c:/php/php8apache2_4.dll"
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>
    # configure the path to php.ini
    PHPIniDir "C:/php"

> Note: The actual path to PHP must be substituted instead of C:/php/ in the above examples. Make sure that the file referenced in the `LoadModule` directive is at the specified location. Use php7apache2_4.dll for PHP 7, or php8apache2_4.dll for PHP 8.

### Running PHP as CGI

It is strongly recommended to consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, the php-cgi files will need to be placed in a directory designated as a CGI directory using the ScriptAlias directive.

A `#!` line will need to be placed in the PHP files, which point to the location of the PHP binary:

Example #2 PHP and Apache 2.x as CGI

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

Warning

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

### Running PHP under FastCGI

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

Obtain `mod_fcgid` from » https://www.apachelounge.com. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure the web server as shown below, taking care to adjust any paths to reflect how it is installed on the system:

Example #3 Configure Apache to run PHP as FastCGI

    LoadModule fcgid_module modules/mod_fcgid.so
    # Where is the php.ini file?
    FcgidInitialEnv PHPRC        "c:/php"
    <FilesMatch \.php$>
        SetHandler fcgid-script
    </FilesMatch>
    FcgidWrapper "c:/php/php-cgi.exe" .php

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

## Installation with IIS for Windows

### Installing IIS

Internet Information Services (IIS) is built in to Windows. On Windows Server, the IIS role can be added via the Server Manager. The CGI Role Feature needs to be included. On Windows Desktop, IIS has to be added via the Control Panel's Add/Remove Programs. The Microsoft documentation has » detailed instructions for enabling IIS. For development, » IIS/Express can also be used.

> Note: The Non-Thread Safe (NTS) version of PHP should be installed when using the FastCGI handler with IIS.

### Configuring PHP with IIS

In IIS Manager, Install FastCGI module and add a handler mapping for `.php` to the path to php-cgi.exe (not php.exe)

The APPCMD command line tool can be used to script IIS configuration.

### Example batch script

Example #1 Command line to configure IIS and PHP

    @echo off

    REM download .ZIP file of PHP build from http://windows.php.net/downloads/

    REM path to directory into which PHP .ZIP file was decompressed (no trailing \)
    set phppath=c:\php

    REM Clear current PHP handlers
    %windir%\system32\inetsrv\appcmd clear config /section:system.webServer/fastCGI
    REM The following command will generate an error message if PHP is not installed. This can be ignored.
    %windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /-[name='PHP_via_FastCGI']

    REM Set up the PHP handler
    %windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI /+[fullPath='%phppath%\php-cgi.exe']
    %windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /+[name='PHP_via_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='%phppath%\php-cgi.exe',resourceType='Unspecified']
    %windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /accessPolicy:Read,Script

    REM Configure FastCGI Variables
    %windir%\system32\inetsrv\appcmd set config -section:system.webServer/fastCgi /[fullPath='%phppath%\php-cgi.exe'].instanceMaxRequests:10000
    %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phppath%\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"
    %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phppath%\php-cgi.exe'].environmentVariables.[name='PHPRC',value='%phppath%\php.ini']"

## Third-party tools for installing PHP

Warning

Builds from third-parties are considered unofficial and not directly supported by the PHP project. Any bugs encountered should be reported to the provider of those unofficial builds unless they can be reproduced using the builds from » the official download area.

» XAMPP, » WampServer, and » Bitnami will also setup PHP applications for use with Apache on Windows.

## Building from source

See the » step-by-step build instructions for building with Visual Studio.

## Running PHP on the command line on Windows systems

This section contains notes and hints specific to getting PHP running from the command line for Windows.

> Note:

> Read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

    C:\php\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 the PHP version and display preferences) to the PATH environment variable. Read more about how to add the appropriate 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 the `.PHP` is placed will determine which script or program is executed when there are matching filenames. For example, placing `.PHP` before `.BAT` will cause the 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:\php\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:\\php\\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:\\php\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

    "C:\PHP Scripts\script" -arg1 -arg2 -arg3

or, if the `"C:\PHP Scripts"` directory is in the PATH environment variable:

    script -arg1 -arg2 -arg3

> Note:

> There is a small problem when intending to use this technique to run PHP scripts as a command line filter, like the example below:

>     dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3

> or

>     dir | script -arg1 -arg2 -arg3

> The script may simply hang and nothing is output. To get this operational, another registry change needs to be made:

>     Windows Registry Editor Version 5.00

>     [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
>     "InheritConsoleHandles"=dword:00000001

> Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788. As of Windows 10, this setting seems to be reversed, making the default install of Windows 10 support inherited console handles automatically. This » Microsoft forum post provides the explanation.

# Installation on Cloud Computing platforms

## Table of Contents

- Azure App Services
- Amazon EC2
- DigitalOcean

PHP installs on the cloud. To the PHP cloud!

## Azure App Services

PHP is frequently used on Azure App Services (aka Microsoft Azure, Windows Azure, Azure Web Apps).

Azure App Services manages pools of Windows Web Servers to host your web application, as an alternative to managing your own web server on your own Azure Compute VMs or other servers.

PHP is already enabled for your Azure App Services web site automatically. In the Azure Portal, select your web site, and you can choose which version of PHP to use. You may want to choose a newer version than the default.

As such, PHP and extensions will run on Azure App Services just as they will on other Windows servers. However, the management interface for Azure App Services is different:

- Azure portal: create, edit settings and delete web sites. » Azure Portal

- Kudu Dashboard: if the website has the URL `site_name.azurewebsites.net`, the Kudu dashboard is `https://site_name.scm.azurewebsites.net/`. The dashboard provides access to debugging capabilities, file management, and site extensions. Site extensions are an Azure mechanism to add extra programs, like PHP preview builds, to a website.

- You can not use IIS Manager, Server Manager, or RDP.

There is also a PHP SDK for programmatically using many Azure Services from your PHP code. See » Azure SDK for PHP.

For more information, see » Azure PHP Developer Center

### WinCache

WinCache is enabled by default on Azure App Services and it is recommended that you leave it enabled. If you install your own build of PHP, you should enable WinCache on that too.

### Custom PHP Build

You may upload your own PHP build to your D:\Home (C:\ is NOT writable). Then in the Azure Portal, set SCRIPT_PROCESSOR for .php to the absolute path of the php-cgi.exe file in your build.

## Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.

## DigitalOcean

DigitalOcean offers the following platforms to get PHP installed, and running web application on its cloud-hosting infrastructure.

- » Cloudways: One-click deployment of major PHP applications: WordPress, Magento, Drupal, Laravel, and more.

- » Droplet: Virtual machine boxes and installing » Lamp stack on a Linux server .

- » App Platform: Managed infrastructure to build, deploy, and scale apps quickly. Learn » how to run PHP application on the App Platform .

- » Functions: Serverless platform that allows developers to run code without provisioning or managing servers. PHP is supported natively. Learn » how to create serverless functions in PHP .

# FastCGI Process Manager (FPM)

## Table of Contents

- Installation
- Configuration

FPM (FastCGI Process Manager) is a primary PHP FastCGI implementation containing some features (mostly) useful for heavy-loaded sites.

These features include:

- advanced process management with graceful stop/start;

- pools that give ability to start workers with different uid/gid/chroot/environment, listening on different ports and using different php.ini (replaces safe_mode);

- configurable 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/ondemand/static child spawning;

- basic and extended status info (similar to Apache mod_status) with various formats like json, xml and openmetrics supported;

- php.ini-based config file.

## Installation

### Compiling from sources

In order to enable FPM in your PHP build you need to add `--enable-fpm` to your configure line.

There are several other FPM-specific configure options (all of them optional):

- `--with-fpm-user` - set FPM user (default - nobody).

- `--with-fpm-group` - set FPM group (default - nobody).

- `--with-fpm-systemd` - Activate systemd integration (default - no).

- `--with-fpm-acl` - Use POSIX Access Control Lists (default - no).

- `--with-fpm-apparmor` - Activate AppArmor integration (default - no).

- `--with-fpm-selinux` - Activate SELinux integration (default - no).

### Changelog

Version | Description
--- | ---
8.2.0 | The `--with-fpm-selinux` option was added.
8.0.0 | The `--with-fpm-apparmor` option was added.

## Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files.

### List of global php-fpm.conf directives

`pid` string

  Path to PID file. Default value: none.

`error_log` string

  Path to error log file. Default value: `#INSTALL_PREFIX#/log/php-fpm.log`. If it's set to "syslog", log is sent to syslogd instead of being written in a local file.

`log_level` string

  Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice.

`log_limit` int

  Log limit for the logged lines which allows to log messages longer than 1024 characters without wrapping. Default value: 1024. Available as of PHP 7.3.0.

`log_buffering` bool

  Experimental logging without extra buffering. Default value: yes. Available as of PHP 7.3.0.

`syslog.facility` string

  used to specify what type of program is logging the message. Default value: daemon.

`syslog.ident` string

  Prepended to every message. If you have multiple FPM instances running on the same server, you can change the default value which must suit common needs. Default value: php-fpm.

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

`process.max` int

  The maximum number of processes FPM will fork. This has been design to control the global number of processes when using dynamic PM within a lot of pools. Use it with caution. Default value: 0.

`process.priority` int

  Specify the nice(2) priority to apply to the master process (only if set). The value can vary from -19 (highest priority) to 20 (lower priority). Default value: not set.

`daemonize` bool

  Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. Default value: yes.

`rlimit_files` int

  Set open file descriptor rlimit for the master process. Default value: system defined value.

`rlimit_core` int

  Set max core size rlimit for the master process. Default value: 0.

`events.mechanism` string

  Specify the event mechanism FPM will use. The following is available: epoll, kqueue (*BSD), port (Solaris), poll, select. Default value: not set (auto detection preferring epoll and kqueue).

`systemd_interval` int

  When FPM is build with systemd integration, specify the interval, in second, between health report notification to systemd. Set to 0 to disable. Default value: 10.

### List of pool directives

With FPM you can run several pools of processes with different setting. These are settings that can be tweaked per pool.

`listen` string

  The address on which to accept FastCGI requests. Valid syntaxes are: 'ip.add.re.ss:port', 'port', '/path/to/unix/socket'. This option is mandatory for each pool.

`listen.backlog` int

  Set listen(2) backlog. A value of `-1` means maximum on BSD systems. Default value: `-1` (FreeBSD or OpenBSD) or `511` (Linux and other platforms).

`listen.allowed_clients` string

  List of IPv4 or IPv6 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: not set (any ip address accepted).

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

`listen.group` string

  See `listen.owner`.

`listen.mode` string

  See `listen.owner`.

`listen.acl_users` string

  When POSIX Access Control Lists are supported you can set them using this option. When set, `listen.owner` and `listen.group` are ignored. Value is a comma separated list of user names.

`listen.acl_groups` string

  See `listen.acl_users`. Value is a comma separated list of group names.

`listen.setfib` int

  Set the associated the route table (FIB). FreeBSD only. Default Value: `-1`. Since PHP 8.2.0.

`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) / 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_spawn_rate` int

  The number of rate to spawn child processes at once. Used only when `pm` is set to `dynamic`. Default value: 32

`pm.process_idle_timeout` mixed

  The number of seconds after which an idle process will be killed. Used only when `pm` is set to `ondemand`. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 10s.

`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_listen` string

  The address on which to accept FastCGI status request. This creates a new invisible pool that can handle requests independently. This is useful if the main pool is busy with long running requests because it is still possible to get the FPM status page before finishing the long running requests. The syntax is the same as for listen directive. Default value: none.

`pm.status_path` string

  The URI to view the FPM status page. This value must start with a leading slash (/). 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.

`process.priority` int

  Specify the nice(2) priority to apply to the worker process (only if set). The value can vary from -19 (highest priority) to 20 (lower priority). Default value: not set.

`process.dumpable` bool

  Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user or group is different than the master process user. It allows to create process core dump and ptrace the process for the pool user. Default Value: no. Since PHP 7.0.29, 7.1.17 and 7.2.5.

`prefix` string

  Specify prefix for path evaluation

`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_terminate_timeout_track_finished` bool

  The timeout set by request_terminate_timeout is not engaged after a fastcgi_finish_request or when application has finished and internal shutdown functions are being called. This directive will enable timeout limit to be applied unconditionally even in such cases. Default value: no. Since PHP 7.3.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.

`request_slowlog_trace_depth` int

  The depth of slowlog log stack trace. Default value: 20. Since PHP 7.2.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 for child processes in this pool. Default value: system defined value.

`rlimit_core` int

  Set max core size rlimit for child processes in this pool. 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` bool

  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.

`decorate_workers_output` bool

  Enable the output decoration for workers output when catch_workers_output is enabled. Default value: yes. Available as of PHP 7.3.0.

`clear_env` bool

  Clear environment in FPM workers. Prevents arbitrary environment variables from reaching FPM worker processes by clearing the environment in workers before env vars specified in this pool configuration are added. Default value: Yes.

`security.limit_extensions` string

  Limits the extensions of the main script FPM will allow to parse. This can prevent configuration mistakes on the web server side. You should only limit FPM to .php extensions to prevent malicious users to use other extensions to execute php code. Default value: .php .phar

`apparmor_hat` string

  If AppArmor is enabled, it allows to change a hat. Default value: not set

`access.log` string

  The access log file. Default value: not set

`access.format` string

  The access log format. Default value: `"%R - %u %t \"%m %r\" %s"`:

  Valid options
  Placeholder | Description
  --- | ---
  `%%` | The `%` character
  `%C` | %CPU used by the request. It can accept the following format: `%{user}C` for user CPU only, `%{system}C` for system CPU only, `%{total}C` for user + system CPU (default)
  `%d` | Time taken to serve the request. It can accept the following formats for precision: `%{seconds}d` (default), `%{milliseconds}d`, `%{microseconds}d`
  `%{name}e` | An environment variable (same as $_ENV or $_SERVER). A variable name must be specified within curly brackets to specify the name of the env variable. For example, server specifics like `%{REQUEST_METHOD}e` or `%{SERVER_PROTOCOL}e`, HTTP headers like `%{HTTP_HOST}e` or `%{HTTP_USER_AGENT}e`
  `%f` | Script filename
  `%l` | `Content-Length` of the request (for HTTP POST request only)
  `%m` | Request HTTP method
  `%M` | Peak of memory allocated by PHP. It can accept the following format: `%{bytes}M` (default), `%{kilobytes}M` `%{kilo}M`, `%{megabytes}M`, `%{mega}M`
  `%n` | Pool name
  `%{name}o` | Output header. The header name must be specified within curly brackets. For example: `%{Content-Type}o`, `%{X-Powered-By}o`, `%{Transfer-Encoding}o`
  `%p` | PID of the child that serviced the request
  `%P` | PID of the parent of the child that serviced the request
  `%q` | Query string
  `%Q` | The `'?'` character, or glue between `%q` and `%r`, if query string exists
  `%r` | Request URI without the query string, see `%q` and `%Q`
  `%R` | Remote IP address
  `%s` | Status (response code)
  `%t` | Server time the request was received. It can accept a `strftime(3)` format: `%d/%b/%Y:%H:%M:%S %z` (default) The `strftime(3)` format must be encapsulated in a `%{<strftime_format>}t` tag, e.g. for a ISO8601 formatted timestring, use: `%{%Y-%m-%dT%H:%M:%S%z}t`
  `%T` | Time the log was written (when the request finished). It can accept a `strftime(3)` format: `%d/%b/%Y:%H:%M:%S %z` (default). The `strftime(3)` format must be encapsulated in a `%{<strftime_format>}T` tag, e.g. for a ISO8601 formatted timestring, use: `%{%Y-%m-%dT%H:%M:%S%z}T`
  `%u` | Basic access authentication user, if specified in `Authorization` header

`access.suppress_path` array

  A list of request_uri values which should be filtered from the access log. Default value: not set. Since PHP 8.2.0.

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

PHP settings passed with `php_value` or `php_flag` will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.

Settings defined with `php_admin_value` and `php_admin_flag` cannot be overridden with ini_set().

PHP settings can be set in the webserver configuration.

Example #2 set PHP settings in nginx.conf

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

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

Caution

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

> Note: Pools are not a security mechanism, because they do not provide full separation; e.g. all pools would use a single OPcache instance.

# Installation of PECL extensions

## Table of Contents

- Introduction to PECL Installations
- Downloading PECL extensions
- Installing a PHP extension on Windows
- Compiling shared PECL extensions with the pecl command
- Compiling shared PECL extensions with phpize
- php-config
- Compiling PECL extensions statically into PHP

## Introduction to PECL Installations

> Note: PHP Installer for Extensions (PIE) is a new tool that will deprecate PECL. We recommend using PIE to install extensions. Find out more at » https://github.com/php/pie

» PECL is a repository of PHP extensions that are made available via the » PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.

These instructions assume `/path/to/php/src/dir/` 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.

A shared extension must be built, installed, and loaded to be useful. The methods described below provide 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.

## Downloading PECL extensions

> Note: PHP Installer for Extensions (PIE) is a new tool that will deprecate PECL. We recommend using PIE to install extensions. Find out more at » https://github.com/php/pie

There are several options for downloading PECL extensions, such as:

- The pecl install extname command downloads the extensions code automatically, so in this case, there is no need for a separate download.
- » https://pecl.php.net/ The PECL website contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: changelog, release notes, requirements, and other similar details.
- pecl download extname PECL extensions that have releases listed on the PECL website are available for download and installation using the » pecl command. Specific revisions may also be specified.
- git Many PECL extensions reside on GitHub.
- SVN Some PECL extensions also reside in SVN. A web-based view may be seen at » https://svn.php.net/pecl/. To download straight from SVN, the following sequence of commands may be used:

      $ svn checkout https://svn.php.net/repository/pecl/extname/trunk extname

- Windows downloads The PHP project compiles and offers Windows DLLs for most PECL extensions on the package page.

## Installing a PHP extension on Windows

There are two ways to load a PHP extension on Windows: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

To load an extension, it has to be available as a .dll file on the 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 the building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to the building from source documentation. If the DLL file is available neither with the PHP distribution nor in PECL, it may be necessary to compile it before the extension can be used.

### Where to find an extension?

PHP extensions are usually called php_*.dll (where the star represents the name of the extension), and they are located under the PHP\ext folder.

PHP ships with the extensions most useful to the majority of developers. They are called bundled extensions.

However, if the bundled extensions do not provide the needed functionality, one extension that does may still be found 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 developing PHP extensions.

If an extension has been developed for particular uses, it may be hosted on PECL so that others with the same needs can benefit from it. A nice side effect is that it's a good chance to receive feedback, (hopefully) thanks, bug reports and even fixes/patches. Before submitting an extension for hosting on PECL, please read » PECL submit.

### Which extension to download?

Many times, there will be several versions of each DLL available:

- Different version numbers (at least the first two numbers should match)
- Different thread safety settings
- Different processor architecture (x86, x64, ...)
- Different debugging settings
- `etc.`

Keep in mind that the extension settings should match all the settings of the PHP executable being used. The following PHP script will tell all about the PHP settings:

Example #1 phpinfo() call

`<?php
phpinfo();
?>`

Or from the command line, run:

    drive:\path\to\php\executable\php.exe -i

### Loading an extension

The most common way to load a PHP extension is to include it in the php.ini configuration file. Please note that many extensions are already present in the php.ini and that the semicolon only needs to be removed to activate them.

Note that, as of PHP 7.2.0, the extension name may be used instead of the extension's file name. As this is OS-independent and easier, especially for newcomers, it becomes the recommended way of specifying extensions to load. File names remain supported for compatibility with prior versions.

    ;extension=php_extname.dll

    extension=php_extname.dll

    ; As of PHP 7.2.0, prefer:
    extension=extname
    zend_extension=another_extension

However, some web servers are confusing because they do not use the php.ini located alongside the PHP executable. To find out where the actual php.ini resides, look for its path in phpinfo():

    Configuration File (php.ini) Path  C:\WINDOWS

    Loaded Configuration File   C:\Program Files\PHP\8.2\php.ini

After activating an extension, save php.ini, restart the web server, and check phpinfo() again. The new extension should now have its own section.

### Resolving problems

If the extension does not appear in phpinfo(), the logs should be checked to learn where the problem comes from.

If PHP is being used from the command line (CLI), the extension loading error can be read directly on the screen.

If PHP is being used with a web server, the location and format of the logs vary depending on the software. Please read the web server documentation to locate the logs, as it has nothing to do with PHP itself.

Common problems are the location of the DLL and the DLLs it depends on, 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, probably the DLL downloaded is not the right one. Try downloading the extension again with the proper settings. Again, phpinfo() can be of great help.

## Compiling shared PECL extensions with the pecl command

PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:

    $ pecl install extname

This will download the source for extname, compile, and install extname.so into the 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, a `beta` package may be installed using the following command:

    $ pecl install extname-beta

A specific version may also be installed using this variant:

    $ pecl install extname-0.1

> Note:

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

## Compiling shared PECL extensions with phpize

Sometimes, using the pecl installer is not an option. This could be because there is a firewall or because the extension being installed is unavailable as a PECL-compatible package, such as unreleased extensions from git. If such an extension needs to be built, the lower-level build tools can be used 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. The php.ini will need to be adjusted, and an `extension=extname.so` line will need to be added before the extension can be used.

If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to install also the appropriate development version of the PHP package as they often include the phpize command along with the proper header files to build PHP and its extensions.

Execute phpize --help to display additional usage information.

## php-config

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

When the extensions are being compiled, if multiple PHP versions are installed, the installation for which to build can be specified by using the --with-php-config option during configuration, setting the path of the respective php-config script.

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

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

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

## Compiling PECL extensions statically into PHP

It may be necessary to build a PECL extension statically into the PHP binary. To do this, the extension source will need to be placed under the /path/to/php/src/dir/ext/ directory, and the PHP build system will be required to regenerate its configure script.

    $ cd /path/to/php/src/dir/ext
    $ pecl download extname
    $ gzip -d < extname.tgz | tar -xvf -
    $ mv extname-x.x.x extname

This will result in the following directory:

    /path/to/php/src/dir/ext/extname

From here, PHP needs to be forced to rebuild the configure script, and then it can be built as normal:

    $ cd /path/to/php/src/dir
    $ rm configure
    $ ./buildconf --force
    $ ./configure --help
    $ ./configure --with-extname --enable-someotherext --with-foobar
    $ make
    $ make install

> Note: To run the buildconf script, the autoconf `2.68` and automake `1.4+` will be needed. Newer versions of autoconf may work but are not supported.

Whether --enable-extname or --with-extname is used depends on the extension. Typically, an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:

    $ ./configure --help | grep extname

# Installation of Composer and third-party packages

## Introduction to Composer

» Composer is a dependency manager for PHP that makes it possible to define third-party code packages used by a project that can then be easily installed and updated. It leverages the built-in class autoloading features of PHP, repositories of PHP packages such as » Packagist, and common project layout and coding conventions.

For example, if a PHP application or website needs to work with UUID values, » Ben Ramsey's `ramsey/uuid` package that implements the widely known and used types of UUIDs that are defined by » RFC 4122 could be used.

Briefly, this is done by creating a `composer.json` in the project, using Composer to install the latest version of the package, and including Composer's autoload script to make it available to the code. The » Composer "Basic Usage" documentation goes into this in more depth.

Example #1 `composer.json` that requires a single package

    {
        "require": {
            "ramsey/uuid": "^4.7"
        }
    }

# Installation of PIE and third-party extensions

## Introduction to PIE

» PIE is an installer for PHP, that makes it possible to install third-party PHP extensions, that can then be easily installed and updated. It leverages the PHP extension repository part of » Packagist to find the source code to build the extension, or a Windows binary to download, if it exists. If it downloads the source code, it also knows how to build and install it.

After » installing the requirements and PIE itself, you can then install the MongoDB extension by running the following on the command line.

Example #1 Installing the MongoDB extension with PIE

    pie install mongodb/mongodb-extension

The » "PIE Usage" documentation goes into this in more depth.

# Runtime Configuration

## Table of Contents

- The configuration file
- .user.ini files
- Where a configuration setting may be set
- How to change configuration settings

## The configuration file

The configuration file (php.ini) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI versions, it happens on every invocation.

php.ini is searched for in these locations (in order):

- SAPI module specific location (`PHPIniDir` directive in Apache 2, `-c` command line option in CGI and CLI)
- The PHPRC environment variable.
- The location of the `php.ini` file can be set for different versions of PHP. The root of the registry keys depends on 32- or 64-bitness of the installed OS and PHP. For 32-bit PHP on a 32-bit OS or a 64-bit PHP on a 64-bit OS use `[(HKEY_LOCAL_MACHINE\SOFTWARE\PHP]` for 32-bit version of PHP on a 64-bit OS use `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP]`] instead. For same bitness installation the following registry keys are examined in order: `[HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z]`, `[HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y]` and `[HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x]`, where x, y and z mean the PHP major, minor and release versions. For 32 bit versions of PHP on a 64 bit OS the following registry keys are examined in order: `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y.z]`, `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y]` and `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x]`, where x, y and z mean the PHP major, minor and release versions. If there is a value for `IniFilePath` in any of these keys, the first one found will be used as the location of the `php.ini` (Windows only).
- `[HKEY_LOCAL_MACHINE\SOFTWARE\PHP]` or `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP]`, value of `IniFilePath` (Windows only).
- Current working directory (except CLI).
- The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows).
- Windows directory (C:\windows or C:\winnt) (for Windows), or `--with-config-file-path` compile time option.

If php-SAPI.ini exists (where SAPI is the SAPI in use, so, for example, php-cli.ini or php-apache.ini), it is used instead of php.ini. The SAPI name can be determined with php_sapi_name().

> Note:

> The Apache web server changes the directory to root at startup, causing PHP to attempt to read php.ini from the root filesystem if it exists.

Environment variables can be referenced within configuration values in php.ini as shown below. As of PHP 8.3.0, a fallback value can be specified that will be used when the referenced variable is not defined.

Example #1 php.ini Environment Variables

    ; PHP_MEMORY_LIMIT is taken from environment
    memory_limit = ${PHP_MEMORY_LIMIT}
    ; If PHP_MAX_EXECUTION_TIME is not defined, it will fall back to 30
    max_execution_time = ${PHP_MAX_EXECUTION_TIME:-30}

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"

It is possible to refer to existing .ini variables from within .ini files. Example: `open_basedir = ${open_basedir} ":/new/dir"`.

### Scan directories

It is possible to configure PHP to scan for .ini files in a directory after reading php.ini. This can be done at compile time by setting the --with-config-file-scan-dir option. The scan directory can then be overridden at run time by setting the PHP_INI_SCAN_DIR environment variable.

It is possible to scan multiple directories by separating them with the platform-specific path separator (`;` on Windows, NetWare and RISC OS; `:` on all other platforms; the value PHP is using is available as the `PATH_SEPARATOR` constant). If a blank directory is given in PHP_INI_SCAN_DIR, PHP will also scan the directory given at compile time via --with-config-file-scan-dir.

Within each directory, PHP will scan all files ending in `.ini` in alphabetical order. A list of the files that were loaded, and in what order, is available by calling php_ini_scanned_files(), or by running PHP with the --ini option.

    Assuming PHP is configured with --with-config-file-scan-dir=/etc/php.d,
    and that the path separator is :...

    $ php
      PHP will load all files in /etc/php.d/*.ini as configuration files.

    $ PHP_INI_SCAN_DIR=/usr/local/etc/php.d php
      PHP will load all files in /usr/local/etc/php.d/*.ini as
      configuration files.

    $ PHP_INI_SCAN_DIR=:/usr/local/etc/php.d php
      PHP will load all files in /etc/php.d/*.ini, then
      /usr/local/etc/php.d/*.ini as configuration files.

    $ PHP_INI_SCAN_DIR=/usr/local/etc/php.d: php
      PHP will load all files in /usr/local/etc/php.d/*.ini, then
      /etc/php.d/*.ini as configuration files.

## .user.ini files

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 running PHP as Apache module, 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 `INI_PERDIR` and `INI_USER` will be recognized in .user.ini-style INI files.

Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.

user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is `.user.ini`.

user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).

## Where a configuration setting may be set

These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.

For example, the output_buffering setting is `INI_PERDIR` therefore it may not be set using ini_set(). However, the display_errors directive is `INI_ALL` therefore it may be set anywhere, including with ini_set().

INI mode constants
`INI_USER` (int)
  Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Entry can be set in .user.ini
`INI_PERDIR` (int)
  Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini
`INI_SYSTEM` (int)
  Entry can be set in php.ini or httpd.conf
`INI_ALL` (int)
  Entry can be set anywhere

## How to change configuration settings

### Running PHP as an Apache module

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.

There are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are `INI_ALL`, `INI_PERDIR`, or `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 `INI_ALL` and `INI_PERDIR` type directives. To clear a previously set value use `none` as the value.

  > Note: Don't use `php_value` to set boolean values. `php_flag` (see below) should be used instead.

`php_flag` `name` `on|off`

  Used to set a boolean configuration directive. Can be used only with `INI_ALL` and `INI_PERDIR` type directives.

`php_admin_value` `name` `value`

  Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with `php_admin_value` can not be overridden by .htaccess or ini_set(). To clear a previously set value use `none` as the value.

`php_admin_flag` `name` `on|off`

  Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with `php_admin_flag` can not be overridden by .htaccess or ini_set().

Example #1 Apache configuration example

    <IfModule mod_php5.c>
      php_value include_path ".:/usr/local/lib/php"
      php_admin_flag engine on
    </IfModule>
    <IfModule mod_php4.c>
      php_value include_path ".:/usr/local/lib/php"
      php_admin_flag engine on
    </IfModule>

Caution

PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as `E_ALL` or `E_NOTICE` to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini

### Changing PHP configuration via the Windows registry

When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key `HKLM\SOFTWARE\PHP\Per Directory Values`, in the sub-keys corresponding to the path names. For example, configuration values for the directory `c:\inetpub\wwwroot` would be stored in the key `HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot`. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in `INI_USER` can be set this way, `INI_PERDIR` values can not, because these configuration values are re-read for each request.

### Other interfaces to PHP

Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.

If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().

- General Installation Considerations
- Installation on Unix systems
  - Installing from packages on Debian GNU/Linux and related distributions
  - Installing from packages on GNU/Linux distributions that use DNF
  - Installing from packages or ports on OpenBSD
  - Installing from source on Unix and macOS systems
  - CGI and command line setups
  - Apache 2.x on Unix systems
  - Nginx 1.4.x on Unix systems
  - Lighttpd 1.4 on Unix systems
  - LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
  - Solaris specific installation tips
- Installation on macOS
  - Installation on macOS using third-party packages
  - Compiling PHP on macOS
  - Using the bundled PHP prior to macOS Monterey
- Installation on Windows systems
  - Recommended configuration on Windows systems
  - Manual installation of pre-built binaries
  - Installation for Apache 2.x on Windows systems
  - Installation with IIS for Windows
  - Third-party tools for installing PHP
  - Building from source
  - Running PHP on the command line on Windows systems
- Installation on Cloud Computing platforms
  - Azure App Services
  - Amazon EC2
  - DigitalOcean
- FastCGI Process Manager (FPM)
  - Installation
  - Configuration
- Installation of PECL extensions
  - Introduction to PECL Installations
  - Downloading PECL extensions
  - Installing a PHP extension on Windows
  - Compiling shared PECL extensions with the pecl command
  - Compiling shared PECL extensions with phpize
  - php-config
  - Compiling PECL extensions statically into PHP
- Introduction to Composer
- Introduction to PIE
- Runtime Configuration
  - The configuration file
  - .user.ini files
  - Where a configuration setting may be set
  - How to change configuration settings

# Language Reference

# Basic syntax

## Table of Contents

- PHP tags
- Escaping from HTML
- Instruction separation
- Comments

## PHP tags

When PHP processes a file, it recognizes the opening and closing tags, `<?php` and `?>`, to define the boundaries of PHP code execution. Content outside these tags is ignored by the PHP parser, allowing PHP to seamlessly embed in various document types.

A whitespace character (space, tab, or newline) must follow `<?php` to ensure proper token separation. Omitting this whitespace will result in a syntax error.

PHP also includes the short echo tag `<?=`, which is shorthand for `<?php echo`.

Example #1 PHP Opening and Closing Tags

`1. <?php echo 'if you want to serve PHP code in XHTML or XML documents,
use these tags'; ?>
2. You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.
3. <? echo 'this code is within short tags, but will only work '.
'if short_open_tag is enabled'; ?>`

Short tags (example three) are available by default but can be disabled either via the short_open_tag php.ini configuration file directive, or are disabled by default if PHP is built with the --disable-short-tags configuration.

> Note:

> As short tags can be disabled it is recommended to only use the normal tags (`<?php ?>` and `<?= ?>`) to maximise compatibility.

If a file ends with PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

Example #2 PHP Code Only File

`<?php
echo "Hello world\n";
// ... more code
echo "Last statement\n";
// the script ends here with no PHP closing tag`

## Escaping from HTML

Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates.

Example #1 Embedding PHP in HTML

`<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>`

This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for the immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example.

Using structures with conditions

Example #2 Advanced escaping using conditions

`<?php if ($expression == true): ?>
This will show if the expression is true.
<?php else: ?>
Otherwise this will show.
<?php endif; ?>`
In this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags; PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition that is not met.

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

> Note:

> If PHP is embeded within XML or XHTML the normal PHP `<?php ?>` must be used to remain compliant with the standards.

## Instruction separation

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

Example #1 Example showing the closing tag encompassing the trailing newline

`<?php echo "Some text"; ?>
No newline
<?= "But newline now" ?>`

The above example will output:

    Some textNo newline
    But newline now

Example #2 Examples of entering and exiting the PHP parser

`<?php
echo "This is a test\n";
?>
<?php echo "This is a test\n" ?>
<?php echo "We omitted the last closing tag\n";`

> Note:

> The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

## Comments

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

Example #1 Comments

`<?php
echo "This is a test\n"; // 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\n";
echo "One Final Test\n"; # 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.

Example #2 One Line Comments

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

'C' style comments end at the first `*/` encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

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

# Types

## Table of Contents

- Introduction
- Type System
- NULL
- Booleans
- Integers
- Floating point numbers
- Strings
- Numeric strings
- Arrays
- Objects
- Enumerations
- Resources
- Callables
- Mixed
- Void
- Never
- Relative class types
- Singleton types
- Iterables
- Type declarations
- Type Juggling

## Introduction

Every single expression in PHP has one of the following built-in types depending on its value:

- null
- bool
- int
- float (floating-point number)
- string
- array
- object
- callable
- resource

PHP is a dynamically typed language, which means that by default there is no need to specify the type of a variable, as this will be determined at runtime. However, it is possible to statically type some aspect of the language via the use of type declarations. Different types that are supported by PHP's type system can be found at the type system page.

Types restrict the kind of operations that can be performed on them. However, if an expression/variable is used in an operation which its type does not support, PHP will attempt to type juggle the value into a type that supports the operation. This process depends on the context in which the value is used. For more information, see the section on Type Juggling.

Tip

The type comparison tables may also be useful, as various examples of comparison between values of different types are present.

> Note: It is possible to force an expression to be evaluated to a certain type by using a type cast. A variable can also be type cast in-place by using the settype() function on it.

To check the value and type of an expression, use the var_dump() function. To retrieve the type of an expression, use the get_debug_type() function. However, to check if an expression is of a certain type use the `is_type` functions instead.

Example #1 Different Types

`<?php
$a_bool = true; // a bool
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an int
echo get_debug_type($a_bool), "\n";
echo get_debug_type($a_str), "\n";
// If this is an integer, increment it by four
if (is_int($an_int)) {
$an_int += 4;
}
var_dump($an_int);
// If $a_bool is a string, print it out
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>`

Output of the above example in PHP 8:

    bool
    string
    int(16)

> Note: Prior to PHP 8.0.0, where the get_debug_type() is not available, the gettype() function can be used instead. However, it doesn't use the canonical type names.

## Type System

PHP uses a nominal type system with a strong behavioral subtyping relation. The subtyping relation is checked at compile time whereas the verification of types is dynamically checked at run time.

PHP's type system supports various atomic types that can be composed together to create more complex types. Some of these types can be written as type declarations.

### Atomic types

Some atomic types are built-in types which are tightly integrated with the language and cannot be reproduced with user defined types.

The list of base types is:

- Built-in types
  - Scalar types:
    - bool type
    - int type
    - float type
    - string type
  - array type
  - object type
  - resource type
  - never type
  - void type
  - Relative class types: self, parent, and static
  - Singleton types
    - false
    - true
  - Unit types
    - null
- User-defined types (generally referred to as class-types)
  - Interfaces
  - Classes
  - Enumerations
- callable type

#### Scalar types

A value is considered scalar if it is of type int, float, string or bool.

#### User-defined types

It is possible to define custom types with interfaces, classes and enumerations. These are considered as user-defined types, or class-types. For example, a class called `Elephant` can be defined, then objects of type `Elephant` can be instantiated, and a function can request a parameter of type `Elephant`.

### Composite types

It is possible to combine multiple atomic types into composite types. PHP allows types to be combined in the following ways:

- Intersection of class-types (interfaces and class names).
- Union of types.

#### Intersection types

An intersection type accepts values which satisfies multiple class-type declarations, rather than a single one. Individual types which form the intersection type are joined by the `&` symbol. Therefore, an intersection type comprised of the types `T`, `U`, and `V` will be written as `T&U&V`.

#### Union types

A union type accepts values of multiple different types, rather than a single one. Individual types which form the union type are joined by the `|` symbol. Therefore, a union type comprised of the types `T`, `U`, and `V` will be written as `T|U|V`. If one of the types is an intersection type, it needs to be bracketed with parenthesis for it to written in DNF: `T|(X&Y)`.

### Type aliases

PHP supports two type aliases: mixed and iterable which corresponds to the union type of `object|resource|array|string|float|int|bool|null` and `Traversable|array` respectively.

> Note: PHP does not support user-defined type aliases.

## NULL

The null type is PHP's unit type, i.e. it has only one value: `null`.

Undefined, and unset() variables will resolve to the value `null`.

### Syntax

There is only one value of type null, and that is the case-insensitive constant `null`.

`<?php
$var = NULL;
?>`

### Casting to `null`

Warning

This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.

Casting a variable to null using `(unset) $var` will not remove the variable or unset its value. It will only return a `null` value.

### See Also

- is_null()
- unset()

## Booleans

The bool type only has two values, and is used to express a truth value. It can be either `true` or `false`.

### Syntax

To specify a bool literal, use the constants `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 bool value is passed on to a control structure.

`<?php
$action = "show_version";
$show_separators = true;
// == 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";
}
?>`

### Converting to boolean

To explicitly convert a value to bool, use the `(bool)` cast. Generally this is not necessary because when a value is used in a logical context it will be automatically interpreted as a value of type bool. For more information see the Type Juggling page.

When converting to bool, the following values are considered `false`:

- the boolean `false` itself
- the integer `0` (zero)
- the floats `0.0` and `-0.0` (zero)
- the empty string `""`, and the string `"0"`
- an array with zero elements
- the unit type NULL (including unset variables)
- Internal objects that overload their casting behaviour to bool. For example: SimpleXML objects created from empty elements without attributes, or GMP objects representing the value `0`.

Every other value is considered `true` (including resource and `NAN`).

Warning

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

Example #1 Casting to Boolean

`<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) "0"); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>`

## Integers

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

### See Also

- Floating point numbers
- Arbitrary precision / BCMath
- Arbitrary length integer / GMP

### Syntax

Ints can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation. The negation operator can be used to denote a negative int.

To use octal notation, precede the number with a `0` (zero). As of PHP 8.1.0, octal notation can also be preceded with `0o` or `0O`. To use hexadecimal notation precede the number with `0x`. To use binary notation precede the number with `0b`.

As of PHP 7.4.0, integer literals may contain underscores (`_`) between digits, for better readability of literals. These underscores are removed by PHP's scanner.

Example #1 Integer literals

`<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0o123; // octal number (as of PHP 8.1.0)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
$a = 1_234_567; // decimal number (as of PHP 7.4.0)
?>`

Formally, the structure for int literals is as of PHP 8.1.0 (previously, the `0o` or `0O` octal prefixes were not allowed, and prior to PHP 7.4.0 the underscores were not allowed):

    decimal     : [1-9][0-9]*(_[0-9]+)*
                | 0

    hexadecimal : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)*

    octal       : 0[oO]?[0-7]+(_[0-7]+)*

    binary      : 0[bB][01]+(_[01]+)*

    integer     : decimal
                | hexadecimal
                | octal
                | binary

The size of an int 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 ints. int size can be determined using the constant `PHP_INT_SIZE`, maximum value using the constant `PHP_INT_MAX`, and minimum value using the constant `PHP_INT_MIN`.

### Integer overflow

If PHP encounters a number beyond the bounds of the int type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the int type will return a float instead.

Example #2 Integer overflow

`<?php
$large_number = 50000000000000000000;
var_dump($large_number); // float(5.0E+19)
var_dump(PHP_INT_MAX + 1); // 32-bit system: float(2147483648)
// 64-bit system: float(9.2233720368548E+18)
?>`

### Integer division

There is no int division operator in PHP, to achieve this use the intdiv() function. `1/2` yields the float `0.5`. The value can be cast to an int to round it towards zero, or the round() function provides finer control over rounding.

Example #3 Divisions

`<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>`

### Converting to integer

To explicitly convert a value to int, use the `(int)` cast. 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 int argument. A value can also be converted to int with the intval() function.

If a resource is converted to an int, then the result will be the unique resource number assigned to the resource by PHP at runtime.

See also Type Juggling.

#### From booleans

`false` will yield `0` (zero), and `true` will yield `1` (one).

#### From floating point numbers

When converting from float to int, the number will be rounded towards zero. As of PHP 8.1.0, a deprecation notice is emitted when implicitly converting a non-integral float to int which loses precision.

Example #4 Casting from Float

`<?php
function foo($value): int {
return $value;
}
var_dump(foo(8.1)); // "Deprecated: Implicit conversion from float 8.1 to int loses precision" as of PHP 8.1.0
var_dump(foo(8.1)); // 8 prior to PHP 8.1.0
var_dump(foo(8.0)); // 8 in both cases
var_dump((int) 8.1); // 8 in both cases
var_dump(intval(8.1)); // 8 in both cases
?>`

If the float is beyond the boundaries of int (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 int result. No warning, not even a notice will be issued when this happens!

> Note:

> `NaN`, `Inf` and `-Inf` will always be zero when cast to int.

Warning

Never cast an unknown fraction to int, 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.

#### From strings

If the string is numeric or leading numeric then it will resolve to the corresponding integer value, otherwise it is converted to zero (`0`).

#### From NULL

`null` is always converted to zero (`0`).

#### From other types

Caution

The behaviour of converting to int is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.

## Floating point numbers

Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

`<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
$d = 1_234.567; // as of PHP 7.4.0
?>`

Formally as of PHP 7.4.0 (previously, underscores have not been allowed):

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

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

Warning

# Floating point precision

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

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like `0.1` or `0.7`, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, `floor((0.1+0.7)*10)` will usually return `7` instead of the expected `8`, since the internal representation will be something like `7.9999999999999991118...`.

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

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

### Converting to float

#### From strings

If the string is numeric or leading numeric then it will resolve to the corresponding float value, otherwise it is converted to zero (`0`).

#### From other types

For values of other types, the conversion is performed by converting the value to int first and then to float. See Converting to integer for more information.

> Note:

> As certain types have undefined behavior when converting to int, this is also the case when converting to float.

### Comparing floats

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

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

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

Example #1 Comparing Floats

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

### NaN

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

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

## Strings

A string is a 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: On 32-bit builds, a string can be as large as up to 2GB (2147483647 bytes maximum)

### Syntax

A string literal can be specified in four different ways:

- single quoted
- double quoted
- heredoc syntax
- nowdoc syntax

#### Single quoted

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

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

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

Example #1 Syntax Variants

`<?php
echo 'this is a simple string', PHP_EOL;
echo 'You can also have embedded newlines in
strings this way as it is
okay to do', PHP_EOL;
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"', PHP_EOL;
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?', PHP_EOL;
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?', PHP_EOL;
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline', PHP_EOL;
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either', PHP_EOL;
?>`

#### Double quoted

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

Escaped characters
Sequence | Meaning
--- | ---
`\n` | linefeed (LF or 0x0A (10) in ASCII)
`\r` | carriage return (CR or 0x0D (13) in ASCII)
`\t` | horizontal tab (HT or 0x09 (9) in ASCII)
`\v` | vertical tab (VT or 0x0B (11) in ASCII)
`\e` | escape (ESC or 0x1B (27) in ASCII)
`\f` | form feed (FF or 0x0C (12) in ASCII)
`\\` | backslash
`\$` | dollar sign
`\"` | double-quote
`\[0-7]{1,3}` | Octal: the sequence of characters matching the regular expression `[0-7]{1,3}` is a character in octal notation (e.g. `"\101" === "A"`), which silently overflows to fit in a byte (e.g. `"\400" === "\000"`)
`\x[0-9A-Fa-f]{1,2}` | Hexadecimal: the sequence of characters matching the regular expression `[0-9A-Fa-f]{1,2}` is a character in hexadecimal notation (e.g. `"\x41" === "A"`)
`\u{[0-9A-Fa-f]+}` | Unicode: the sequence of characters matching the regular expression `[0-9A-Fa-f]+` is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation. The braces are required in the sequence. E.g. `"\u{41}" === "A"`

As in single quoted strings, escaping any other character will result in the backslash being printed too.

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

#### Heredoc

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

The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.

Also, the closing 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.

Example #2 Basic Heredoc example as of PHP 7.3.0

`<?php
// no indentation
echo <<<END
a
b
c
\n
END;
// 4 spaces of indentation
echo <<<END
a
b
c
END;`

Output of the above example in PHP 7.3:

          a
         b
        c

      a
     b
    c

If the closing identifier is indented further than any lines of the body, then a ParseError will be thrown:

Example #3 Closing identifier must not be indented further than any lines of the body

`<?php
echo <<<END
a
b
c
END;`

Output of the above example in PHP 7.3:

    Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4

If the closing identifier is indented, tabs can be used as well, however, tabs and spaces must not be intermixed regarding the indentation of the closing identifier and the indentation of the body (up to the closing identifier). In any of these cases, a ParseError will be thrown. These whitespace constraints have been included because mixing tabs and spaces for indentation is harmful to legibility.

Example #4 Different indentation for body (spaces) closing identifier

`<?php
// All the following code do not work.
// different indentation for body (spaces) ending marker (tabs)
{
echo <<<END
a
END;
}
// mixing spaces and tabs in body
{
echo <<<END
a
END;
}
// mixing spaces and tabs in ending marker
{
echo <<<END
a
END;
}`

Output of the above example in PHP 7.3:

    Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8

The closing identifier for the body string is not required to be followed by a semicolon or newline. For example, the following code is allowed as of PHP 7.3.0:

Example #5 Continuing an expression after a closing identifier

`<?php
$values = [<<<END
a
b
c
END, 'd e f'];
var_dump($values);`

Output of the above example in PHP 7.3:

    array(2) {
      [0] =>
      string(11) "a
      b
        c"
      [1] =>
      string(5) "d e f"
    }

Warning

If the closing identifier was found at the start of a line, then regardless of whether it was a part of another word, it may be considered as the closing identifier and causes a ParseError.

Example #6 Closing identifier in body of the string tends to cause ParseError

`<?php
$values = [<<<END
a
b
END ING
END, 'd e f'];`

Output of the above example in PHP 7.3:

    Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 5

To avoid this problem, it is safe to follow the simple rule: do not choose a word that appears in the body of the text as a closing identifier.

Warning

Prior to PHP 7.3.0, 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 macOS. 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.

Example #7 Invalid example, prior to PHP 7.3.0

`<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
// Identifier must not be indented
?>`

Example #8 Valid example, even prior to PHP 7.3.0

`<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>`

Heredocs containing variables can not be used for initializing class properties.

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 #9 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 __construct()
{
$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 #10 Heredoc in arguments example

`<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>`

It's possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #11 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;
}
?>`

The opening Heredoc identifier may optionally be enclosed in double quotes:

Example #12 Using double quotes in Heredoc

`<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>`

#### Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no String interpolation 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 #13 Nowdoc string quoting example

`<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;`

The above example will output:

    Example of string spanning multiple lines
    using nowdoc syntax. Backslashes are always treated literally,
    e.g. \\ and \'.

Example #14 Nowdoc string quoting example with variables

`<?php
class foo
{
public $foo;
public $bar;
function __construct()
{
$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': \x41

Example #15 Static data example

`<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>`

#### String interpolation

When a string is specified in double quotes or with heredoc, variables can be substituted within it.

There are two types of syntax: a basic one and an advanced one. The basic 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.

##### Basic syntax

If a dollar sign (`$`) is encountered, the characters that follow it which can be used in a variable name will be interpreted as such and substituted.

Example #16 String Interpolation

`<?php
$juice = "apple";
echo "He drank some $juice juice." . PHP_EOL;
?>`

The above example will output:

    He drank some apple juice.

Formally, the structure for the basic variable substitution syntax is as follows:

    string-variable::
         variable-name   (offset-or-property)?
       | ${   expression   }

    offset-or-property::
         offset-in-string
       | property-in-string

    offset-in-string::
         [   name   ]
       | [   variable-name   ]
       | [   integer-literal   ]

    property-in-string::
         ->  name

    variable-name::
         $   name

    name::
         [a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*

Warning

The `${ expression }` syntax is deprecated as of PHP 8.2.0, as it can be interpreted as variable variables:

`<?php
const foo = 'bar';
$foo = 'foo';
$bar = 'bar';
var_dump("${foo}");
var_dump("${(foo)}");
?>`

Output of the above example in PHP 8.2:

    Deprecated: Using ${var} in strings is deprecated, use {$var} instead in file on line 6

    Deprecated: Using ${expr} (variable variables) in strings is deprecated, use {${expr}} instead in file on line 9
    string(3) "foo"
    string(3) "bar"

The above example will output:

    string(3) "foo"
    string(3) "bar"

The advanced string interpolation syntax should be used instead.

> Note: If it is not possible to form a valid name the dollar sign remains as verbatim in the string:

> `<?php
> echo "No interpolation $ has happened\n";
> echo "No interpolation $\n has happened\n";
> echo "No interpolation $2 has happened\n";
> ?>`

> The above example will output:

>     No interpolation $  has happened
>     No interpolation $
>      has happened
>     No interpolation $2 has happened

Example #17 Interpolating the value of the first dimension of an array or property

`<?php
$juices = array("apple", "orange", "string_key" => "purple");
echo "He drank some $juices[0] juice.";
echo PHP_EOL;
echo "He drank some $juices[1] juice.";
echo PHP_EOL;
echo "He drank some $juices[string_key] juice.";
echo PHP_EOL;
class A {
public $s = "string";
}
$o = new A();
echo "Object value: $o->s.";
?>`

The above example will output:

    He drank some apple juice.
    He drank some orange juice.
    He drank some purple juice.
    Object value: string.

> Note: The array key must be unquoted, and it is therefore not possible to refer to a constant as a key with the basic syntax. Use the advanced syntax instead.

As of PHP 7.1.0 also negative numeric indices are supported.

Example #18 Negative numeric indices

`<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>`

The above example will output:

    The character at index -2 is n.
    Changing the character at index -3 to o gives strong.

For anything more complex, the advanced syntax must be used.

##### Advanced (curly) syntax

The advanced syntax permits the interpolation of variables with arbitrary accessors.

Any scalar variable, array element or object property (static or not) with a string representation can be included via this syntax. The expression is written the same way as it would appear outside the string, and then wrapped 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:

Example #19 Curly Syntax

`<?php
const DATA_KEY = 'const-key';
$great = 'fantastic';
$arr = [
'1',
'2',
'3',
[41, 42, 43],
'key' => 'Indexed value',
'const-key' => 'Key with minus sign',
'foo' => ['foo1', 'foo2', 'foo3']
];
// Won't work, outputs: This is { fantastic}
echo "This is { $great}" . PHP_EOL;
// Works, outputs: This is fantastic
echo "This is {$great}" . PHP_EOL;
// To show curly braces in the output:
echo "This is {{$great}}" . PHP_EOL;
class Square {
public $width;
public function __construct(int $width) { $this->width = $width; }
}
$square = new Square(5);
// Works
echo "This square is {$square->width}00 centimeters wide." . PHP_EOL;
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}" . PHP_EOL;
// Works
echo "This works: {$arr[3][2]}" . PHP_EOL;
echo "This works: {$arr[DATA_KEY]}" . PHP_EOL;
// When using multidimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][2]}" . PHP_EOL;
echo "This works: {$obj->values[3]->name}" . PHP_EOL;
echo "This works: {$obj->$staticProp}" . PHP_EOL;
// Won't work, outputs: C:\directory\{fantastic}.txt
echo "C:\directory\{$great}.txt" . PHP_EOL;
// Works, outputs: C:\directory\fantastic.txt
echo "C:\\directory\\{$great}.txt" . PHP_EOL;
?>`

> Note: As this syntax allows arbitrary expressions it is possible to use variable variables within the advanced syntax.

#### String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

> Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted `E_NOTICE` for reading (yielding an empty string) and `E_WARNING` for writing (leaving the string untouched).

> Note: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits `E_WARNING`. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte.

Warning

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

> Note: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array.

Example #20 Some string examples

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

String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.

Example #21 Example of Illegal String Offsets

`<?php
$str = 'abc';
$keys = [ '1', '1.0', 'x', '1x' ];
foreach ($keys as $keyToTry) {
var_dump(isset($str[$keyToTry]));
try {
var_dump($str[$keyToTry]);
} catch (TypeError $e) {
echo $e->getMessage(), PHP_EOL;
}
echo PHP_EOL;
}
?>`

The above example will output:

    bool(true)
    string(1) "b"

    bool(false)
    Cannot access offset of type string on string

    bool(false)
    Cannot access offset of type string on string

    bool(false)

    Warning: Illegal string offset "1x" in Standard input code on line 10
    string(1) "b"

> Note:

> Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using `[]` or `{}` silently returns `null`.

> Note:

> Characters within string literals can be accessed using `[]` or `{}`.

> Note:

> Accessing characters within string literals using the `{}` syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

### Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (Sodium and Hash).

Finally, see also the character type functions.

### Converting to string

A value can be converted to a string using the `(string)` cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A bool `true` value is converted to the string `"1"`. bool `false` is converted to `""` (the empty string). This allows conversion back and forth between bool and string values.

An int 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:

> As of PHP 8.0.0, the decimal point character is always a period ("`.`"). Prior to PHP 8.0.0, 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.

In order to convert objects to string, the magic method __toString must be used.

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.

### Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value `0` (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string `"á"` equivalent to `"\xE1"` (ISO-8859-1), `"\xC3\xA1"` (UTF-8, C form), `"\x61\xCC\x81"` (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicitly declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

- Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
- Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension.
- Others use the current locale (see setlocale()), but operate byte-by-byte.
- Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the `u` modifier is used).

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.

## Numeric strings

A PHP string is considered numeric if it can be interpreted as an int or a float.

Formally as of PHP 8.0.0:

    WHITESPACES      \s*
    LNUM             [0-9]+
    DNUM             ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
    EXPONENT_DNUM    (({LNUM} | {DNUM}) [eE][+-]? {LNUM})
    INT_NUM_STRING   {WHITESPACES} [+-]? {LNUM} {WHITESPACES}
    FLOAT_NUM_STRING {WHITESPACES} [+-]? ({DNUM} | {EXPONENT_DNUM}) {WHITESPACES}
    NUM_STRING       ({INT_NUM_STRING} | {FLOAT_NUM_STRING})

PHP also has a concept of leading numeric strings. This is simply a string which starts like a numeric string followed by any characters.

> Note:

> Any string that contains the letter `E` (case insensitive) bounded by numbers will be seen as a number expressed in scientific notation. This can produce unexpected results.

> Example #1 Scientific Notation Comparisons

> `<?php
> var_dump("0D1" == "000"); // false, "0D1" is not scientific notation
> var_dump("0E1" == "000"); // true, "0E1" is 0 * (10 ^ 1), or 0
> var_dump("2E1" == "020"); // true, "2E1" is 2 * (10 ^ 1), or 20
> ?>`

### Strings used in numeric contexts

When a string needs to be evaluated as number (e.g. arithmetic operations, int type declaration, etc.) the following steps are taken to determine the outcome:

1. If the string is numeric, resolve to an int if the string is an integer numeric string and fits into the limits of the int type limits (as defined by `PHP_INT_MAX`), otherwise resolve to a float.
2. If the context allows leading numeric strings and the string is one, resolve to an int if the leading part of the string is an integer numeric string and fits into the limits of the int type limits (as defined by `PHP_INT_MAX`), otherwise resolve to a float. Additionally an error of level `E_WARNING` is raised.
3. The string is not numeric, throw a TypeError.

### Behavior prior to PHP 8.0.0

Prior to PHP 8.0.0, a string was considered numeric only if it had leading whitespaces, if it had trailing whitespaces then the string was considered to be leading numeric.

Prior to PHP 8.0.0, when a string was used in a numeric context it would perform the same steps as above with the following differences:

- The usage of a leading numeric string would raise an `E_NOTICE` instead of an `E_WARNING`.
- If the string is not numeric, an `E_WARNING` was raised and the value `0` would be returned.

Prior to PHP 7.1.0, neither `E_NOTICE` nor `E_WARNING` was raised.
`<?php
$foo = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // TypeError as of PHP 8.0.0, $foo is integer (1) previously
$foo = 1 + "bob3"; // TypeError as of PHP 8.0.0, $foo is integer (1) previously
$foo = 1 + "10 Small Pigs"; // $foo is integer (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously
$foo = "10.0 pigs " + 1; // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously
$foo = "10.0 pigs " + 1.0; // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously
?>`

## Arrays

For a list of all array functions, see the array functions chapter in the documentation.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

### Syntax

#### Specifying with array()

An array can be created using the array() language construct. It takes any number of comma-separated `key => value` pairs as arguments.

    array(
        key  => value,
        key2 => value2,
        key3 => value3,
        ...
    )

The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. `array(1, 2)` is preferred over `array(1, 2, )`. For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.

> Note:

> A short array syntax exists which replaces `array()` with `[]`.

Example #1 A simple array

`<?php
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array2 = [
"foo" => "bar",
"bar" => "foo",
];
var_dump($array1, $array2);
?>`

The key can either be an int or a string. The value can be of any type.

Additionally the following key casts will occur:

- Strings containing valid decimal ints, unless the number is preceded by a `+` sign, will be cast to the int type. E.g. the key `"8"` will actually be stored under `8`. On the other hand `"08"` will not be cast, as it isn't a valid decimal integer.
- Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key `8.7` will actually be stored under `8`.
- Bools are cast to ints, too, i.e. the key `true` will actually be stored under `1` and the key `false` under `0`.
- Null will be cast to the empty string, i.e. the key `null` will actually be stored under `""`.
- Arrays and objects can not be used as keys. Doing so will result in a warning: `Illegal offset type`.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Example #2 Type Casting and Overwriting example

`<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>`

The above example will output:

    array(1) {
      [1]=>
      string(1) "d"
    }

As all the keys in the above example are cast to `1`, the value will be overwritten on every new element and the last assigned value `"d"` is the only one left over.

PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

Example #3 Mixed int 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 int 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`.

Example #6 Complex Type Casting and Overwriting example

This example includes all variations of type casting of keys and overwriting of elements.

`<?php
$array = array(
1 => 'a',
'1' => 'b', // the value "a" will be overwritten by "b"
1.5 => 'c', // the value "b" will be overwritten by "c"
-1 => 'd',
'01' => 'e', // as this is not an integer string it will NOT override the key for 1
'1.5' => 'f', // as this is not an integer string it will NOT override the key for 1
true => 'g', // the value "c" will be overwritten by "g"
false => 'h',
'' => 'i',
null => 'j', // the value "i" will be overwritten by "j"
'k', // value "k" is assigned the key 2. This is because the largest integer key before that was 1
2 => 'l', // the value "k" will be overwritten by "l"
);
var_dump($array);
?>`

The above example will output:

    array(7) {
      [1]=>
      string(1) "g"
      [-1]=>
      string(1) "d"
      ["01"]=>
      string(1) "e"
      ["1.5"]=>
      string(1) "f"
      [0]=>
      string(1) "h"
      [""]=>
      string(1) "j"
      [2]=>
      string(1) "l"
    }

Example #7 Negative index example

When assigning a negative integer key `n`, PHP will take care to assign the next key to `n+1`.

`<?php
$array = [];
$array[-5] = 1;
$array[] = 2;
var_dump($array);
?>`

The above example will output:

    array(2) {
      [-5]=>
      int(1)
      [-4]=>
      int(2)
    }

Warning

Prior to PHP 8.3.0, assigning a negative integer key `n` would assign the next key to `0`, the previous example would therefore output:

    array(2) {
      [-5]=>
      int(1)
      [0]=>
      int(2)
    }

#### Accessing array elements with square bracket syntax

Array elements can be accessed using the `array[key]` syntax.

Example #8 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:

> Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. `$array[42]` and `$array{42}` would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Example #9 Array dereferencing

`<?php
function getArray() {
return array(1, 2, 3);
}
$secondElement = getArray()[1];
var_dump($secondElement);
?>`

> Note:

> Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an `E_WARNING`-level error message (`E_NOTICE`-level prior to PHP 8.0.0) will be issued, and the result will be `null`.

> Note:

> Array dereferencing a scalar value which is not a string yields `null`. Prior to PHP 7.4.0, that did not issue an error message. As of PHP 7.4.0, this issues `E_NOTICE`; as of PHP 8.0.0, this issues `E_WARNING`.

#### Creating/modifying with square bracket syntax

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

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

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

If $arr doesn't exist yet or is set to `null` or `false`, 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 a variable by a direct assignment.

> Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.

> Note: As of PHP 8.1.0, creating a new array from `false` value is deprecated. Creating a new array from `null` and undefined values is still allowed.

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.

Example #10 Using Square Brackets with Arrays

`<?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
var_dump($arr);
unset($arr); // This deletes the whole array
var_dump($arr);
?>`

> Note:

> As mentioned above, if no key is specified, the maximum of the existing int indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no int 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
>     )

#### Array destructuring

Arrays can be destructured using the `[]` (as of PHP 7.1.0) or list() language constructs. These constructs can be used to destructure an array into distinct variables.

Example #11 Array Destructuring

`<?php
$source_array = ['foo', 'bar', 'baz'];
[$foo, $bar, $baz] = $source_array;
echo $foo, PHP_EOL; // prints "foo"
echo $bar, PHP_EOL; // prints "bar"
echo $baz, PHP_EOL; // prints "baz"
?>`

Array destructuring can be used in `foreach` to destructure a multi-dimensional array while iterating over it.

Example #12 Array Destructuring in Foreach

`<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];
foreach ($source_array as [$id, $name]) {
echo "{$id}: '{$name}'\n";
}
?>`

Array elements will be ignored if the variable is not provided. Array destructuring always starts at index `0`.

Example #13 Ignoring Elements

`<?php
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[, , $baz] = $source_array;
echo $baz; // prints "baz"
?>`

As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified.

Example #14 Destructuring Associative Arrays

`<?php
$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];
// Assign the element at index 'baz' to the variable $three
['baz' => $three] = $source_array;
echo $three, PHP_EOL; // prints 3
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[2 => $baz] = $source_array;
echo $baz, PHP_EOL; // prints "baz"
?>`

Array destructuring can be used for easy swapping of two variables.

Example #15 Swapping Two Variable

`<?php
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a, PHP_EOL; // prints 2
echo $b, PHP_EOL; // prints 1
?>`

> Note:

> The spread operator (`...`) is not supported in assignments.

> Note:

> Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an `E_WARNING`-level error message (`E_NOTICE`-level prior to PHP 8.0.0) will be issued, and the result will be `null`.

> Note:

> Destructuring a scalar value assigns `null` to all variables.

### Useful functions

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

> Note:

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

> Example #16 Unsetting Intermediate Elements

> `<?php
> $a = array(1 => 'one', 2 => 'two', 3 => 'three');
> /* will produce an array that would have been defined as
> $a = array(1 => 'one', 3 => 'three');
> and NOT
> $a = array(1 => 'one', 2 =>'three');
> */
> unset($a[2]);
> var_dump($a);
> $b = array_values($a);
> // Now $b is array(0 => 'one', 1 =>'three')
> var_dump($b);
> ?>`

The `foreach` control structure exists specifically for arrays. It provides an easy way to traverse an array.

### Array do's and don'ts

#### Why is `$foo[bar]` wrong?

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

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

This is wrong, but it works. The reason is that this code has an undefined constant (`bar`) rather than a string (`'bar'` - notice the quotes). 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.

Warning

The fallback to treat an undefined constant as bare string issues an error of level `E_NOTICE`. This has been deprecated as of PHP 7.2.0, and issues an error of level `E_WARNING`. As of PHP 8.0.0, it has been removed and throws an Error exception.

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.

Example #17 Key Quoting

`<?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:

Example #18 More Examples

`<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
echo $arr['fruit'], PHP_EOL; // apple
echo $arr['veggie'], PHP_EOL; // carrot
// Incorrect. This does not work and throws a PHP Error because
// of an undefined constant named fruit
//
// Error: Undefined constant "fruit"
try {
echo $arr[fruit];
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), PHP_EOL;
}
// 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
echo $arr['fruit'], PHP_EOL; // apple
echo $arr[fruit], PHP_EOL; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no error occurs here
echo "Hello $arr[fruit]", PHP_EOL; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
echo "Hello {$arr[fruit]}", PHP_EOL; // Hello carrot
echo "Hello {$arr['fruit']}", PHP_EOL; // Hello apple
// Concatenation is another option
echo "Hello " . $arr['fruit'], PHP_EOL; // Hello apple
?>`
`<?php
// 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']";
?>`

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.

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

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words `empty` and `default` this way, since they are reserved keywords.

> Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so `"$foo[bar]"` is valid. See the above examples for details on why as well as the section on variable parsing in strings.

### Converting to array

For any of the types int, float, string, bool 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 `NUL` bytes on either side. Uninitialized typed properties are silently discarded.

Example #19 Converting to an Array

`<?php
class A {
private $B;
protected $C;
public $D;
function __construct()
{
$this->{1} = null;
}
}
var_export((array) new A());
?>`

The above example will output:

    array (
      '' . "\0" . 'A' . "\0" . 'B' => NULL,
      '' . "\0" . '*' . "\0" . 'C' => NULL,
      'D' => NULL,
      1 => NULL,
    )

These `NUL` can result in some unexpected behaviour:

Example #20 Casting an Object to an Array

`<?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 example will output:

    array(3) {
      ["BA"]=>
      NULL
      ["AA"]=>
      NULL
      ["AA"]=>
      NULL
    }

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

Converting `null` to an array results in an empty array.

### Comparing

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

### Array unpacking

An array prefixed by `...` will be expanded in place during array definition. Only arrays and objects which implement Traversable can be expanded. Array unpacking with `...` is available as of PHP 7.4.0. This is also called the spread operator.

It's possible to expand multiple times, and add normal elements before or after the `...` operator:

Example #21 Simple array unpacking

`<?php
// Using short array syntax.
// Also, works with array() syntax.
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; // [1, 2, 3]
$arr3 = [0, ...$arr1]; // [0, 1, 2, 3]
$arr4 = [...$arr1, ...$arr2, 111]; // [1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; // [1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c' => 'd']; // ['a', 'b', 'c' => 'd']
var_dump($arr1, $arr2, $arr3, $arr4, $arr5, $arr6);
?>`

Unpacking an array with the `...` operator follows the semantics of the array_merge() function. That is, later string keys overwrite earlier ones and integer keys are renumbered:

Example #22 Array unpacking with duplicate key

`<?php
// string key
$arr1 = ["a" => 1];
$arr2 = ["a" => 2];
$arr3 = ["a" => 0, ...$arr1, ...$arr2];
var_dump($arr3); // ["a" => 2]
// integer key
$arr4 = [1, 2, 3];
$arr5 = [4, 5, 6];
$arr6 = [...$arr4, ...$arr5];
var_dump($arr6); // [1, 2, 3, 4, 5, 6]
// Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6]
// where the original integer keys have not been retained.
?>`

> Note:

> Keys that are neither integers nor strings throw a TypeError. Such keys can only be generated by a Traversable object.

> Note:

> Prior to PHP 8.1, unpacking an array which has a string key is not supported:

> `<?php
> $arr1 = [1, 2, 3];
> $arr2 = ['a' => 4];
> $arr3 = [...$arr1, ...$arr2];
> // Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5
> $arr4 = [1, 2, 3];
> $arr5 = [4, 5];
> $arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5]
> ?>`

### Examples

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

Example #23 Array Versatility

`<?php
// This:
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
var_dump($a, $b);
// . . .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').
var_dump($a, $b);
?>`

Example #24 Using array()

`<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
var_dump($map);
// strictly numerical keys
// this is the same as array(0 => 7, 1 => 8, ...)
$array = array( 7,
8,
0,
156,
-10
);
var_dump($array);
$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
);
var_dump($switching);
// empty array
$empty = array();
var_dump($empty);
?>`

Example #25 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 by passing them by reference.

Example #26 Changing element in the loop

`<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as &$color) {
$color = mb_strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
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 #27 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 #28 Filling an array

`<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
var_dump($files);
?>`

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 #29 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 #30 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"
)
);
var_dump($fruits);
// 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";
var_dump($juices);
?>`

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

Example #31 Array Copying

`<?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
var_dump($arr1, $arr2, $arr3);
?>`

## Objects

### Object Initialization

To create a new object, use the `new` statement to instantiate a class:

Example #1 Object Construction

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

### Converting to object

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. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated.

Example #2 Casting to an Object

`<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // outputs 'bool(true)'
// Deprecated as of PHP 8.1
var_dump(key($obj)); // outputs 'string(1) "1"'
?>`

For any other value, a member variable named `scalar` will contain the value.

Example #3 `(object)` cast

`<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>`

## Enumerations

(PHP 8 >= 8.1.0)

### Basic Enumerations

Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type.

`<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
function do_stuff(Suit $s)
{
// ...
}
do_stuff(Suit::Spades);
?>`

For a full discussion, see the Enumerations chapter.

### Casting

If an enum is converted to an object, it is not modified. If an enum is converted to an array, an array with a single `name` key (for Pure enums) or an array with both `name` and `value` keys (for Backed enums) is created. All other cast types will result in an error.

## Resources

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.

### Converting to resource

As resource variables hold special handles to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

### Freeing resources

Thanks to the reference-counting system being part of 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.

## Callables

A callable is a reference to a function or method that is passed to another function as an argument. They are represented with the callable type declaration.

`<?php
function foo(callable $callback) {
$callback();
}
?>`

Some functions accept callback functions as a parameter, e.g. array_map(), usort(), or preg_replace_callback().

### Creation of callables

A callable is a type that represents something that can be invoked. Callables can be passed as arguments to functions or methods which expect a callback parameter or they can be invoked directly. The callable type cannot be used as a type declaration for class properties. Instead, use a Closure type declaration.

Callables can be created in several different ways:

- Closure object
- string containing the name of a function or a method
- array containing a class name or an object in index 0 and the method name in index 1
- object implementing the __invoke() magic method

A Closure object can be created using anonymous function syntax, arrow function syntax, first-class callable syntax, or the Closure::fromCallable() method.

> Note: The first-class callable syntax is only available as of PHP 8.1.0.

Example #1 Callback example using a Closure

`<?php
// Using anonymous function syntax
$double1 = function ($a) {
return $a * 2;
};
// Using first-class callable syntax
function double_function($a) {
return $a * 2;
}
$double2 = double_function(...);
// Using arrow function syntax
$double3 = fn($a) => $a * 2;
// Using Closure::fromCallable
$double4 = Closure::fromCallable('double_function');
// Use the closure as a callback here to
// double the size of each element in our range
$new_numbers = array_map($double1, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double2, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double3, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double4, range(1, 5));
print implode(' ', $new_numbers);
?>`

Output of the above example in PHP 8.1:

    2 4 6 8 10
    2 4 6 8 10
    2 4 6 8 10
    2 4 6 8 10

A callable can also be a string containing the name of a function or a static method. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), isset(), list(), print or unset().

Static class methods can be used without instantiating an object of that class by either, creating an array with the class name at index 0 and the method name at index 1, or by using the special syntax with the scope resolution operator `::`, as in `'ClassName::methodName'`.

A method of an instantiated object can be a callable when provided as an array with the object at index 0 and the method name at index 1.

The main difference between a Closure object and the callable type is that a Closure object is scope-independent and can always be invoked, whereas a callable type may be scope-dependent and may not be directly invoked. Closure is the preferred way to create callables.

> Note: While Closure objects are bound to the scope where they are created, callables referencing class methods as strings or arrays are resolved in the scope where they are called. To create a callable from a private or protected method, which can then be invoked from outside the class scope, use Closure::fromCallable() or the first-class callable syntax.

PHP allows the creation of callables which can be used as a callback argument but cannot be called directly. These are context-dependent callables which reference a class method in the inheritance hierarchy of a class, e.g. `'parent::method'` or `["static", "method"]`.

> Note: As of PHP 8.2.0, context-dependent callables are deprecated. Remove the context dependency by replacing `'parent::method'` with `parent::class . '::method'` or use the first-class callable syntax.

Example #2 Calling various types of callables with call_user_function()

`<?php
// An example callback function
function my_callback_function() {
echo 'hello world!', PHP_EOL;
}
// An example callback method
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!', PHP_EOL;
}
}
// Type 1: Simple callback
call_user_func('my_callback_function');
// Type 2: Static class method call
call_user_func(['MyClass', 'myCallbackMethod']);
// Type 3: Object method call
$obj = new MyClass();
call_user_func([$obj, 'myCallbackMethod']);
// Type 4: Static class method call
call_user_func('MyClass::myCallbackMethod');
// Type 5: Static class method call using ::class keyword
call_user_func([MyClass::class, 'myCallbackMethod']);
// Type 6: Relative static class method call
class A {
public static function who() {
echo 'A', PHP_EOL;
}
}
class B extends A {
public static function who() {
echo 'B', PHP_EOL;
}
}
call_user_func(['B', 'parent::who']); // deprecated as of PHP 8.2.0
// Type 7: Objects implementing __invoke can be used as callables
class C {
public function __invoke($name) {
echo 'Hello ', $name;
}
}
$c = new C();
call_user_func($c, 'PHP!');
?>`

The above example will output:

    hello world!
    Hello World!
    Hello World!
    Hello World!
    Hello World!

    Deprecated: Callables of the form ["B", "parent::who"] are deprecated in script on line 41
    A
    Hello PHP!

> 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

The mixed type accepts every value. It is equivalent to the union type `object|resource|array|string|float|int|bool|null`. Available as of PHP 8.0.0.

mixed is, in type theory parlance, the top type. Meaning every other type is a subtype of it.

## Void

void is a return-only type declaration indicating the function does not return a value, but the function may still terminate. Therefore, it cannot be part of a union type declaration. Available as of PHP 7.1.0.

> Note: Even if a function has a return type of void it will still return a value, this value is always `null`.

## Never

never is a return-only type indicating the function does not terminate. This means that it either calls exit(), throws an exception, or is an infinite loop. Therefore, it cannot be part of a union type declaration. Available as of PHP 8.1.0.

never is, in type theory parlance, the bottom type. Meaning it is the subtype of every other type and can replace any other return type during inheritance.

## Relative class types

These types declarations can only be used within classes.

### self

The value must be an `instanceof` the same class as the one in which the type declaration is used.

### parent

The value must be an `instanceof` a parent of the class in which the type declaration is used.

### static

static is a return-only type which requires that the value returned must be an `instanceof` the same class as the one the method is called in. Available as of PHP 8.0.0.

## Singleton types

Singleton types are those which allow only one value. PHP has support for two singleton types: false as of PHP 8.0.0 and true as of PHP 8.2.0.

Warning

Prior to PHP 8.2.0 the false type could only be used as part of a union type.

> Note: It is not possible to define custom singleton types. Consider using enumerations instead.

## Iterables

Iterable is a built-in compile time type alias for `array|Traversable`. From its introduction in PHP 7.1.0 and prior to PHP 8.2.0, iterable was a built-in pseudo-type that acted as the aforementioned type alias and can be used as a type declaration. An iterable type can be used in `foreach` and with yield from within a generator.

> Note:

> Functions declaring iterable as a return type may also be generators.

> Example #1 Iterable generator return type example

> `<?php
> function gen(): iterable {
> yield 1;
> yield 2;
> yield 3;
> }
> foreach(gen() as $value) {
> echo $value, "\n";
> }
> ?>`

## Type declarations

Type declarations can be added to function arguments, return values, as of PHP 7.4.0, class properties, and as of PHP 8.3.0, class constants. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown.

Every single type that PHP supports, with the exception of resource can be used within a user-land type declaration. This page contains a changelog of availability of the different types and documentation about usage of them in type declarations.

> Note:

> When a class implements an interface method or reimplements a method which has already been defined by a parent class, it has to be compatible with the aforementioned definition. A method is compatible if it follows the variance rules.

### Changelog

Version | Description
--- | ---
8.3.0 | Support for class, interface, trait, and enum constant typing has been added.
8.2.0 | Support for DNF types has been added.
8.2.0 | Support for the literal type true has been added.
8.2.0 | The types null and false can now be used standalone.
8.1.0 | Support for intersection types has been added.
8.1.0 | Returning by reference from a void function is now deprecated.
8.1.0 | Support for the return only type never has been added.
8.0.0 | Support for mixed has been added.
8.0.0 | Support for the return only type static has been added.
8.0.0 | Support for union types has been added.
7.4.0 | Support for class properties typing has been added.
7.2.0 | Support for object has been added.
7.1.0 | Support for iterable has been added.
7.1.0 | Support for void has been added.
7.1.0 | Support for nullable types has been added.

### Atomic Types Usage Notes

Atomic types have straight forward behaviour with some minor caveats which are described in this section.

#### Scalar types

Warning

Name aliases for scalar types (bool, int, float, string) are not supported. Instead, they are treated as class or interface names. For example, using `boolean` as a type declaration will require the value to be an `instanceof` the class or interface `boolean`, rather than of type bool:

`<?php
function test(boolean $param) {}
test(true);
?>`

Output of the above example in PHP 8:

    Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in /in/9YrUX on line 2

    Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in - on line 3 and defined in -:2
    Stack trace:
    #0 -(3): test(true)
    #1 {main}
      thrown in - on line 2

#### void

> Note:

> Returning by reference from a void function is deprecated as of PHP 8.1.0, because such a function is contradictory. Previously, it already emitted the following `E_NOTICE` when called: Only variable references should be returned by reference.

> `<?php
> function &test(): void {}
> ?>`

#### Callable types

This type cannot be used as a class property type declaration.

> Note: It is not possible to specify the signature of the function.

#### Type declarations on pass-by-reference Parameters

If a pass-by-reference parameter has a type declaration, the type of the variable is only checked on function entry, at the beginning of the call, but not when the function returns. This means that a function can change the type of variable reference.

Example #1 Typed pass-by-reference Parameters

`<?php
function array_baz(array &$param)
{
$param = 1;
}
$var = [];
array_baz($var);
var_dump($var);
array_baz($var);
?>`

The above example will output something similar to:

    int(1)

    Fatal error: Uncaught TypeError: array_baz(): Argument #1 ($param) must be of type array, int given, called in - on line 9 and defined in -:2
    Stack trace:
    #0 -(9): array_baz(1)
    #1 {main}
      thrown in - on line 2

### Composite Types Usage Notes

Composite type declarations are subject to a couple of restrictions and will perform a redundancy check at compile time to prevent simple bugs.

Caution

Prior to PHP 8.2.0, and the introduction of DNF types, it was not possible to combine intersection types with union types.

#### Union types

Warning

It is not possible to combine the two singleton types false and true together in a union type. Use bool instead.

Caution

Prior to PHP 8.2.0, as false and null could not be used as standalone types, a union type comprised of only these types was not permitted. This comprises the following types: false, `false|null`, and `?false`.

##### Nullable type syntactic sugar

A single base type declaration can be marked nullable by prefixing the type with a question mark (`?`). Thus `?T` and `T|null` are identical.

> Note: This syntax is supported as of PHP 7.1.0, and predates generalized union types support.

> Note:

> It is also possible to achieve nullable arguments by making `null` the default value. This is not recommended as if the default value is changed in a child class a type compatibility violation will be raised as the null type will need to be added to the type declaration. This behavior is also deprecated since PHP 8.4.

> Example #2 Old way to make arguments nullable

> `<?php
> class C {}
> function f(C $c = null) {
> var_dump($c);
> }
> f(new C);
> f(null);
> ?>`

> The above example will output:

>     object(C)#1 (0) {
>     }
>     NULL

#### Duplicate and redundant types

To catch simple bugs in composite type declarations, redundant types that can be detected without performing class loading will result in a compile-time error. This includes:

- Each name-resolved type may only occur once. Types such as `int|string|INT` or `Countable&Traversable&COUNTABLE` result in an error.
- Using mixed or never results in an error.
- For union types:
  - If bool is used, false or true cannot be used additionally.
  - If object is used, class types cannot be used additionally.
  - If iterable is used, array and Traversable cannot be used additionally.
- For intersection types:
  - Using a type which is not a class-type results in an error.
  - Using either self, parent, or static results in an error.
- For DNF types:
  - If a more generic type is used, the more restrictive one is redundant.
  - Using two identical intersection types.

> Note: This does not guarantee that the type is “minimal”, because doing so would require loading all used class types.

For example, if `A` and `B` are class aliases, then `A|B` remains a legal union type, even though it could be reduced to either `A` or `B`. Similarly, if class `B extends A {}`, then `A|B` is also a legal union type, even though it could be reduced to just `A`.

`<?php
function foo(): int|INT {} // Disallowed
function foo(): bool|false {} // Disallowed
function foo(): int&Traversable {} // Disallowed
function foo(): self&Traversable {} // Disallowed
use A as B;
function foo(): A|B {} // Disallowed ("use" is part of name resolution)
function foo(): A&B {} // Disallowed ("use" is part of name resolution)
class_alias('X', 'Y');
function foo(): X|Y {} // Allowed (redundancy is only known at runtime)
function foo(): X&Y {} // Allowed (redundancy is only known at runtime)
?>`

### Examples

Example #3 Basic class type declaration

`<?php
class C {}
class D extends C {}
// This doesn't extend C.
class E {}
function f(C $c) {
echo get_class($c)."\n";
}
f(new C);
f(new D);
f(new E);
?>`

Output of the above example in PHP 8:

    C
    D

    Fatal error: Uncaught TypeError: f(): Argument #1 ($c) must be of type C, E given, called in /in/gLonb on line 14 and defined in /in/gLonb:8
    Stack trace:
    #0 -(14): f(Object(E))
    #1 {main}
      thrown in - on line 8

Example #4 Basic interface type declaration

`<?php
interface I { public function f(); }
class C implements I { public function f() {} }
// This doesn't implement I.
class E {}
function f(I $i) {
echo get_class($i)."\n";
}
f(new C);
f(new E);
?>`

Output of the above example in PHP 8:

    C

    Fatal error: Uncaught TypeError: f(): Argument #1 ($i) must be of type I, E given, called in - on line 13 and defined in -:8
    Stack trace:
    #0 -(13): f(Object(E))
    #1 {main}
      thrown in - on line 8

Example #5 Basic return type declaration

`<?php
function sum($a, $b): float {
return $a + $b;
}
// Note that a float will be returned.
var_dump(sum(1, 2));
?>`

The above example will output:

    float(3)

Example #6 Returning an object

`<?php
class C {}
function getC(): C {
return new C;
}
var_dump(getC());
?>`

The above example will output:

    object(C)#1 (0) {
    }

Example #7 Nullable argument type declaration

`<?php
class C {}
function f(?C $c) {
var_dump($c);
}
f(new C);
f(null);
?>`

The above example will output:

    object(C)#1 (0) {
    }
    NULL

Example #8 Nullable return type declaration

`<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>`

Example #9 Class property type declaration

`<?php
class User {
public static string $foo = 'foo';
public int $id;
public string $username;
public function __construct(int $id, string $username) {
$this->id = $id;
$this->username = $username;
}
}
?>`

### Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.

It is possible to enable strict mode on a per-file basis. In strict mode, only a value corresponding exactly to the type declaration will be accepted, otherwise a TypeError will be thrown. The only exception to this rule is that an int value will pass a float type declaration.

Warning

Function calls from within internal functions will not be affected by the `strict_types` declaration.

To enable strict mode, the `declare` statement is used with the `strict_types` declaration:

> Note:

> Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (coercive typing) will be respected, and the value will be coerced.

> Note:

> Strict typing is only defined for scalar type declarations.

Example #10 Strict typing for arguments values

`<?php
declare(strict_types=1);
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>`

Output of the above example in PHP 8:

    int(3)

    Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, float given, called in - on line 9 and defined in -:4
    Stack trace:
    #0 -(9): sum(1.5, 2.5)
    #1 {main}
      thrown in - on line 4

Example #11 Coercive typing for argument values

`<?php
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
// These will be coerced to integers: note the output below!
var_dump(sum(1.5, 2.5));
?>`

The above example will output:

    int(3)
    int(3)

Example #12 Strict typing for return values

`<?php
declare(strict_types=1);
function sum($a, $b): int {
return $a + $b;
}
var_dump(sum(1, 2));
var_dump(sum(1, 2.5));
?>`

The above example will output:

    int(3)

    Fatal error: Uncaught TypeError: sum(): Return value must be of type int, float returned in -:5
    Stack trace:
    #0 -(9): sum(1, 2.5)
    #1 {main}
      thrown in - on line 5

## Type Juggling

PHP does not require explicit type definition in variable declaration. In this case, the type of a variable is determined by the value it stores. That is to say, if a string is assigned to variable $var, then $var is of type string. If afterwards an int value is assigned to $var, it will be of type int.

PHP may attempt to convert the type of a value to another automatically in certain contexts. The different contexts which exist are:

- Numeric
- String
- Logical
- Integral and string
- Comparative
- Function

> Note: When a value needs to be interpreted as a different type, the value itself does not change types.

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.

### Numeric contexts

This is the context when using an arithmetical operator.

In this context if either operand is a float (or not interpretable as an int), both operands are interpreted as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int. As of PHP 8.0.0, if one of the operands cannot be interpreted a TypeError is thrown.

### String contexts

This is the context when using echo, print, string interpolation, or the string concatenation operator.

In this context the value will be interpreted as string. If the value cannot be interpreted a TypeError is thrown. Prior to PHP 7.4.0, an `E_RECOVERABLE_ERROR` was raised.

### Logical contexts

This is the context when using conditional statements, the ternary operator, or a logical operator.

In this context the value will be interpreted as bool.

### Integral and string contexts

This is the context when using bitwise operators.

In this context if all operands are of type string the result will also be a string. Otherwise, the operands will be interpreted as ints, and the result will also be an int. As of PHP 8.0.0, if one of the operands cannot be interpreted a TypeError is thrown.

### Comparative contexts

This is the context when using a comparison operator.

The type conversions which occur in this context are explained in the Comparison with Various Types table.

### Function contexts

This is the context when a value is passed to a typed parameter, property, or returned from a function which declares a return type.

In this context the value must be a value of the type. Two exceptions exist, the first one is: if the value is of type int and the declared type is float, then the integer is converted to a floating point number. The second one is: if the declared type is a scalar type, the value is convertable to a scalar type, and the coercive typing mode is active (the default), the value may be converted to an accepted scalar value. See below for a description of this behaviour.

Warning

Internal functions automatically coerce `null` to scalar types, this behaviour is DEPRECATED as of PHP 8.1.0.

#### Coercive typing with simple type declarations

- bool type declaration: value is interpreted as bool.
- int type declaration: value is interpreted as int if the conversion is well-defined. For example the string is numeric.
- float type declaration: value is interpreted as float if the conversion is well-defined. For example the string is numeric.
- string type declaration: value is interpreted as string.

#### Coercive typing with union types

When `strict_types` is not enabled, scalar type declarations are subject to limited implicit type coercions. If the exact type of the value is not part of the union, then the target type is chosen in the following order of preference:

1. int
2. float
3. string
4. bool

If the type exists in the union and the value can be coerced to the type under PHP's existing type-checking semantics, then the type is chosen. Otherwise, the next type is tried.
Caution

As an exception, if the value is a string and both int and float are part of the union, the preferred type is determined by the existing numeric string semantics. For example, for `"42"` int is chosen, while for `"42.0"` float is chosen.

> Note:

> Types that are not part of the above preference list are not eligible targets for implicit coercion. In particular no implicit coercions to the null, false, and true types occur.

Example #1 Example of types being coerced into a type part of the union

`<?php
// int|string
42 --> 42 // exact type
"42" --> "42" // exact type
new ObjectWithToString --> "Result of __toString()"
// object never compatible with int, fall back to string
42.0 --> 42 // float compatible with int
42.1 --> 42 // float compatible with int
1e100 --> "1.0E+100" // float too large for int type, fall back to string
INF --> "INF" // float too large for int type, fall back to string
true --> 1 // bool compatible with int
[] --> TypeError // array not compatible with int or string
// int|float|bool
"45" --> 45 // int numeric string
"45.0" --> 45.0 // float numeric string
"45X" --> true // not numeric string, fall back to bool
"" --> false // not numeric string, fall back to bool
"X" --> true // not numeric string, fall back to bool
[] --> TypeError // array not compatible with int, float or bool
?>`

### Type Casting

Type casting converts the value to a chosen type by writing the type within parentheses before the value to convert.

Example #2 Type Casting

`<?php
$foo = 10; // $foo is an integer
$bar = (bool) $foo; // $bar is a boolean
var_dump($bar);
?>`

The casts allowed are:

- `(int)` - cast to int
- `(bool)` - cast to bool
- `(float)` - cast to float
- `(string)` - cast to string
- `(array)` - cast to array
- `(object)` - cast to object
- `(unset)` - cast to NULL

Warning

`(integer)` is an alias of the `(int)` cast. `(boolean)` is an alias of the `(bool)` cast. `(binary)` is an alias of the `(string)` cast. `(double)` and `(real)` are aliases of the `(float)` cast. These casts do not use the canonical type name and are deprecated as of PHP 8.5.0.

Warning

The `(real)` cast alias has been deprecated as of PHP 7.4.0 and removed as of PHP 8.0.0.

Warning

The `(unset)` cast has been deprecated as of PHP 7.2.0. Note that the `(unset)` cast is the same as assigning the value NULL to the variable or call. The `(unset)` cast is removed as of PHP 8.0.0.

Caution

The `(binary)` cast and `b` prefix exists for forward support. Currently `(binary)` and `(string)` are identical, however this may change and should not be relied upon.

> Note:

> Whitespaces are ignored within the parentheses of a cast. Therefore, the following two casts are equivalent:

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

Casting literal strings and variables to binary strings:

`<?php
$binary = (binary) $string;
$binary = b"binary string";
?>`

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

Example #3 Different Casting Mechanisms

`<?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", PHP_EOL;
}
?>`

It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:

- Converting to boolean
- Converting to integer
- Converting to float
- Converting to string
- Converting to array
- Converting to object
- Converting to resource
- Converting to NULL
- The type comparison tables

> Note: Because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

> Example #4 Using Array Offset with a String

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

# Variables

## Table of Contents

- Basics
- Predefined Variables
- Variable scope
- Variable variables
- Variables From External Sources

## Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

A valid variable name starts with a letter (`A-Z`, `a-z`, or the bytes from 128 through 255) or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: `^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$`

> Note: PHP doesn't support Unicode variable names, however, some character encodings (such as UTF-8) encode characters in such a way that all bytes of a multi-byte character fall within the allowed range, thus making it a valid variable name.

> Note: `$this` is a special variable that can't be assigned. Prior to PHP 7.1.0, indirect assignment (e.g. by using variable variables) was possible.

Tip

See also the Userland Naming Guide.

Example #1 Valid variable names

`<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
?>`

Example #2 Invalid variable names

`<?php
$4site = 'not yet'; // invalid; starts with a number`

PHP accepts a sequence of any bytes as a variable name. Variable names that do not follow the above-mentioned naming rules can only be accessed dynamically at runtime. See variable variables for information on how to access them.

Example #3 Accessing obscure variable names

`<?php
${'invalid-name'} = 'bar';
$name = 'invalid-name';
echo ${'invalid-name'}, " ", $$name;
?>`

The above example will output:

    bar bar

By default, variables are always assigned by value. That is to say, when an expression is assigned 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 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 because test() doesn't return a variable by reference.
?>`

It is not necessary to declare variables in PHP, however, it is a very good practice. Accessing an undefined variable will result in an `E_WARNING` (prior to PHP 8.0.0, `E_NOTICE`). An undefined variable has a default value of `null`. The isset() language construct can be used to detect if a variable has already been initialized.

Example #4 Default value of an uninitialized variable

`<?php
// Unset AND unreferenced (no use context) variable.
var_dump($unset_var);
?>`

The above example will output:

    Warning: Undefined variable $unset_var in ...
    NULL

PHP allows array autovivification (automatic creation of new arrays) from an undefined variable. Appending an element to an undefined variable will create a new array and will not generate a warning.

Example #5 Autovivification of an array from an undefined variable

`<?php
$unset_array[] = 'value'; // Does not generate a warning.
?>`
Warning

Relying on the default value of an uninitialized variable is problematic when including one file in another which uses the same variable name.

A variable can be destroyed by using the unset() language construct.

For information on variable-related functions, see the Variable Functions Reference.

## Predefined Variables

PHP provides a number of predefined variables. PHP also provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These arrays are automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) Refer to the list of superglobals for details.

> Note: Variable variables

> Superglobals cannot be used as variable variables inside functions or class methods.

If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

## Variable scope

The scope of a variable is the context within which it is defined. PHP has a function scope and a global scope. Any variable defined outside a function is limited to the global scope. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.

Example #1 Example of global variable scope

`<?php
$a = 1;
include 'b.inc'; // Variable $a will be available within b.inc
?>`

Any variable created inside a named function or an anonymous function is limited to the scope of the function body. However, arrow functions bind variables from the parent scope to make them available inside the body. If a file include occurs inside a function within the calling file, the variables contained in the called file will be available as if they had been defined inside the calling function.

Example #2 Example of local variable scope

`<?php
$a = 1; // global scope
function test()
{
echo $a; // Variable $a is undefined as it refers to a local version of $a
}
?>`

The example above will generate an undefined variable `E_WARNING` (or an `E_NOTICE` prior to PHP 8.0.0). This is because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. Note that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

### The `global` keyword

The `global` keyword is used to bind a variable from a global scope into a local scope. The keyword can be used with a list of variables or a single variable. A local variable will be created referencing the global variable of the same name. If the global variable does not exist, the variable will be created in global scope and assigned `null`.

Example #3 Using `global`

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

The above example 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 #4 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 #5 Example demonstrating superglobals and scope

`<?php
function test_superglobal()
{
echo $_POST['name'];
}
?>`

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

### Using `static` variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Example #6 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 #7 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. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Example #8 Static variables with recursive functions

`<?php
function test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>`

Prior to PHP 8.3.0, static variables could only be initialized using a constant expression. As of PHP 8.3.0, dynamic expressions (e.g. function calls) are also allowed:

Example #9 Declaring static variables

`<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // correct
static $int = sqrt(121); // correct as of PHP 8.3.0
$int++;
echo $int;
}
?>`

Static variables inside anonymous functions persist only within that specific function instance. If the anonymous function is recreated on each call, the static variable will be reinitialized.

Example #10 Static variables in anonymous functions

`<?php
function exampleFunction($input) {
$result = (static function () use ($input) {
static $counter = 0;
$counter++;
return "Input: $input, Counter: $counter\n";
});
return $result();
}
// Calls to exampleFunction will recreate the anonymous function, so the static
// variable does not retain its value.
echo exampleFunction('A'); // Outputs: Input: A, Counter: 1
echo exampleFunction('B'); // Outputs: Input: B, Counter: 1
?>`

As of PHP 8.1.0, when a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method. This means that static variables in methods now behave the same way as static properties.

As of PHP 8.3.0, static variables can be initialized with arbitrary expressions. This means that method calls, for example, can be used to initialize static variables.

Example #11 Usage of static Variables in Inherited Methods

`<?php
class Foo {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class Bar extends Foo {}
var_dump(Foo::counter()); // int(1)
var_dump(Foo::counter()); // int(2)
var_dump(Bar::counter()); // int(3), prior to PHP 8.1.0 int(1)
var_dump(Bar::counter()); // int(4), prior to PHP 8.1.0 int(2)
?>`

### References with `global` and `static` variables

PHP 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;
$new = new stdClass;
$obj = &$new;
}
function test_global_noref() {
global $obj;
$new = new stdClass;
$obj = $new;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>`

The above example will output:

    NULL
    object(stdClass)#1 (0) {
    }

A similar behaviour applies to the `static` statement. References are not stored statically:

`<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// Assign a reference to the static variable
$obj = &$new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// Assign the object to the static variable
$obj = $new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>`

The above example will output:

    Static object: NULL
    Static object: NULL

    Static object: NULL
    Static object: object(stdClass)#3 (1) {
      ["property"]=>
      int(1)
    }

This example demonstrates that when assigning a reference to a static variable, it is not remembered when the `&get_instance_ref()` function is called a second time.

## Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

`<?php
$a = 'hello';
?>`

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

`<?php
$$a = 'world';
?>`

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

`<?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, an ambiguity problem has to be resolved. That is, if the parser sees $$a[1] then it needs to know if $a[1] was meant to be used as a variable, or if $$a was wanted 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 there is 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 multiple 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 {
public $bar = 'I am bar.';
public $arr = ['I am A.', 'I am B.', 'I am C.'];
public $r = 'I am r.';
}
$foo = new Foo();
$bar = 'bar';
$baz = ['foo', 'bar', 'baz', 'quux'];
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
echo $foo->{$arr}[1] . "\n";
?>`

The above example will output:

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

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable `$this` is also a special variable that cannot be referenced dynamically.

## Variables From External Sources

### HTML Forms (GET and POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few 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>

There are only two ways to access data from HTML forms. Currently available methods are listed below:

Example #2 Accessing data from a simple POST HTML form

`<?php
echo $_POST['username'];
echo $_REQUEST['username'];
?>`

Using a GET form is similar except the appropriate GET predefined variable can be used 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.

> Note:

> Dots and spaces in variable names are converted to underscores. For example `<input name="a.b" />` becomes `$_REQUEST["a_b"]`.

PHP also understands arrays in the context of form variables (see the related faq). For example, related variables may be grouped together, or this feature may be used 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>`

> Note: If an external variable name begins with a valid array syntax, trailing characters are silently ignored. For example, `<input name="foo[bar]baz">` becomes `$_REQUEST['foo']['bar']`.

#### IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

    <input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

### HTTP Cookies

PHP transparently supports HTTP cookies as defined by » RFC 6265. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. It is possible to 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 as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

> Note: As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names of incoming cookies are no longer url-decoded for security reasons.

If multiple values should be assigned to a single cookie variable, they can be assigned 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 the script. If just one cookie should be set 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 the browser unless the path or domain is different. So, for a shopping cart application a counter may be kept, and passed 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);
?>`

### Dots in incoming variable names

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 */
?>`
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

### Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

HTTP being a text protocol, most, if not all, content that comes in Superglobal arrays, like $_POST and $_GET will remain as strings. PHP will not try to convert values to a specific type. In the example below, $_GET["var1"] will contain the string "null" and $_GET["var2"], the string "123".

    /index.php?var1=null&var2=123

### Changelog

Version | Description
--- | ---
7.2.34, 7.3.23, 7.4.11 | The names of incoming cookies are no longer url-decoded for security reasons.

# Constants

## Table of Contents

- Syntax
- Predefined constants
- Magic constants

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). Constants are case-sensitive. By convention, constant identifiers are always uppercase.

> Note:

> Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.

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_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$`

It is possible to define() constants with reserved or even invalid names, whose value can only be retrieved with the constant() function. However, doing so is not recommended.

Tip

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 128 through 255 (0x80-0xff).

Like superglobals, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope. For more information on scope, read the manual section on variable scope.

> Note: As of PHP 7.1.0, class constant may declare a visibility of protected or private, making them only available in the hierarchical scope of the class in which it is defined.

## Syntax

Constants can be defined using the `const` keyword, or by using the define()-function. While define() allows a constant to be defined to an arbitrary expression, the `const` keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.

When using the `const` keyword, only scalar (bool, int, float and string) expressions and constant arrays containing only scalar expressions are accepted. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

The value of a constant is accessed simply by specifying its name. Unlike variables, a constant is not prepended with a `$`. It is also possible to use the constant() function to read a constant's value if the constant's name is obtained dynamically. Use get_defined_constants() to get a list of all defined constants.

> Note: Constants and (global) variables are in a different namespace. This implies that for example `true` and $TRUE are generally different.

If an undefined constant is used an Error is thrown. Prior to PHP 8.0.0, undefined constants would be interpreted as a bare word string, i.e. (CONSTANT vs "CONSTANT"). This fallback is deprecated as of PHP 7.2.0, and an error of level `E_WARNING` is issued when it happens. Prior to PHP 7.2.0, an error of level E_NOTICE has been issued instead. See also the manual entry on why $foo[bar] is wrong (unless `bar` is a constant). This does not apply to (fully) qualified constants, which will always raise a Error if undefined.

> Note: To check if a constant is set, use the defined() function.

These are the differences between constants and variables:

- Constants do not have a dollar sign (`$`) before them;
- Constants may be defined and accessed anywhere without regard to variable scoping rules;
- Constants may not be redefined or undefined once they have been set; and
- Constants may only evaluate to scalar values or arrays.

Example #1 Defining Constants

`<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // Emits an Error: Undefined constant "Constant"
// Prior to PHP 8.0.0, outputs "Constant" and issues a warning.
?>`

Example #2 Defining Constants using the `const` keyword

`<?php
// Simple scalar value
const CONSTANT = 'Hello World';
echo CONSTANT;
// Scalar expression
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;
const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"
// Constant arrays
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>`

> 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, `if` statements or `try`/`catch` blocks.

### See Also

- Class Constants

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

## Magic constants

There are a few 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 a script. All these "magical" constants are resolved at compile time, unlike regular constants, which are resolved at runtime. These special constants are case-insensitive and are as follows:

PHP's magic constants
Name | Description
--- | ---
`__LINE__` | The current line number of the file.
`__FILE__` | The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
`__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.
`__FUNCTION__` | The function name, or `{closure}` for anonymous functions.
`__CLASS__` | The class name. The class name includes the namespace it was declared in (e.g. `Foo\Bar`). When used inside a trait method, `__CLASS__` is the name of the class the trait is used in.
`__TRAIT__` | The trait name. The trait name includes the namespace it was declared in (e.g. `Foo\Bar`).
`__METHOD__` | The class method name.
`__PROPERTY__` | Only valid inside a property hook. It is equal to the name of the property.
`__NAMESPACE__` | The name of the current namespace.
`ClassName::class` | The fully qualified class name.

### See Also

- ::class
- get_class()
- get_object_vars()
- file_exists()
- function_exists()

# Expressions

Expressions are the most important building blocks 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: int values, floating point values (float), string values and bool 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.

# Operators

## Table of Contents

- Operator Precedence
- Arithmetic
- Increment and Decrement
- Assignment
- Bitwise
- Comparison
- Error Control
- Execution
- Logic
- String
- Array
- Type
- Functional

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

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

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

## Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression `1 + 5 * 3`, the answer is `16` and not `18` because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: `(1 + 5) * 3` evaluates to `18`.

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

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

Associativity is only meaningful for binary (and ternary) operators. Unary operators are either prefix or postfix so this notion is not applicable. For example `!!$a` can only be grouped as `!(!$a)`.

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

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

Operator Precedence
Associativity | Operators | Additional Information
--- | --- | ---
(n/a) | `clone` `new` | clone and new
right | `**` | arithmetic
(n/a) | `+` `-` `++` `--` `~` `(int)` `(float)` `(string)` `(array)` `(object)` `(bool)` `@` | arithmetic (unary `+` and `-`), increment/decrement, bitwise, type casting and error control
left | `instanceof` | type
(n/a) | `!` | logical
left | `*` `/` `%` | arithmetic
left | `+` `-` `.` | arithmetic (binary `+` and `-`), array and string (`.` prior to PHP 8.0.0)
left | `<<` `>>` | bitwise
left | `.` | string (as of PHP 8.0.0)
left | `|>` | pipe
non-associative | `<` `<=` `>` `>=` | comparison
non-associative | `==` `!=` `===` `!==` `<>` `<=>` | comparison
left | `&` | bitwise and references
left | `^` | bitwise
left | `|` | bitwise
left | `&&` | logical
left | `||` | logical
right | `??` | null coalescing
non-associative | `? :` | ternary (left-associative prior to PHP 8.0.0)
right | `=` `+=` `-=` `*=` `**=` `/=` `.=` `%=` `&=` `|=` `^=` `<<=` `>>=` `??=` | assignment
(n/a) | `yield from` | yield from
(n/a) | `yield` | yield
(n/a) | `print` | print
left | `and` | logical
left | `xor` | logical
left | `or` | logical
(n/a) | `throw` | throw

Example #1 Associativity

`<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
var_dump($a);
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
var_dump($a, $b);
?>`

The ternary operator specifically requires the use of parenthesis to disambiguate precedence.

Example #2 Explicit Precedence

`<?php
$a = true ? 0 : (true ? 1 : 2);
var_dump($a);
// this is not allowed since PHP 8
// $a = true ? 0 : true ? 1 : 2;
?>`

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 #3 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
?>`

Example #4 `+`, `-` and `.` precedence

`<?php
$x = 4;
// this line might result in unexpected output:
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// the desired precedence can be enforced by using parentheses:
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
// this is not allowed, and throws a TypeError:
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
?>`

The above example will output:

    -1, or so I hope
    -1, or so I hope
    Fatal error: Uncaught TypeError: Unsupported operand types: string - int

Example #5 Prior to PHP 8, `+`, `-` and `.` had the same precedence

`<?php
$x = 4;
// this line might result in unexpected output:
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// because it is evaluated like this line (prior to PHP 8.0.0):
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
// the desired precedence can be enforced by using parentheses:
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
?>`

The above example will output:

    -1, or so I hope
    -1, or so I hope
    x minus one equals 3, or so I hope

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

### Changelog

Version | Description
--- | ---
8.0.0 | String concatenation (`.`) now has a lower precedence than arithmetic addition/subtraction (`+` and `-`) and bitwise shift left/right (`<<` and `>>`); previously it had the same precedence as `+` and `-` and a higher precedence than `<<` and `>>`.
8.0.0 | The ternary operator (`? :`) is non-associative now; previously it was left-associative.
7.4.0 | Relying on the precedence of string concatenation (`.`) relative to arithmetic addition/subtraction (`+` or `-`) or bitwise shift left/right (`<<` or `>>`), i.e. using them together in an unparenthesized expression, is deprecated.
7.4.0 | Relying on left-associativity of the ternary operator (`? :`), i.e. nesting multiple unparenthesized ternary operators, is deprecated.

## Arithmetic Operators

Remember basic arithmetic from school? These work just like those.

Arithmetic Operators
Example | Name | Result
--- | --- | ---
`+$a` | Identity | Conversion of $a to int or float as appropriate.
`-$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` | Modulo | Remainder of $a divided by $b.
`$a ** $b` | Exponentiation | Result of raising $a to the $b'th power.

The division operator `/` returns a float value unless the two operands are int (or numeric strings which are type juggled to int) and the numerator is a multiple of the divisor, in which case an integer value will be returned. For integer division, see intdiv().

Operands of modulo are converted to int before processing. For floating-point modulo, see fmod().

The result of the modulo operator `%` has the same sign as the dividend — that is, the result of `$a % $b` will have the same sign as $a. For example:

Example #1 The Modulo Operator

`<?php
var_dump(5 % 3);
var_dump(5 % -3);
var_dump(-5 % 3);
var_dump(-5 % -3);
?>`

The above example will output:

    int(2)
    int(2)
    int(-2)
    int(-2)

### See Also

- Math functions

## Incrementing/Decrementing Operators

PHP supports pre- and post-increment and decrement operators. Those unary operators allow to increment or decrement the value by one.

Increment/decrement Operators
Example | Name | Effect
--- | --- | ---
++$a | Pre-increment | Increments $a by one, then returns $a.
$a++ | Post-increment | Returns $a, then increments $a by one.
--$a | Pre-decrement | Decrements $a by one, then returns $a.
$a-- | Post-decrement | Returns $a, then decrements $a by one.

Example #1 Examples of Increment/Decrement

`<?php
echo 'Post-increment:', PHP_EOL;
$a = 5;
var_dump($a++);
var_dump($a);
echo 'Pre-increment:', PHP_EOL;
$a = 5;
var_dump(++$a);
var_dump($a);
echo 'Post-decrement:', PHP_EOL;
$a = 5;
var_dump($a--);
var_dump($a);
echo 'Pre-decrement:', PHP_EOL;
$a = 5;
var_dump(--$a);
var_dump($a);
?>`

The above example will output:

    Post-increment:
    int(5)
    int(6)
    Pre-increment:
    int(6)
    int(6)
    Post-decrement:
    int(5)
    int(4)
    Pre-decrement:
    int(4)
    int(4)

Warning

The increment and decrement operators have no effect on values of type bool. A `E_WARNING` is emitted as of PHP 8.3.0, because this will implicitly cast the value to int in the future.

The decrement operator has no effect on values of type null. A `E_WARNING` is emitted as of PHP 8.3.0, because this will implicitly cast the value to int in the future.

The decrement operator has no effect on non- numeric string. A `E_WARNING` is emitted as of PHP 8.3.0, because a TypeError will be thrown in the future.

> Note:

> Internal objects that support overloading addition and/or subtraction can also be incremented and/or decremented. One such internal object is GMP.

### PERL string increment feature

Warning

This feature is soft-deprecated as of PHP 8.3.0. The str_increment() function should be used instead.

It is possible to increment a non- numeric string in PHP. The string must be an alphanumerical ASCII string. Which increments letters up to the next letter, when reaching the letter `Z` the increment is carried to the value on the left. For example, `$a = 'Z'; $a++;` turns $a into `'AA'`.

Example #2 PERL string increment example

`<?php
echo '== Alphabetic strings ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
echo ++$s . PHP_EOL;
}
// Alphanumeric strings behave differently
echo '== Alphanumeric strings ==' . 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:

    == Alphabetic strings ==
    X
    Y
    Z
    AA
    AB
    AC
    == Alphanumeric strings ==
    A9
    B0
    B1
    B2
    B3
    B4
    A09
    A10
    A11
    A12
    A13
    A14

Warning

If the alphanumerical string can be interpreted as a numeric string it will be cast to an int or float. This is particularly an issue with strings that look like a floating point numbers written in exponential notation. The str_increment() function does not suffer from these implicit type cast.

Example #3 Alphanumerical string converted to float

`<?php
$s = "5d9";
var_dump(++$s);
var_dump(++$s);
?>`

The above example will output:

    string(3) "5e0"
    float(6)

This is because the value `"5e0"` is interpreted as a float and cast to the value `5.0` before being incremented.

## Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "`$a = 3`" is 3. This allows you to do some tricky things:

Example #1 Nested Assignments

`<?php
$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.
var_dump($a);
?>`

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:

Example #2 Combined Assignments

`<?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!";
var_dump($a, $b);
?>`

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. Objects may be explicitly copied via the clone keyword.

### Assignment by Reference

Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #3 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
?>`

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

Example #4 new Operator By-Reference

`<?php
class C {}
$o = &new C;
?>`

The above example will output:

    Parse error: syntax error, unexpected token ";", expecting "("

More information on references and their potential uses can be found in the References Explained section of the manual.

### Arithmetic Assignment Operators

Example | Equivalent | Operation
--- | --- | ---
$a += $b | $a = $a + $b | Addition
$a -= $b | $a = $a - $b | Subtraction
$a *= $b | $a = $a * $b | Multiplication
$a /= $b | $a = $a / $b | Division
$a %= $b | $a = $a % $b | Modulus
$a **= $b | $a = $a ** $b | Exponentiation

### Bitwise Assignment Operators

Example | Equivalent | Operation
--- | --- | ---
$a &= $b | $a = $a & $b | Bitwise And
$a |= $b | $a = $a | $b | Bitwise Or
$a ^= $b | $a = $a ^ $b | Bitwise Xor
$a <<= $b | $a = $a << $b | Left Shift
$a >>= $b | $a = $a >> $b | Right Shift

### Other Assignment Operators

Example | Equivalent | Operation
--- | --- | ---
$a .= $b | $a = $a . $b | String Concatenation
$a ??= $b | $a = $a ?? $b | Null Coalesce

### See Also

- arithmetic operators
- bitwise operators
- null coalescing operator

## Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Bitwise Operators
Example | Name | Result
--- | --- | ---
`$a & $b` | And | Bits that are set in both $a and $b are set.
`$a | $b` | Or (inclusive or) | Bits that are set in either $a or $b are set.
`$a ^ $b` | Xor (exclusive or) | Bits that are set in $a or $b but not both are set.
`~ $a` | Not | Bits that are set in $a are not set, and vice versa.
`$a << $b` | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two")
`$a >> $b` | Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence. For example, `$a & $b == true` evaluates the equivalency then the bitwise and; while `($a & $b) == true` evaluates the bitwise and then the equivalency.

If both operands for the `&`, `|` and `^` operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

If the operand for the `~` operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers.

Both operands and the result for the `<<` and `>>` operators are always treated as integers.

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, PHP_EOL; // Outputs '5'
echo "12" ^ "9", PHP_EOL; // Outputs the Backspace character (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
echo "hallo" ^ "hello", PHP_EOL; // Outputs the ascii values #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
echo 2 ^ "3", PHP_EOL; // Outputs 1
// 2 ^ ((int) "3") == 1
echo "2" ^ 3, PHP_EOL; // 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\n";
}
?>`

Output of the above example on 32 bit machines:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Output of the above example on 64 bit machines:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Warning

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

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators
Example | Name | Result
--- | --- | ---
$a == $b | Equal | `true` if $a is equal to $b after type juggling.
$a === $b | Identical | `true` if $a is equal to $b, and they are of the same type.
$a != $b | Not equal | `true` if $a is not equal to $b after type juggling.
$a <> $b | Not equal | `true` if $a is not equal to $b after type juggling.
$a !== $b | Not identical | `true` if $a is not equal to $b, or they are not of the same type.
$a < $b | Less than | `true` if $a is strictly less than $b.
$a > $b | Greater than | `true` if $a is strictly greater than $b.
$a <= $b | Less than or equal to | `true` if $a is less than or equal to $b.
$a >= $b | Greater than or equal to | `true` if $a is greater than or equal to $b.
$a <=> $b | Spaceship | An int less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b, respectively.

If both operands are numeric strings, or one operand is a number and the other one is a numeric string, then the comparison is done 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.

Warning

Prior to PHP 8.0.0, if a string is compared to a number or a numeric string then the string was converted to a number before performing the comparison. This can lead to surprising results as can be seen with the following example:

`<?php
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");
switch ("a") {
case 0:
echo "0";
break;
case "a":
echo "a";
break;
}
?>`

Output of the above example in PHP 7:

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

Output of the above example in PHP 8:

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

Example #1 Comparison Operators

`<?php
// Integers
echo 1 <=> 1, ' '; // 0
echo 1 <=> 2, ' '; // -1
echo 2 <=> 1, ' '; // 1
// Floats
echo 1.5 <=> 1.5, ' '; // 0
echo 1.5 <=> 2.5, ' '; // -1
echo 2.5 <=> 1.5, ' '; // 1
// Strings
echo "a" <=> "a", ' '; // 0
echo "a" <=> "b", ' '; // -1
echo "b" <=> "a", ' '; // 1
echo "a" <=> "aa", ' '; // -1
echo "zz" <=> "aa", ' '; // 1
// Arrays
echo [] <=> [], ' '; // 0
echo [1, 2, 3] <=> [1, 2, 3], ' '; // 0
echo [1, 2, 3] <=> [], ' '; // 1
echo [1, 2, 3] <=> [1, 2, 1], ' '; // 1
echo [1, 2, 3] <=> [1, 2, 4], ' '; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b, ' '; // 0
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b, ' '; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b, ' '; // 1
// not only values are compared; keys must match
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b, ' '; // 1
?>`

For various types, comparison is done according to the following table (in order).

Comparison with Various Types
Type of Operand 1 | Type of Operand 2 | Result
--- | --- | ---
null or string | string | Convert `null` to "", numerical or lexical comparison
bool or null | anything | Convert both sides to bool, `false` < `true`
object | object | Built-in classes can define its own comparison, different classes are incomparable, same class see Object Comparison
string, resource, int or float | string, resource, int or float | 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 incomparable, otherwise - compare value by value (see following example)
object | anything | object is always greater
array | anything | array is always greater

Example #2 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 #3 Transcription of standard array comparison

`<?php
// Arrays are compared like this with standard comparison operators as well as the spaceship operator.
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 1;
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>`
Warning

# Comparison of floating point numbers

Because of the way floats are represented internally, you should not test two floats for equality.

See the documentation for float for more information.

> Note: Be aware that PHP's type juggling is not always obvious when comparing values of different types, particularly comparing ints to bools or ints to strings. It is therefore generally advisable to use `===` and `!==` comparisons rather than `==` and `!=` in most cases.

### Incomparable Values

While identity comparison (`===` and `!==`) can be applied to arbitrary values, the other comparison operators should only be applied to comparable values. The result of comparing incomparable values is undefined, and should not be relied upon.

### See Also

- strcasecmp()
- strcmp()
- Array operators
- Types

### Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #4 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'];
}
?>`
The expression `(expr1) ? (expr2) : (expr3)` evaluates to expr2 if expr1 evaluates to `true`, and expr3 if expr1 evaluates to `false`.

It is possible to leave out the middle part of the ternary operator. Expression `expr1 ?: expr3` evaluates to the result of expr1 if expr1 evaluates to `true`, and expr3 otherwise. expr1 is only evaluated once in this case.

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

> Note:

> It is recommended to avoid "stacking" ternary expressions. PHP's behaviour when using more than one unparenthesized ternary operator within a single expression is non-obvious compared to other languages. Indeed prior to PHP 8.0.0, ternary expressions were evaluated left-associative, instead of right-associative like most other programming languages. Relying on left-associativity is deprecated as of PHP 7.4.0. As of PHP 8.0.0, the ternary operator is non-associative.

> Example #5 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' prior to PHP 8.0.0
> // this is because ternary expressions are left-associative
> // the following is a more obvious version of the same code as above
> echo ((true ? 'true' : false) ? 't' : 'f');
> // here, one 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.
> ?>`

> Note:

> Chaining of short-ternaries (`?:`), however, is stable and behaves reasonably. It will evaluate to the first argument that evaluates to a non-falsy value. Note that undefined values will still raise a warning.

> Example #6 Short-ternary chaining

> `<?php
> echo 0 ?: 1 ?: 2 ?: 3, PHP_EOL; //1
> echo 0 ?: 0 ?: 2 ?: 3, PHP_EOL; //2
> echo 0 ?: 0 ?: 0 ?: 3, PHP_EOL; //3
> ?>`

### Null Coalescing Operator

Another useful shorthand operator is the "??" (or null coalescing) operator.

Example #7 Assigning a default value

`<?php
// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';
// The above is identical to this if/else statement
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else {
$action = 'default';
}
?>`
The expression `(expr1) ?? (expr2)` evaluates to expr2 if expr1 is `null`, and expr1 otherwise.

In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

> Note: Please note that the null coalescing 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 $foo ?? $bar;` in a return-by-reference function will therefore not work and a warning is issued.

> Note:

> The null coalescing operator has low precedence. That means if mixing it with other operators (such as string concatenation or arithmetic operators) parentheses will likely be required.

> `<?php
> // Raises a warning that $name is undefined.
> print 'Mr. ' . $name ?? 'Anonymous';
> // Prints "Mr. Anonymous"
> print 'Mr. ' . ($name ?? 'Anonymous');
> ?>`

> Note:

> Please note that the null coalescing operator allows for simple nesting:

> Example #8 Nesting null coalescing operator

> `<?php
> $foo = null;
> $bar = null;
> $baz = 1;
> $qux = 2;
> echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1
> ?>`

## Error Control Operators

PHP supports one error control operator: the at sign (`@`). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed.

If a custom error handler function is set with set_error_handler(), it will still be called even though the diagnostic has been suppressed.

Warning

Prior to PHP 8.0.0, the error_reporting() called inside the custom error handler always returned `0` if the error was suppressed by the `@` operator. As of PHP 8.0.0, it returns the value of this (bitwise) expression: `E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE`.

Any error message generated by the expression is available in the `"message"` element of the array returned by error_get_last(). The result of that function will change on each error, so it needs to be checked early.

Example #1 Intentional file error

`<?php
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '" . error_get_last()['message'] . "'");
?>`

Example #2 Suppressing Expressions

`<?php
// 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 one can take the value of something, then one can prepend the `@` operator to it. For instance, it can be prepended to variables, functions calls, certain language construct calls (e.g. include), and so forth. It cannot be prepended to function or class definitions, or conditional structures such as `if` and `foreach`, and so forth.

Warning

Prior to PHP 8.0.0, it was possible for the `@` operator to disable critical errors that will terminate script execution. For example, prepending `@` to a call of a function which did not exist, by being unavailable or mistyped, would cause the script to terminate with no indication as to why.

### See Also

- error_reporting()
- Error Handling and Logging functions

## Execution Operators

PHP supports one execution operator: backticks (````). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

Example #1 Backtick Operator

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

> Note:

> The backtick operator is disabled when shell_exec() is disabled.

> Note:

> Unlike some other languages, backticks have no special meaning within double-quoted strings.

### Changelog

Version | Description
--- | ---
8.5.0 | The backtick operator as an alias for shell_exec() has been deprecated.

### See Also

- Program Execution functions
- popen()
- proc_open()
- Using PHP from the commandline

## Logical Operators

Logical Operators
Example | Name | Result
--- | --- | ---
$a and $b | And | `true` if both $a and $b are `true`.
$a or $b | Or | `true` if either $a or $b is `true`.
$a xor $b | Xor | `true` if either $a or $b is `true`, but not both.
! $a | Not | `true` if $a is not `true`.
$a && $b | And | `true` if both $a and $b are `true`.
$a || $b | Or | `true` if either $a or $b is `true`.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

Example #1 Logical operators illustrated

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

The above example will output something similar to:

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

## String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('`.=`'), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

Example #1 String Concatenating

`<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
var_dump($b);
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
var_dump($a);
?>`

### See Also

- String type
- String functions

## Array Operators

Array Operators
Example | Name | Result
--- | --- | ---
$a + $b | Union | Union of $a and $b.
$a == $b | Equality | `true` if $a and $b have the same key/value pairs.
$a === $b | Identity | `true` if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b | Inequality | `true` if $a is not equal to $b.
$a <> $b | Inequality | `true` if $a is not equal to $b.
$a !== $b | Non-identity | `true` if $a is not identical to $b.

The `+` operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Example #1 Array Append Operator

`<?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);
$a += $b; // Union of $a += $b is $a and $b
echo "Union of \$a += \$b: \n";
var_dump($a);
?>`

The above example will output:

    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"
    }
    Union of $a += $b:
    array(3) {
      ["a"]=>
      string(5) "apple"
      ["b"]=>
      string(6) "banana"
      ["c"]=>
      string(6) "cherry"
    }

Elements of arrays are equal for the comparison if they have the same key and value.

Example #2 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

- Array type
- Array functions

## Type Operators

`instanceof` is used to determine whether a PHP variable is an instantiated object of a certain class:

Example #1 Using `instanceof` with classes

`<?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` with interfaces

`<?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, were not allowed prior to PHP 7.3.0.

Example #6 Using `instanceof` to test other variables

`<?php
$a = 1;
$b = NULL;
$c = fopen('/tmp/', 'r');
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

As of PHP 7.3.0, constants are allowed on the left-hand-side of the `instanceof` operator.

Example #7 Using `instanceof` to test constants

`<?php
var_dump(FALSE instanceof stdClass);
?>`

Output of the above example in PHP 7.3:

    bool(false)

As of PHP 8.0.0, `instanceof` can now be used with arbitrary expressions. The expression must be wrapped in parentheses and produce a string.

Example #8 Using `instanceof` with an arbitrary expression

`<?php
class ClassA extends \stdClass {}
class ClassB extends \stdClass {}
class ClassC extends ClassB {}
class ClassD extends ClassA {}
function getSomeClass(): string
{
return ClassA::class;
}
var_dump(new ClassA instanceof ('std' . 'Class'));
var_dump(new ClassB instanceof ('Class' . 'B'));
var_dump(new ClassC instanceof ('Class' . 'A'));
var_dump(new ClassD instanceof (getSomeClass()));
?>`

Output of the above example in PHP 8:

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

The `instanceof` operator has a functional variant with the is_a() function.

### See Also

- get_class()
- is_a()

## Functional Operators

PHP 8.5 and later supports one operator that works directly on callables. The `|>` operator, or “pipe,” accepts a single-parameter callable on the right and passes the left-side value to it, evaluating to the callable's result. The callable on the right may be any valid PHP callable: a Closure, a first-class callable, an object that implements __invoke(), etc.

That means the following two lines are logically equivalent.

Example #1 Using `|>`

`<?php
$result = "Hello World" |> strlen(...);
echo $result, PHP_EOL;
$result = strlen("Hello World");
echo $result, PHP_EOL;
?>`

The above example will output:

    11
    11

For a single call that is not especially useful. It becomes useful when multiple calls are chained together. That is, the following two code fragments are logically equivalent:

Example #2 Chaining |> calls

`<?php
$result = "PHP Rocks"
|> htmlentities(...)
|> str_split(...)
|> (fn($x) => array_map(strtoupper(...), $x))
|> (fn($x) => array_filter($x, fn($v) => $v != 'O'))
;
print_r($result);
$temp = "PHP Rocks";
$temp = htmlentities($temp);
$temp = str_split($temp);
$temp = array_map(strtoupper(...), $temp);
$temp = array_filter($temp, fn($v) => $v != 'O');
$result = $temp;
print_r($result);
?>`

The above example will output:

    Array
    (
        [0] => P
        [1] => H
        [2] => P
        [3] =>
        [4] => R
        [6] => C
        [7] => K
        [8] => S
    )
    Array
    (
        [0] => P
        [1] => H
        [2] => P
        [3] =>
        [4] => R
        [6] => C
        [7] => K
        [8] => S
    )

The left-hand side of the pipe may be any value or expression. The right-hand side may be any valid PHP callable that takes a single parameter, or any expression that evaluates to such a callable. Functions with more than one required parameter are not allowed and will fail as if the function were called normally with insufficient arguments. Functions that take a variable by reference are not allowed. If the right-hand side does not evaluate to a valid callable it will throw an Error.

> Note:

> Be aware that, to avoid syntax ambiguity, arrow functions MUST be wrapped in parentheses when used with a pipe operator, as in the examples above. Failing to do so will result in a fatal error.

### See Also

- Closure

# Control Structures

## Table of Contents

- Introduction
- if
- else
- elseif/else if
- Alternative syntax for control structures
- while
- do-while
- for
- foreach
- break
- continue
- switch
- match
- declare
- return
- require
- include
- require_once
- include_once
- goto

## Introduction

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.

### See Also

The following are also considered language constructs even though they are referenced under functions in the manual.

- list()
- array()
- echo
- eval()
- print

## if

(PHP 4, PHP 5, PHP 7, PHP 8)

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.

## else

(PHP 4, PHP 5, PHP 7, PHP 8)

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";
}
?>`
The `else` statement is only executed if the `if` expression evaluated to `false`, and if there were any `elseif` expressions - only if they evaluated to `false` as well (see elseif).

> Note: Dangling else

> In case of nested `if`-`else` statements, an `else` is always associated with the nearest `if`.

> `<?php
> $a = false;
> $b = true;
> if ($a)
> if ($b)
> echo "b";
> else
> echo "c";
> ?>`
> Despite the indentation (which does not matter for PHP), the `else` is associated with the `if ($b)`, so the example does not produce any output. While relying on this behavior is valid, it is recommended to avoid it by using curly braces to resolve potential ambiguities.

## elseif/else if

(PHP 4, PHP 5, PHP 7, PHP 8)

`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 `elseif`s within the same `if` statement. The first `elseif` expression (if any) that evaluates to `true` would be executed. In PHP, it's possible to 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 (the same behavior as C) 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 `if`/`elseif` conditions, the use of `elseif` in a single word becomes necessary. PHP will fail with a parse error if `else if` is split into two words.

`<?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;`
`<?php
/* 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;
?>`

## Alternative syntax for control structures

(PHP 4, PHP 5, PHP 7, PHP 8)

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.

Warning

Any output (including whitespace) between a `switch` statement and the first `case` will result in a syntax error. For example, this is invalid:

`<?php switch ($foo): ?>
<?php case 1: ?>
// ...
<?php endswitch; ?>`

Whereas this is valid, as the trailing newline after the `switch` statement is considered part of the closing `?>` and hence nothing is output between the `switch` and `case`:

`<?php switch ($foo): ?>
<?php case 1: ?>
...
<?php endswitch; ?>`

See also while, for, and if for further examples.

## while

(PHP 4, PHP 5, PHP 7, PHP 8)

`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). If the `while` expression evaluates to `false` from the very beginning, the nested statement(s) won't even be run once.

Like with the `if` statement, you can group multiple statements within the same `while` loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

    while (expr):
        statement
        ...
    endwhile;

The following examples are identical, and both print the numbers 1 through 10:

`<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>`

## do-while

(PHP 4, PHP 5, PHP 7, PHP 8)

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

It is possible to use the `goto` operator instead of this hack.

## for

(PHP 4, PHP 5, PHP 7, PHP 8)

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

    for (expr1; expr2; expr3)
        statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to `true`, the loop continues and the nested statement(s) are executed. If it evaluates to `false`, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as `true`, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional `break` statement instead of using the `for` truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

`<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>`

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in `for` loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for `for` loops.

    for (expr1; expr2; expr3):
        statement
        ...
    endfor;

It's a common thing to many users to iterate through arrays like in the example below.

`<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = array(
array('name' => 'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < count($people); ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>`

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

`<?php
$people = array(
array('name' => 'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>`

## foreach

(PHP 4, PHP 5, PHP 7, PHP 8)

The `foreach` construct provides an easy way to iterate over arrays and Traversable objects. `foreach` will issue an error when used with a variable containing a different data type or with an uninitialized variable.

`foreach` can optionally get the `key` of each element:

    foreach (iterable_expression as $value) {
        statement_list
    }

    foreach (iterable_expression as $key => $value) {
        statement_list
    }

The first form traverses the iterable given by `iterable_expression`. On each iteration, the value of the current element is assigned to `$value`.

The second form will additionally assign the current element's key to the `$key` variable on each iteration.

Note that `foreach` does not modify the internal array pointer, which is used by functions such as current() and key().

It is possible to customize object iteration.

Example #1 Common `foreach` usages

`<?php
/* Example: value only */
$array = [1, 2, 3, 17];
foreach ($array as $value) {
echo "Current element of \$array: $value.\n";
}
/* Example: key and value */
$array = [
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
];
foreach ($array as $key => $value) {
echo "Key: $key => Value: $value\n";
}
/* Example: multi-dimensional key-value arrays */
$grid = [];
$grid[0][0] = "a";
$grid[0][1] = "b";
$grid[1][0] = "y";
$grid[1][1] = "z";
foreach ($grid as $y => $row) {
foreach ($row as $x => $value) {
echo "Value at position x=$x and y=$y: $value\n";
}
}
/* Example: dynamic arrays */
foreach (range(1, 5) as $value) {
echo "$value\n";
}
?>`

> Note:

> `foreach` does not support the ability to suppress error messages using the `@`.

### Unpacking nested arrays

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

It is possible to iterate over an array of arrays and unpack the nested array into loop variables by using either array destructuring via `[]` or by using the list() language construct as the value.

> Note: Please note that array destructuring via `[]` is only possible as of PHP 7.1.0

In both of the following examples `$a` will be set to the first element of the nested array and `$b` will contain the second element:

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

The above example will output:

    A: 1; B: 2
    A: 3; B: 4

When providing fewer variables than there are elements in the array, the remaining elements will be ignored. Similarly, elements can be skipped over by using a comma:

`<?php
$array = [
[1, 2, 5],
[3, 4, 6],
];
foreach ($array as [$a, $b]) {
// Note that there is no $c here.
echo "$a $b\n";
}
foreach ($array as [, , $c]) {
// Skipping over $a and $b
echo "$c\n";
}
?>`

The above example will output:

    1 2
    3 4
    5
    6

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 [$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:

### foreach and references

It is possible to directly modify array elements within a loop by preceding `$value` with `&`. In that case the value will be assigned by reference.

`<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now [2, 4, 6, 8]
unset($value); // break the reference with the last element
?>`
Warning

Reference to a `$value` of the last array element remain even after the `foreach` loop. It is recommended to destroy these using unset(). Otherwise, the following behavior will occur:

`<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now [2, 4, 6, 8]
// without an unset($value), $value is still a reference to the last item: $arr[3]
foreach ($arr as $key => $value) {
// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
?>`

The above example will output:

    0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
    1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
    2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
    3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )

Example #2 Iterate a constant array's values by reference

`<?php
foreach ([1, 2, 3, 4] as &$value) {
$value = $value * 2;
}
?>`

### See Also

- array
- Traversable
- iterable
- list()

## break

(PHP 4, PHP 5, PHP 7, PHP 8)

`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. The default value is `1`, only the immediate enclosing structure is broken out of.

`<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>`

## continue

(PHP 4, PHP 5, PHP 7, PHP 8)

`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: In PHP the switch statement is considered a looping structure for the purposes of `continue`. `continue` behaves like `break` (when no arguments are passed) but will raise a warning as this is likely to be a mistake. If a `switch` is inside a loop, `continue 2` will continue with the next iteration of the outer loop.

`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
$arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
foreach ($arr as $key => $value) {
if (0 === ($key % 2)) { // skip members with even key
continue;
}
echo $value . "\n";
}
?>`

The above examples will output:

    one
    three
    five

`<?php
$i = 0;
while ($i++ < 5) {
echo "Outer\n";
while (1) {
echo "Middle\n";
while (1) {
echo "Inner\n";
continue 3;
}
echo "This never gets output.\n";
}
echo "Neither does this.\n";
}
?>`

The above examples will output:

    Outer
    Middle
    Inner
    Outer
    Middle
    Inner
    Outer
    Middle
    Inner
    Outer
    Middle
    Inner
    Outer
    Middle
    Inner

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

Changelog for `continue`
Version | Description
--- | ---
7.3.0 | `continue` within a `switch` that is attempting to act like a `break` statement for the `switch` will trigger an `E_WARNING`.

## switch

(PHP 4, PHP 5, PHP 7, PHP 8)

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

In the following example, each code block is equivalent. One uses a series of `if` and `elseif` statements, and the other a `switch` statement. In each case, the output is the same.

Example #1 `switch` structure

`<?php
// This switch statement:
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
// Is equivalent to:
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
?>`

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 whose expression evaluates to 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";
}
?>`

> Note: Multiple default cases will raise a `E_COMPILE_ERROR` error.

> Note: Technically the `default` case may be listed in any order. It will only be used if no other case matches. However, by convention it is best to place it at the end as the last branch.

If no `case` branch matches, and there is no `default` branch, then no code will be executed, just as if no `if` statement was true.

A case value may be given as an expression. However, that expression will be evaluated on its own and then loosely compared with the switch value. That means it cannot be used for complex evaluations of the switch value. For example:

`<?php
$target = 1;
$start = 3;
switch ($target) {
case $start - 1:
print "A";
break;
case $start - 2:
print "B";
break;
case $start - 3:
print "C";
break;
case $start - 4:
print "D";
break;
}
// Prints "B"
?>`

For more complex comparisons, the value `true` may be used as the switch value. Or, alternatively, `if`-`else` blocks instead of `switch`.

`<?php
$offset = 1;
$start = 3;
switch (true) {
case $start - $offset === 1:
print "A";
break;
case $start - $offset === 2:
print "B";
break;
case $start - $offset === 3:
print "C";
break;
case $start - $offset === 4:
print "D";
break;
}
// Prints "B"
?>`

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 'stella';
case 'heineken';
echo 'Good choice';
break;
default;
echo 'Please make a new selection...';
break;
}
?>`

### See Also

- match

## match

(PHP 8)

The `match` expression branches evaluation based on an identity check of a value. Similarly to a `switch` statement, a `match` expression has a subject expression that is compared against multiple alternatives. Unlike `switch`, it will evaluate to a value much like ternary expressions. Unlike `switch`, the comparison is an identity check (`===`) rather than a weak equality check (`==`). Match expressions are available as of PHP 8.0.0.

Example #1 Structure of a `match` expression

`<?php
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
?>`

Example #2 Basic `match` usage

`<?php
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
?>`

The above example will output:

    string(19) "This food is a cake"

Example #3 Example of using `match` with comparison operators

`<?php
$age = 18;
$output = match (true) {
$age < 2 => "Baby",
$age < 13 => "Child",
$age <= 19 => "Teenager",
$age >= 40 => "Old adult",
$age > 19 => "Young adult",
};
var_dump($output);
?>`

The above example will output:

    string(8) "Teenager"

> Note: The result of a `match` expression does not need to be used.

> Note: When a `match` expression is used as a standalone expression it must be terminated by a semicolon `;`.

The `match` expression is similar to a `switch` statement but has some key differences:

- A `match` arm compares values strictly (`===`) instead of loosely as the switch statement does.
- A `match` expression returns a value.
- `match` arms do not fall-through to later cases the way `switch` statements do.
- A `match` expression must be exhaustive.

As `switch` statements, `match` expressions are executed match arm by match arm. In the beginning, no code is executed. The conditional expressions are only evaluated if all previous conditional expressions failed to match the subject expression. Only the return expression corresponding to the matching conditional expression will be evaluated. For example:

`<?php
$result = match ($x) {
foo() => 'value',
$this->bar() => 'value', // $this->bar() isn't called if foo() === $x
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
// etc.
};
?>`

`match` expression arms may contain multiple expressions separated by a comma. That is a logical OR, and is a short-hand for multiple match arms with the same right-hand side.

`<?php
$result = match ($x) {
// This match arm:
$a, $b, $c => 5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};
?>`

A special case is the `default` pattern. This pattern matches anything that wasn't previously matched. For example:

`<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>`

> Note: Multiple default patterns will raise a `E_FATAL_ERROR` error.

A `match` expression must be exhaustive. If the subject expression is not handled by any match arm an UnhandledMatchError is thrown.

Example #4 Example of an unhandled match expression

`<?php
$condition = 5;
try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>`

The above example will output:

    object(UnhandledMatchError)#1 (7) {
      ["message":protected]=>
      string(33) "Unhandled match value of type int"
      ["string":"Error":private]=>
      string(0) ""
      ["code":protected]=>
      int(0)
      ["file":protected]=>
      string(9) "/in/ICgGK"
      ["line":protected]=>
      int(6)
      ["trace":"Error":private]=>
      array(0) {
      }
      ["previous":"Error":private]=>
      NULL
    }

### Using match expressions to handle non identity checks

It is possible to use a `match` expression to handle non-identity conditional cases by using `true` as the subject expression.

Example #5 Using a generalized match expressions to branch on integer ranges

`<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
?>`

The above example will output:

    string(11) "young adult"

Example #6 Using a generalized match expressions to branch on string content

`<?php
$text = 'Bienvenue chez nous';
$result = match (true) {
str_contains($text, 'Welcome'), str_contains($text, 'Hello') => 'en',
str_contains($text, 'Bienvenue'), str_contains($text, 'Bonjour') => 'fr',
// ...
};
var_dump($result);
?>`

The above example will output:

    string(2) "fr"

## declare

(PHP 4, PHP 5, PHP 7, PHP 8)

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 three directives are recognized:

- `ticks`
- `encoding`
- `strict_types`

As directives are handled as the file is being compiled, only literals may be given as directive values. Variables and constants cannot be used. To illustrate:

`<?php
// This is valid:
declare(ticks=1);
// This is invalid:
const TICK_VALUE = 1;
declare(ticks=TICK_VALUE);
?>`

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
?>`

### Ticks

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` block'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'); // causes a tick event
$a = 1; // causes a tick event
if ($a > 0) {
$a += 2; // causes a tick event
print $a; // causes a tick event
}
?>`

See also register_tick_function() and unregister_tick_function().

### Encoding

A script's encoding can be specified per-script using the `encoding` directive.

Example #2 Declaring an encoding for the script

`<?php
declare(encoding='ISO-8859-1');
// code here
?>`
Caution

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.

See also zend.script_encoding.

## return

(PHP 4, PHP 5, PHP 7, PHP 8)

`return` returns program control to the calling module. Execution resumes at the expression following the called module's invocation.

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` also ends 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 argument are not required and their use is discouraged.

> Note: If no parameter is supplied, then the parentheses must be omitted and `null` will be returned. Calling `return` with parentheses but with no arguments will result in a parse error.

As of PHP 7.1.0, return statements without an argument in functions which declare a return type trigger `E_COMPILE_ERROR`, unless the return type is void, in which case return statements with an argument trigger that error.

## require

(PHP 4, PHP 5, PHP 7, PHP 8)

`require` is identical to include except upon failure it will also produce an Error exception (`E_COMPILE_ERROR` level error prior to PHP 8.0.0) whereas include will only produce a warning (`E_WARNING` level error).

See the include documentation for how this works.

## include

(PHP 4, PHP 5, PHP 7, PHP 8)

The `include` expression 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 an `E_WARNING` if it cannot find a file; this is different behavior from require, which will emit an `E_ERROR`.

Note that both `include` and `require` raise additional `E_WARNING`s, if the file cannot be accessed, before raising the final `E_WARNING` or `E_ERROR`, respectively.

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.

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';
?>`
Warning

# Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: `include` returns `FALSE` on failure and raises a warning. Successful includes, unless overridden by the included file, return `1`. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because `include` is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example #4 Comparing return value of include

`<?php
// won't work, evaluated as include(('vars.php') == TRUE), i.e. include('1')
if (include('vars.php') == TRUE) {
echo 'OK';
}
// works
if ((include 'vars.php') == TRUE) {
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 will raise a fatal error because the functions were already declared. 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, or named arguments.

See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.

## require_once

(PHP 4, PHP 5, PHP 7, PHP 8)

The `require_once` expression is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once documentation for information about the `_once` behaviour, and how it differs from its non `_once` siblings.

## include_once

(PHP 4, PHP 5, PHP 7, PHP 8)

The `include_once` expression includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include expression, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns `true`. As the name suggests, the file 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.

## goto

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Image courtesy of » xkcd

The `goto` operator can be used to jump to another section in the program. The target point is specified by a case-sensitive 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

# Functions

## Table of Contents

- User-defined functions
- Function parameters and arguments
- Returning values
- Variable functions
- Internal (built-in) functions
- Anonymous functions
- Arrow Functions
- First class callable syntax

## User-defined functions

A function is defined using the `function` keyword, a name, a list of parameters (which might be empty) separated by commas (`,`) enclosed in parentheses, followed by the body of the function enclosed in curly braces, such as the following:

Example #1 Declaring a new function named `foo`

`<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>`

> Note:

> As of PHP 8.0.0, the list of parameters may have a trailing comma:

> `<?php
> function foo($arg_1, $arg_2,) { }
> ?>`

Any valid PHP code may appear inside the body of 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_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$`.

Tip

See also the Userland Naming Guide.

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example #2 Conditional functions

`<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
?>`

Example #3 Functions within functions

`<?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 for the ASCII characters `A` to `Z`, 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.

Example #4 Recursive functions

`<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>`

> Note: Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error.

## Function parameters and arguments

The function parameters are declared in the function signature. 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 and the result is assigned to the parameters of the function, before the function is actually called (eager evaluation).

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported.

> Note:

> As of PHP 7.3.0, it is possible to have a trailing comma in the argument list for a function calls:

> `<?php
> $v = foo(
> $arg_1,
> $arg_2,
> );
> ?>`

As of PHP 8.0.0, the list of function parameters may include a trailing comma, which will be ignored. That is particularly useful in cases where the list of parameters is long or contains long variable names, making it convenient to list parameters vertically.

Example #1 Function parameter list with trailing comma

`<?php
function takes_many_args(
$first_arg,
$second_arg,
$a_very_long_argument_name,
$arg_with_default = 5,
$again = 'a default string', // This trailing comma was not permitted before 8.0.0.
)
{
// ...
}
?>`

### Passing arguments by reference

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

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

Example #2 Passing function arguments 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.'
?>`

It is an error to pass a constant expression as an argument to a parameter that expects to be passed by reference.

### Default parameter values

A function may define default values for parameters using syntax similar to assigning a variable. The default is used only when the parameter's argument is not passed. Note that passing `null` does not assign the default value.

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.

Default parameter values may be scalar values, arrays, the special type `null`, and as of PHP 8.1.0, objects using the new ClassName() syntax.

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 above example will output:

    Making a cup of cappuccino with hands.
    Making a cup of cappuccino, lavazza with teapot.

Example #5 Using objects as default values (as of PHP 8.1.0)

`<?php
class DefaultCoffeeMaker {
public function brew() {
return "Making coffee.\n";
}
}
class FancyCoffeeMaker {
public function brew() {
return "Crafting a beautiful coffee just for you.\n";
}
}
function makecoffee($coffeeMaker = new DefaultCoffeeMaker)
{
return $coffeeMaker->brew();
}
echo makecoffee();
echo makecoffee(new FancyCoffeeMaker);
?>`

The above example will output:

    Making coffee.
    Crafting a beautiful coffee just for you.

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that any optional parameters should be specified after any required parameters, otherwise they cannot be omitted from calls. Consider the following example:

Example #6 Incorrect usage of default function parameters

`<?php
function makeyogurt($container = "bowl", $flavour)
{
return "Making a $container of $flavour yogurt.\n";
}
echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour
?>`

The above example will output:

    Fatal error: Uncaught ArgumentCountError: Too few arguments
     to function makeyogurt(), 1 passed in example.php on line 42

Now, compare the above with this:

Example #7 Correct usage of default function parameters

`<?php
function makeyogurt($flavour, $container = "bowl")
{
return "Making a $container of $flavour yogurt.\n";
}
echo makeyogurt("raspberry"); // "raspberry" is $flavour
?>`

The above example will output:

    Making a bowl of raspberry yogurt.

As of PHP 8.0.0, named arguments can be used to skip over multiple optional parameters.

Example #8 Correct usage of default function parameters

`<?php
function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek")
{
return "Making a $container of $flavour $style yogurt.\n";
}
echo makeyogurt(style: "natural");
?>`

The above example will output:

    Making a bowl of raspberry natural yogurt.

As of PHP 8.0.0, declaring mandatory parameters after optional parameters is deprecated. This can generally be resolved by dropping the default value, since it will never be used. One exception to this rule are parameters of the form `Type $param = null`, where the `null` default makes the type implicitly nullable. This usage is deprecated as of PHP 8.4.0, and an explicit nullable type should be used instead.

Example #9 Declaring optional parameters after mandatory parameters

`<?php
function foo($a = [], $b) {} // Default not used; deprecated as of PHP 8.0.0
function foo($a, $b) {} // Functionally equivalent, no deprecation notice
function bar(A $a = null, $b) {} // As of PHP 8.1.0, $a is implicitly required
// (because it comes before the required one),
// but implicitly nullable (deprecated as of PHP 8.4.0),
// because the default parameter value is null
function bar(?A $a, $b) {} // Recommended
?>`

> Note: As of PHP 7.1.0, omitting a parameter which does not specify a default throws an ArgumentCountError; in previous versions it raised a Warning.

> Note: Parameters that expect the argument by reference may have a default value.

### Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions by using the `...` token.

Parameter lists may include the `...` token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array:

Example #10 Using `...` to access variable arguments

`<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>`

The above example will output:

    10

`...` can also be used when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #11 Using `...` to provide arguments

`<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>`

The above example will output:

    3
    3

You may specify normal positional parameters before the `...` token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by `...`.

It is also possible to add a type declaration before the `...` token. If this is present, then all arguments captured by `...` must match that parameter type.

Example #12 Type declared variable arguments

`<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}
$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';
// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>`

The above example will output:

    3 days
    Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

Finally, variable arguments can also be passed by reference by prefixing the `...` with an ampersand (`&`).

### Named Arguments

PHP 8.0.0 introduced named arguments as an extension of the existing positional parameters. Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent and allows skipping default values arbitrarily.

Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed.

Example #13 Named argument syntax

`<?php
myFunction(paramName: $value);
array_foobar(array: $value);
// NOT supported.
function_name($variableStoringParamName: $value);
?>`

Example #14 Positional arguments versus named arguments

`<?php
// Using positional arguments:
array_fill(0, 100, 50);
// Using named arguments:
array_fill(start_index: 0, count: 100, value: 50);
?>`

The order in which the named arguments are passed does not matter.

Example #15 Same example as above with a different order of parameters

`<?php
array_fill(value: 50, count: 100, start_index: 0);
?>`

Named arguments can be combined with positional arguments. In this case, the named arguments must come after the positional arguments. It is also possible to specify only some of the optional arguments of a function, regardless of their order.

Example #16 Combining named arguments with positional arguments

`<?php
htmlspecialchars($string, double_encode: false);
// Same as
htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false);
?>`

Passing an argument to the same named parameter multiple times results in an Error exception.

Example #17 Error thrown when passing an argument to the same named parameter multiple times

`<?php
function foo($param) { ... }
foo(param: 1, param: 2);
// Error: Named parameter $param overwrites previous argument
foo(1, param: 2);
// Error: Named parameter $param overwrites previous argument
?>`

As of PHP 8.1.0, it is possible to use named arguments after unpacking the arguments. A named argument must not override an already unpacked argument.

Example #18 Use named arguments after unpacking

`<?php
function foo($a, $b, $c = 3, $d = 4) {
return $a + $b + $c + $d;
}
var_dump(foo(...[1, 2], d: 40)); // 46
var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46
var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument
?>`

## Returning values

Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.

> Note:

> If the return is omitted the value `null` will be returned.

### Use of return

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 [0, 1, 2];
}
// Array destructuring will collect each member of the array individually
[$zero, $one, $two] = small_numbers();
// Prior to 7.1.0, the only equivalent alternative is using list() construct
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.

## Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

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

Example #4 Complex callables

`<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar"
?>`

### See Also

- is_callable()
- call_user_func()
- function_exists()
- variable variables

## Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysqli_connect(), PHP must be compiled with MySQLi support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP.

Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.

> Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return `null` but this is just a convention, and cannot be relied upon. As of PHP 8.0.0, a TypeError exception is supposed to be thrown in this case.

> Note:

> Scalar types for built-in functions are nullable by default in coercive mode. As of PHP 8.1.0, passing `null` to an internal function parameter that is not declared nullable is discouraged and emits a deprecation notice in coercive mode to align with the behavior of user-defined functions, where scalar types need to be marked as nullable explicitly.

> For example, strlen() function expects the parameter `$string` to be a non-nullable string. For historical reasons, PHP allows passing `null` for this parameter in coercive mode, and the parameter is implicitly cast to string, resulting in a `""` value. In contrast, a TypeError is emitted in strict mode.

> `<?php
> var_dump(strlen(null));
> // "Deprecated: Passing null to parameter #1 ($string) of type string is deprecated" as of PHP 8.1.0
> // int(0)
> var_dump(str_contains("foobar", null));
> // "Deprecated: Passing null to parameter #2 ($needle) of type string is deprecated" as of PHP 8.1.0
> // bool(true)
> ?>`

### See Also

- function_exists()
- the function reference
- get_extension_funcs()
- dl()

## Anonymous functions

Anonymous functions, also known as `closures`, allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses.

Anonymous functions are implemented using the Closure class.

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. As of PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter. A return type declaration of the function has to be placed after the `use` clause.

Example #3 Inheriting variables from the parent scope

`<?php
$message = 'hello';
// No "use"
$example = function () {
var_dump($message);
};
$example();
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
$example();
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
$example();
// Reset message
$message = 'hello';
// Inherit by-reference
$example = function () use (&$message) {
var_dump($message);
};
$example();
// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
$example();
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");
// Return type declaration comes after the use clause
$example = function () use ($message): string {
return "hello $message";
};
var_dump($example());
?>`

The above example will output something similar to:

    Notice: Undefined variable: message in /example.php on line 6
    NULL
    string(5) "hello"
    string(5) "hello"
    string(5) "hello"
    string(5) "world"
    string(11) "hello world"
    string(11) "hello world"

As of PHP 8.0.0, the list of scope-inherited variables may include a trailing comma, which will be ignored.

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 #4 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
?>`

Example #5 Automatic binding of `$this`

`<?php
class Test
{
public function testing()
{
return function() {
var_dump($this);
};
}
}
$object = new Test;
$function = $object->testing();
$function();
?>`

The above example will output:

    object(Test)#1 (0) {
    }

When declared in the context of a class, the current class is automatically bound to it, making `$this` available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead.

### Static anonymous functions

Anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime.

Example #6 Attempting to use `$this` inside a static anonymous function

`<?php
class Foo
{
function __construct()
{
$func = static function() {
var_dump($this);
};
$func();
}
};
new Foo();
?>`

The above example will output:

    Notice: Undefined variable: this in %s on line %d
    NULL

Example #7 Attempting to bind an object to a static anonymous function

`<?php
$func = static function() {
// function body
};
$func = $func->bindTo(new stdClass);
$func();
?>`

The above example will output:

    Warning: Cannot bind an instance to a static closure in %s on line %d

### Changelog

Version | Description
--- | ---
8.3.0 | Closures created from magic methods can accept named parameters.
7.1.0 | Anonymous functions may not close over superglobals, $this, or any variable with the same name as a parameter.

### Notes

> Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

## Arrow Functions

Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions.

Both anonymous functions and arrow functions are implemented using the Closure class.

Arrow functions have the basic form `fn (argument_list) => expr`.

Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic.

When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions $fn1 and $fn2 behave the same way.

Example #1 Arrow functions capture variables by value automatically

`<?php
$y = 1;
$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
?>`

The above example will output:

    4

This also works if the arrow functions are nested:

Example #2 Arrow functions capture variables by value automatically, even when nested

`<?php
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// Outputs 51
var_export($fn(5)(10));
?>`

Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions:

Example #3 Examples of arrow functions

`<?php
fn(array $x) => $x;
static fn($x): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;
?>`

Arrow functions use by-value variable binding. This is roughly equivalent to performing a `use($x)` for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings.

Example #4 Values from the outer scope cannot be modified by arrow functions

`<?php
$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_export($x); // Outputs 1
?>`

### Changelog

Version | Description
--- | ---
7.4.0 | Arrow functions became available.

### Notes

> Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within an arrow function.

## First class callable syntax

The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating anonymous functions from callable. It supersedes existing callable syntax using strings and arrays. The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired.

`CallableExpr(...)` syntax is used to create a Closure object from callable. `CallableExpr` accepts any expression that can be directly called in the PHP grammar:

Example #1 Simple first class callable syntax

`<?php
class Foo {
public function method() {}
public static function staticmethod() {}
public function __invoke() {}
}
$obj = new Foo();
$classStr = 'Foo';
$methodStr = 'method';
$staticmethodStr = 'staticmethod';
$f1 = strlen(...);
$f2 = $obj(...); // invokable object
$f3 = $obj->method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);
// traditional callable using string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
?>`

> Note:

> The `...` is part of the syntax, and not an omission.

`CallableExpr(...)` has the same semantics as Closure::fromCallable(). That is, unlike callable using strings and arrays, `CallableExpr(...)` respects the scope at the point where it is created:

Example #2 Scope comparison of `CallableExpr(...)` and traditional callable

`<?php
class Foo {
public function getPrivateMethod() {
return [$this, 'privateMethod'];
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo = new Foo;
$privateMethod = $foo->getPrivateMethod();
$privateMethod();
// Fatal error: Call to private method Foo::privateMethod() from global scope
// This is because call is performed outside from Foo and visibility will be checked from this point.
class Foo1 {
public function getPrivateMethod() {
// Uses the scope where the callable is acquired.
return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo1 = new Foo1;
$privateMethod = $foo1->getPrivateMethod();
$privateMethod(); // Foo1::privateMethod
?>`

> Note:

> Object creation by this syntax (e.g `new Foo(...)`) is not supported, because `new Foo()` syntax is not considered a call.

> Note:

> The first-class callable syntax cannot be combined with the nullsafe operator. Both of the following result in a compile-time error:

> `<?php
> $obj?->method(...);
> $obj?->prop->method(...);
> ?>`

# Classes and Objects

## Table of Contents

- Introduction
- The Basics
- Properties
- Property Hooks
- Class Constants
- Autoloading Classes
- Constructors and Destructors
- Visibility
- Object Inheritance
- Scope Resolution Operator (::)
- Static Keyword
- Class Abstraction
- Object Interfaces
- Traits
- Anonymous classes
- Overloading
- Object Iteration
- Magic Methods
- Final Keyword
- Object Cloning
- Comparing Objects
- Late Static Bindings
- Objects and references
- Object Serialization
- Covariance and Contravariance
- Lazy Objects
- OOP Changelog

## Introduction

PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and methods, additional magic methods, interfaces, and cloning.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Tip

See also the Userland Naming Guide.

## The Basics

### class

Basic class definitions begin with the keyword `class`, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

The class name can be any valid label, provided it is not a PHP reserved word. As of PHP 8.4.0, using a single underscore `_` as a class name is deprecated. 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_\x80-\xff][a-zA-Z0-9_\x80-\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 the value of the calling object.

Warning

Calling a non-static method statically throws an Error. Prior to PHP 8.0.0, this would generate a deprecation notice, and $this would be undefined.

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()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>`

Output of the above example in PHP 7:

    $this is defined (A)

    Deprecated: Non-static method A::foo() should not be called statically in %s  on line 27
    $this is not defined.

    Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
    $this is not defined.

    Deprecated: Non-static method B::bar() should not be called statically in %s  on line 32

    Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
    $this is not defined.

Output of the above example in PHP 8:

    $this is defined (A)

    Fatal error: Uncaught Error: Non-static method A::foo() cannot be called statically in %s :27
    Stack trace:
    #0 {main}
      thrown in %s  on line 27

#### Readonly classes

As of PHP 8.2.0, a class can be marked with the readonly modifier. Marking a class as readonly will add the readonly modifier to every declared property, and prevent the creation of dynamic properties. Moreover, it is impossible to add support for them by using the AllowDynamicProperties attribute. Attempting to do so will trigger a compile-time error.

`<?php
#[\AllowDynamicProperties]
readonly class Foo {
}
// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo
?>`

As neither untyped nor static properties can be marked with the `readonly` modifier, readonly classes cannot declare them either:

`<?php
readonly class Foo
{
public $bar;
}
// Fatal error: Readonly property Foo::$bar must have type
?>`
`<?php
readonly class Foo
{
public static int $bar;
}
// Fatal error: Readonly class Foo cannot declare static properties
?>`

A readonly class can be extended if, and only if, the child class is also a readonly class.

### new

To create an instance of a class, the `new` keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

If a variable containing a string with 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.

> Note:

> If there are no arguments to be passed to the class's constructor, parentheses after the class name may be omitted.

Example #3 Creating an instance

`<?php
class SimpleClass {
}
$instance = new SimpleClass();
var_dump($instance);
// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
var_dump($instance);
?>`

As of PHP 8.0.0, using `new` with arbitrary expressions is supported. This allows more complex instantiation if the expression produces a string. The expressions must be wrapped in parentheses.

Example #4 Creating an instance using an arbitrary expression

In the given example we show multiple examples of valid arbitrary expressions that produce a class name. This shows a call to a function, string concatenation, and the `::class` constant.

`<?php
class ClassA extends \stdClass {}
class ClassB extends \stdClass {}
class ClassC extends ClassB {}
class ClassD extends ClassA {}
function getSomeClass(): string
{
return 'ClassA';
}
var_dump(new (getSomeClass()));
var_dump(new ('Class' . 'B'));
var_dump(new ('Class' . 'C'));
var_dump(new (ClassD::class));
?>`

Output of the above example in PHP 8:

    object(ClassA)#1 (0) {
    }
    object(ClassB)#1 (0) {
    }
    object(ClassC)#1 (0) {
    }
    object(ClassD)#1 (0) {
    }

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 #5 Object Assignment

`<?php
class SimpleClass {
public string $var;
}
$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"
    }

It's possible to create instances of an object in a couple of ways:

Example #6 Creating new objects

`<?php
class Test
{
public static function getNew()
{
return new static();
}
}
class Child extends Test {}
$obj1 = new Test(); // By the class name
$obj2 = new $obj1(); // Through the variable containing an object
var_dump($obj1 !== $obj2);
$obj3 = Test::getNew(); // By the class method
var_dump($obj3 instanceof Test);
$obj4 = Child::getNew(); // Through a child class method
var_dump($obj4 instanceof Child);
?>`

The above example will output:

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

It is possible to access a member of a newly created object in a single expression:

Example #7 Access member of newly created object

`<?php
echo (new DateTime())->format('Y'), PHP_EOL;
// surrounding parentheses are optional as of PHP 8.4.0
echo new DateTime()->format('Y'), PHP_EOL;
?>`

The above example will output something similar to:

    2025
    2025

> Note: Prior to PHP 7.1, the arguments are not evaluated if there is no constructor function defined.

### Properties and methods

Class properties and methods live in separate "namespaces", so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call.

Example #8 Property access vs. method call

`<?php
class Foo
{
public $bar = 'property';
public function bar() {
return 'method';
}
}
$obj = new Foo();
echo $obj->bar, PHP_EOL, $obj->bar(), PHP_EOL;`

The above example will output:

    property
    method

That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses.

Example #9 Calling an anonymous function stored in a property

`<?php
class Foo
{
public $bar;
public function __construct() {
$this->bar = function() {
return 42;
};
}
}
$obj = new Foo();
echo ($obj->bar)(), PHP_EOL;`

The above example will output:

    42

### extends

A class can inherit the constants, 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 constants, 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 or constant as final, they may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

> Note: As of PHP 8.1.0, constants may be declared as final.

Example #10 Simple Class Inheritance

`<?php
class SimpleClass
{
function displayVar()
{
echo "Parent class\n";
}
}
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
    Parent Class

#### Signature compatibility rules

When overriding a method, its signature must be compatible with the parent method. Otherwise, a fatal error is emitted, or, prior to PHP 8.0.0, an `E_WARNING` level error is generated. A signature is compatible if it respects the variance rules, makes a mandatory parameter optional, adds only optional new parameters and doesn't restrict but only relaxes the visibility. This is known as the Liskov Substitution Principle, or LSP for short. The constructor, and `private` methods are exempt from these signature compatibility rules, and thus won't emit a fatal error in case of a signature mismatch.

Example #11 Compatible child methods

`<?php
class Base
{
public function foo(int $a) {
echo "Valid\n";
}
}
class Extend1 extends Base
{
function foo(int $a = 5)
{
parent::foo($a);
}
}
class Extend2 extends Base
{
function foo(int $a, $b = 5)
{
parent::foo($a);
}
}
$extended1 = new Extend1();
$extended1->foo();
$extended2 = new Extend2();
$extended2->foo(1);`

The above example will output:

    Valid
    Valid

The following examples demonstrate that a child method which removes a parameter, or makes an optional parameter mandatory, is not compatible with the parent method.

Example #12 Fatal error when a child method removes a parameter

`<?php
class Base
{
public function foo(int $a = 5) {
echo "Valid\n";
}
}
class Extend extends Base
{
function foo()
{
parent::foo(1);
}
}`

Output of the above example in PHP 8 is similar to:

    Fatal error: Declaration of Extend::foo() must be compatible with Base::foo(int $a = 5) in /in/evtlq on line 13

Example #13 Fatal error when a child method makes an optional parameter mandatory

`<?php
class Base
{
public function foo(int $a = 5) {
echo "Valid\n";
}
}
class Extend extends Base
{
function foo(int $a)
{
parent::foo($a);
}
}`

Output of the above example in PHP 8 is similar to:

    Fatal error: Declaration of Extend::foo(int $a) must be compatible with Base::foo(int $a = 5) in /in/qJXVC on line 13

Warning

Renaming a method's parameter in a child class is not a signature incompatibility. However, this is discouraged as it will result in a runtime Error if named arguments are used.

Example #14 Error when using named arguments and parameters were renamed in a child class

`<?php
class A {
public function test($foo, $bar) {}
}
class B extends A {
public function test($a, $b) {}
}
$obj = new B;
// Pass parameters according to A::test() contract
$obj->test(foo: "foo", bar: "bar"); // ERROR!`

The above example will output something similar to:

    Fatal error: Uncaught Error: Unknown named parameter $foo in /in/XaaeN:14
    Stack trace:
    #0 {main}
      thrown in /in/XaaeN on line 14

### ::class

The `class` keyword is also used for class name resolution. To obtain the fully qualified name of a class `ClassName` use `ClassName::class`. This is particularly useful with namespaced classes.

Example #15 Class name resolution

`<?php
namespace NS {
class ClassName {
}
echo ClassName::class;
}
?>`

The above example will output:

    NS\ClassName

> Note:

> The class name resolution using `::class` is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

> Example #16 Missing class name resolution

> `<?php
> print Does\Not\Exist::class;
> ?>`

> The above example will output:

>     Does\Not\Exist

As of PHP 8.0.0, `::class` may also be used on objects. This resolution happens at runtime, not compile time. Its effect is the same as calling get_class() on the object.

Example #17 Object name resolution

`<?php
namespace NS {
class ClassName {
}
$c = new ClassName();
print $c::class;
}
?>`

The above example will output:

    NS\ClassName

### Nullsafe methods and properties

As of PHP 8.0.0, properties and methods may also be accessed with the "nullsafe" operator instead: `?->`. The nullsafe operator works the same as property or method access as above, except that if the object being dereferenced is `null` then `null` will be returned rather than an exception thrown. If the dereference is part of a chain, the rest of the chain is skipped.

The effect is similar to wrapping each access in an is_null() check first, but more compact.

Example #18 Nullsafe Operator

`<?php
// As of PHP 8.0.0, this line:
$result = $repository?->getUser(5)?->name;
// Is equivalent to the following code block:
if (is_null($repository)) {
$result = null;
} else {
$user = $repository->getUser(5);
if (is_null($user)) {
$result = null;
} else {
$result = $user->name;
}
}
?>`

> Note:

> The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return. For indicating an error, a thrown exception is preferable.

## Properties

Class member variables are called properties. They may be referred to using other terms such as fields, but for the purposes of this reference properties will be used. They are defined by using at least one modifier (such as Visibility, Static Keyword, or, as of PHP 8.1.0, readonly), optionally (except for `readonly` properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value.

> Note:

> An obsolete way of declaring class properties, is by using the `var` keyword instead of a modifier.

> Note: A property declared without a Visibility modifier will be 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 the value of the calling object.

Example #1 Property declarations

`<?php
class SimpleClass
{
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = [true, false];
public $var8 = <<<'EOD'
hello world
EOD;
// Without visibility modifier:
static $var9;
readonly int $var10;
}
?>`

> Note:

> There are various functions to handle classes and objects. See the Class/Object Functions reference.

### Type declarations

As of PHP 7.4.0, property definitions can include Type declarations, with the exception of callable.

Example #2 Example of typed properties

`<?php
class User
{
public int $id;
public ?string $name;
public function __construct(int $id, ?string $name)
{
$this->id = $id;
$this->name = $name;
}
}
$user = new User(1234, null);
var_dump($user->id);
var_dump($user->name);
?>`

The above example will output:

    int(1234)
    NULL

Typed properties must be initialized before accessing, otherwise an Error is thrown.

Example #3 Accessing properties

`<?php
class Shape
{
public int $numberOfSides;
public string $name;
public function setNumberOfSides(int $numberOfSides): void
{
$this->numberOfSides = $numberOfSides;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getNumberOfSides(): int
{
return $this->numberOfSides;
}
public function getName(): string
{
return $this->name;
}
}
$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());
$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>`

The above example will output:

    string(8) "triangle"
    int(3)
    string(6) "circle"

    Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

### Readonly properties

As of PHP 8.1.0, a property can be declared with the `readonly` modifier, which prevents modification of the property after initialization. Prior to PHP 8.4.0 a `readonly` property is implicitly private-set, and may only be written to from the same class. As of PHP 8.4.0, `readonly` properties are implicitly `protected(set)`, so may be set from child classes. That may be overridden explicitly if desired.

Example #4 Example of readonly properties

`<?php
class Test {
public readonly string $prop;
public function __construct(string $prop) {
// Legal initialization.
$this->prop = $prop;
}
}
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>`

> Note:

> The readonly modifier can only be applied to typed properties. A readonly property without type constraints can be created using the Mixed type.

> Note:

> Readonly static properties are not supported.

A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an Error exception.

Example #5 Illegal initialization of readonly properties

`<?php
class Test1 {
public readonly string $prop;
}
$test1 = new Test1;
// Illegal initialization outside of private scope.
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>`

> Note:

> Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.

> `<?php
> class Test {
> // Fatal error: Readonly property Test::$prop cannot have default value
> public readonly int $prop = 42;
> }
> ?>`

> Note:

> Readonly properties cannot be unset() once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared.

Modifications are not necessarily plain assignments, all of the following will also result in an Error exception:

`<?php
class Test {
public function __construct(
public readonly int $i = 0,
public readonly array $ary = [],
) {}
}
$test = new Test;
$test->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
unset($test->ary[0]);
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);
?>`

However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:

`<?php
class Test {
public function __construct(public readonly object $obj) {}
}
$test = new Test(new stdClass);
// Legal interior mutation.
$test->obj->foo = 1;
// Illegal reassignment.
$test->obj = new stdClass;
?>`

As of PHP 8.3.0, readonly properties can be reinitialized when cloning an object using the __clone() method.

Example #6 Readonly properties and cloning

`<?php
class Test1 {
public readonly ?string $prop;
public function __clone() {
$this->prop = null;
}
public function setProp(string $prop): void {
$this->prop = $prop;
}
}
$test1 = new Test1;
$test1->setProp('foobar');
$test2 = clone $test1;
var_dump($test2->prop); // NULL
?>`

### Dynamic properties

If trying to assign to a non-existent property on an object, PHP will automatically create a corresponding property. This dynamically created property will only be available on this class instance.

Warning

Dynamic properties are deprecated as of PHP 8.2.0. It is recommended to declare the property instead. To handle arbitrary property names, the class should implement the magic methods __get() and __set(). At last resort the class can be marked with the `#[\AllowDynamicProperties]` attribute.

## Property Hooks

Property hooks, also known as "property accessors" in some other languages, are a way to intercept and override the read and write behavior of a property. This functionality serves two purposes:

1. It allows for properties to be used directly, without get- and set- methods, while leaving the option open to add additional behavior in the future. That renders most boilerplate get/set methods unnecessary, even without using hooks.
2. It allows for properties that describe an object without needing to store a value directly.

There are two hooks available on non-static properties: `get` and `set`. They allow overriding the read and write behavior of a property, respectively. Hooks are available for both typed and untyped properties.

A property may be "backed" or "virtual". A backed property is one that actually stores a value. Any property that has no hooks is backed. A virtual property is one that has hooks and those hooks do not interact with the property itself. In this case, the hooks are effectively the same as methods, and the object does not use any space to store a value for that property.

Property hooks are incompatible with `readonly` properties. If there is a need to restrict access to a `get` or `set` operation in addition to altering its behavior, use asymmetric property visibility.

> Note: Version Information
> Property hooks were introduced in PHP 8.4.

### Basic Hook Syntax

The general syntax for declaring a hook is as follows.

Example #1 Property hooks (full version)

`<?php
class Example
{
private bool $modified = false;
public string $foo = 'default value' {
get {
if ($this->modified) {
return $this->foo . ' (modified)';
}
return $this->foo;
}
set(string $value) {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
$example = new Example();
$example->foo = 'changed';
print $example->foo;
?>`

The $foo property ends in `{}`, rather than a semicolon. That indicates the presence of hooks. Both a `get` and `set` hook are defined, although it is allowed to define only one or the other. Both hooks have a body, denoted by `{}`, that may contain arbitrary code.

The `set` hook additionally allows specifying the type and name of an incoming value, using the same syntax as a method. The type must be either the same as the type of the property, or contravariant (wider) to it. For instance, a property of type string could have a `set` hook that accepts string|Stringable, but not one that only accepts array.

At least one of the hooks references `$this->foo`, the property itself. That means the property will be "backed". When calling `$example->foo = 'changed'`, the provided string will be first cast to lowercase, then saved to the backing value. When reading from the property, the previously saved value may conditionally be appended with additional text.

There are a number of shorthand syntax variants as well to handle common cases.

If the `get` hook is a single expression, then the `{}` may be omitted and replaced with an arrow expression.

Example #2 Property get expression

This example is equivalent to the previous.

`<?php
class Example
{
private bool $modified = false;
public string $foo = 'default value' {
get => $this->foo . ($this->modified ? ' (modified)' : '');
set(string $value) {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
?>`

If the `set` hook's parameter type is the same as the property type (which is typical), it may be omitted. In that case, the value to set is automatically given the name $value.

Example #3 Property set defaults

This example is equivalent to the previous.

`<?php
class Example
{
private bool $modified = false;
public string $foo = 'default value' {
get => $this->foo . ($this->modified ? ' (modified)' : '');
set {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
?>`

If the `set` hook is only setting a modified version of the passed in value, then it may also be simplified to an arrow expression. The value the expression evaluates to will be set on the backing value.

Example #4 Property set expression

`<?php
class Example
{
private bool $modified = false;
public string $foo = 'default value' {
get => $this->foo . ($this->modified ? ' (modified)' : '');
set => strtolower($value);
}
}
?>`

This example is not quite equivalent to the previous, as it does not also modify `$this->modified`. If multiple statements are needed in the set hook body, use the braces version.

A property may implement zero, one, or both hooks as the situation requires. All shorthand versions are mutually-independent. That is, using a short-get with a long-set, or a short-set with an explicit type, or so on is all valid.

On a backed property, omitting a `get` or `set` hook means the default read or write behavior will be used.

> Note: Hooks can be defined when using constructor property promotion. However, when doing so, values provided to the constructor must match the type associated with the property, regardless of what the `set` hook might allow. Consider the following:

> `<?php
> class Example
> {
> public function __construct(
> public private(set) DateTimeInterface $created {
> set (string|DateTimeInterface $value) {
> if (is_string($value)) {
> $value = new DateTimeImmutable($value);
> }
> $this->created = $value;
> }
> },
> ) {
> }
> }`
> Internally, the engine decomposes this to the following:
> `<?php
> class Example
> {
> public private(set) DateTimeInterface $created {
> set (string|DateTimeInterface $value) {
> if (is_string($value)) {
> $value = new DateTimeImmutable($value);
> }
> $this->created = $value;
> }
> }
> public function __construct(
> DateTimeInterface $created,
> ) {
> $this->created = $created;
> }
> }`
> Any attempts to set the property outside the constructor will allow either string or DateTimeInterface values, but the constructor will only allow DateTimeInterface. This is because the defined type for the property (DateTimeInterface) is used as the parameter type within the constructor signature, regardless of what the `set` hook allows. If this kind of behavior is needed from the constructor, constructor property promotion cannot be used.

### Virtual properties

Virtual properties are properties that have no backing value. A property is virtual if neither its `get` nor `set` hook references the property itself using exact syntax. That is, a property named `$foo` whose hook contains `$this->foo` will be backed. But the following is not a backed property, and will error:

Example #5 Invalid virtual property

`<?php
class Example
{
public string $foo {
get {
$temp = __PROPERTY__;
return $this->$temp; // Doesn't refer to $this->foo, so it doesn't count.
}
}
}
?>`

For virtual properties, if a hook is omitted then that operation does not exist and trying to use it will produce an error. Virtual properties take up no memory space in an object. Virtual properties are suited for "derived" properties, such as those that are the combination of two other properties.

Example #6 Virtual property

`<?php
class Rectangle
{
// A virtual property.
public int $area {
get => $this->h * $this->w;
}
public function __construct(public int $h, public int $w) {}
}
$s = new Rectangle(4, 5);
print $s->area; // prints 20
$s->area = 30; // Error, as there is no set operation defined.
?>`

Defining both a `get` and `set` hook on a virtual property is also allowed.

### Scoping

All hooks operate in the scope of the object being modified. That means they have access to all public, private, or protected methods of the object, as well as any public, private, or protected properties, including properties that may have their own property hooks. Accessing another property from within a hook does not bypass the hooks defined on that property.

The most notable implication of this is that non-trivial hooks may sub-call to an arbitrarily complex method if they wish.

Example #7 Calling a method from a hook

`<?php
class Person {
public string $phone {
set => $this->sanitizePhone($value);
}
private function sanitizePhone(string $value): string {
$value = ltrim($value, '+');
$value = ltrim($value, '1');
if (!preg_match('/\d\d\d\-\d\d\d\-\d\d\d\d/', $value)) {
throw new \InvalidArgumentException();
}
return $value;
}
}
?>`

### References

Because the presence of hooks intercept the read and write process for properties, they cause issues when acquiring a reference to a property or with indirect modification, such as `$this->arrayProp['key'] = 'value';`. That is because any attempted modification of the value by reference would bypass a set hook, if one is defined.

In the rare case that getting a reference to a property that has hooks defined is necessary, the `get` hook may be prefixed with `&` to cause it to return by reference. Defining both `get` and `&get` on the same property is a syntax error.

Defining both `&get` and `set` hooks on a backed property is not allowed. As noted above, writing to the value returned by reference would bypass the `set` hook. On virtual properties, there is no necessary common value shared between the two hooks, so defining both is allowed.

Writing to an index of an array property also involves an implicit reference. For that reason, writing to a backed array property with hooks defined is allowed if and only if it defines only a `&get` hook. On a virtual property, writing to the array returned from either `get` or `&get` is legal, but whether that has any impact on the object depends on the hook implementation.

Overwriting the entire array property is fine, and behaves the same as any other property. Only working with elements of the array require special care.

### Inheritance

#### Final hooks

Hooks may also be declared final, in which case they may not be overridden.

Example #8 Final hooks

`<?php
class User
{
public string $username {
final set => strtolower($value);
}
}
class Manager extends User
{
public string $username {
// This is allowed
get => strtoupper($this->username);
// But this is NOT allowed, because set is final in the parent.
set => strtoupper($value);
}
}
?>`

A property may also be declared final. A final property may not be redeclared by a child class in any way, which precludes altering hooks or widening its access.

Declaring hooks final on a property that is declared final is redundant, and will be silently ignored. This is the same behavior as final methods.

A child class may define or redefine individual hooks on a property by redefining the property and just the hooks it wishes to override. A child class may also add hooks to a property that had none. This is essentially the same as if the hooks were methods.

Example #9 Hook inheritance

`<?php
class Point
{
public int $x;
public int $y;
}
class PositivePoint extends Point
{
public int $x {
set {
if ($value < 0) {
throw new \InvalidArgumentException('Too small');
}
$this->x = $value;
}
}
}
?>`

Each hook overrides parent implementations independently of each other. If a child class adds hooks, any default value set on the property is removed, and must be redeclared. That is the same consistent with how inheritance works on hook-less properties.

#### Accessing parent hooks

A hook in a child class may access the parent class's property using the `parent::$prop` keyword, followed by the desired hook. For example, `parent::$propName::get()`. It may be read as "access the prop defined on the parent class, and then run its get operation" (or set operation, as appropriate).

If not accessed this way, the parent class's hook is ignored. This behavior is consistent with how all methods work. This also offers a way to access the parent class's storage, if any. If there is no hook on the parent property, its default get/set behavior will be used. Hooks may not access any other hook except their own parent on their own property.

The example above could be rewritten as follows, which would allow for the `Point` class to add its own `set` hook in the future without issues (in the previous example, a hook added to the parent class would be ignored in the child).

Example #10 Parent hook access (set)

`<?php
class Point
{
public int $x;
public int $y;
}
class PositivePoint extends Point
{
public int $x {
set {
if ($value < 0) {
throw new \InvalidArgumentException('Too small');
}
parent::$x::set($value);
}
}
}
?>`

An example of overriding only a get hook could be:

Example #11 Parent hook access (get)

`<?php
class Strings
{
public string $val;
}
class CaseFoldingStrings extends Strings
{
public bool $uppercase = true;
public string $val {
get => $this->uppercase
? strtoupper(parent::$val::get())
: strtolower(parent::$val::get());
}
}
?>`

### Serialization

PHP has a number of different ways in which an object may be serialized, either for public consumption or for debugging purposes. The behavior of hooks varies depending on the use case. In some cases, the raw backing value of a property will be used, bypassing any hooks. In others, the property will be read or written "through" the hook, just like any other normal read/write action.

- var_dump(): Use raw value
- serialize(): Use raw value
- unserialize(): Use raw value
- __serialize()/__unserialize(): Custom logic, uses get/set hook
- Array casting: Use raw value
- var_export(): Use get hook
- json_encode(): Use get hook
- JsonSerializable: Custom logic, uses get hook
- get_object_vars(): Use get hook
- get_mangled_object_vars(): Use raw value

## Class Constants

It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is `public`.

> Note:

> Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.

It's also possible for interfaces to have constants. Look at the interface documentation for examples.

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

Note that class constants are allocated once per class, and not for each class instance.

As of PHP 8.3.0, class constants can have a scalar type such as `bool`, `int`, `float`, `string`, or even `array`. When using `array`, the contents can only be other scalar types.

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";
$class = new MyClass();
$class->showConstant();
echo $class::CONSTANT."\n";
?>`

The special `::class` constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:

Example #2 Namespaced ::class example

`<?php
namespace foo {
class bar {
}
echo bar::class; // foo\bar
}
?>`

Example #3 Class constant expression example

`<?php
const ONE = 1;
class foo {
const TWO = ONE * 2;
const THREE = ONE + self::TWO;
const SENTENCE = 'The value of THREE is '.self::THREE;
}
?>`

Example #4 Class constant visibility modifiers, as of PHP 7.1.0

`<?php
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>`

Output of the above example in PHP 7.1:

    bar

    Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

> Note:

> As of PHP 7.1.0 visibility modifiers are allowed for class constants.

Example #5 Class constant visibility variance check, as of PHP 8.3.0

`<?php
interface MyInterface
{
public const VALUE = 42;
}
class MyClass implements MyInterface
{
protected const VALUE = 42;
}
?>`

Output of the above example in PHP 8.3:

    Fatal error: Access level to MyClass::VALUE must be public (as in interface MyInterface) …

> Note: As of PHP 8.3.0 visibility variance is checked more strictly. Prior to this version, the visibility of a class constant could be different from the visibility of the constant in the implemented interface.

Example #6 Fetch class constant syntax, as of PHP 8.3.0

`<?php
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
$name = 'BAR';
echo Foo::{$name}, PHP_EOL; // bar
?>`

> Note:

> As of PHP 8.3.0, class constants can be fetched dynamically using a variable.

Example #7 Assigning types to class constants, as of PHP 8.3.0

`<?php
class MyClass {
public const bool MY_BOOL = true;
public const int MY_INT = 1;
public const float MY_FLOAT = 1.01;
public const string MY_STRING = 'one';
public const array MY_ARRAY = [self::MY_BOOL, self::MY_INT, self::MY_FLOAT, self::MY_STRING];
}
var_dump(MyClass::MY_BOOL);
var_dump(MyClass::MY_INT);
var_dump(MyClass::MY_FLOAT);
var_dump(MyClass::MY_STRING);
var_dump(MyClass::MY_ARRAY);
?>`

Output of the above example in PHP 8.3:

    bool(true)
    int(1)
    float(1.01)
    string(3) "one"
    array(4) {
      [0]=>
      bool(true)
      [1]=>
      int(1)
      [2]=>
      float(1.01)
      [3]=>
      string(3) "one"
    }

## Autoloading Classes

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

The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

Any class-like construct may be autoloaded the same way. That includes classes, interfaces, traits, and enumerations.

Caution

Prior to PHP 8.0.0, it was possible to use __autoload() to autoload classes and interfaces. However, it is a less flexible alternative to spl_autoload_register() and __autoload() is deprecated as of PHP 7.2.0, and removed as of PHP 8.0.0.

> Note:

> spl_autoload_register() may be called multiple times in order to register multiple autoloaders. Throwing an exception from an autoload function, however, will interrupt that process and not allow further autoload functions to run. For that reason, throwing exceptions from an autoload function is strongly discouraged.

Example #1 Autoload example

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

`<?php
spl_autoload_register(function ($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
spl_autoload_register(function ($name) {
var_dump($name);
});
class Foo implements ITest {
}
/*
string(5) "ITest"
Fatal error: Interface 'ITest' not found in ...
*/
?>`

Example #3 Using Composer's autoloader

» Composer generates a `vendor/autoload.php` which is set up to automatically load packages that are being managed by Composer. By including this file, those packages can be used without any additional work.

`<?php
require __DIR__ . '/vendor/autoload.php';
$uuid = Ramsey\Uuid\Uuid::uuid7();
echo "Generated new UUID -> ", $uuid->toString(), "\n";
?>`

### See Also

- unserialize()
- unserialize_callback_func
- unserialize_max_depth
- spl_autoload_register()
- spl_autoload()
- __autoload()

## Constructors and Destructors

### Constructor

__construct(mixed `...$values` = ""): void

PHP 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 Constructors in inheritance

`<?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();
?>`

Unlike other methods, __construct() is exempt from the usual signature compatibility rules when being extended.

Constructors are ordinary methods which are called during the instantiation of their corresponding object. As such, they may define an arbitrary number of arguments, which may be required, may have a type, and may have a default value. Constructor arguments are called by placing the arguments in parentheses after the class name.

Example #2 Using constructor arguments

`<?php
class Point {
protected int $x;
protected int $y;
public function __construct(int $x, int $y = 0) {
$this->x = $x;
$this->y = $y;
}
}
// Pass both parameters.
$p1 = new Point(4, 5);
// Pass only the required parameter. $y will take its default value of 0.
$p2 = new Point(4);
// With named parameters (as of PHP 8.0):
$p3 = new Point(y: 5, x: 4);
?>`

If a class has no constructor, or the constructor has no required arguments, the parentheses may be omitted.

#### Old-style constructors

Prior to PHP 8.0.0, classes in the global namespace will interpret a method named the same as the class as an old-style constructor. That syntax is deprecated, and will result in an `E_DEPRECATED` error but still call that function as a constructor. If both __construct() and a same-name method are defined, __construct() will be called.

In namespaced classes, or any class as of PHP 8.0.0, a method named the same as the class never has any special meaning.

Always use __construct() in new code.

#### Constructor Promotion

As of PHP 8.0.0, constructor parameters may also be promoted to correspond to an object property. It is very common for constructor parameters to be assigned to a property in the constructor but otherwise not operated upon. Constructor promotion provides a short-hand for that use case. The example above could be rewritten as the following.

Example #3 Using constructor property promotion

`<?php
class Point {
public function __construct(protected int $x, protected int $y = 0) {
}
}`

When a constructor argument includes a modifier, PHP will interpret it as both an object property and a constructor argument, and assign the argument value to the property. The constructor body may then be empty or may contain other statements. Any additional statements will be executed after the argument values have been assigned to the corresponding properties.

Not all arguments need to be promoted. It is possible to mix and match promoted and not-promoted arguments, in any order. Promoted arguments have no impact on code calling the constructor.

> Note:

> Using a visibility modifier (`public`, `protected` or `private`) is the most likely way to apply property promotion, but any other single modifier (such as `readonly`) will have the same effect.

> Note:

> Object properties may not be typed callable due to engine ambiguity that would introduce. Promoted arguments, therefore, may not be typed callable either. Any other type declaration is permitted, however.

> Note:

> As promoted properties are desugared to both a property as well as a function parameter, any and all naming restrictions for both properties as well as parameters apply.

> Note:

> Attributes placed on a promoted constructor argument will be replicated to both the property and argument. Default values on a promoted constructor argument will be replicated only to the argument and not the property.

#### New in initializers

As of PHP 8.1.0, objects can be used as default parameter values, static variables, and global constants, as well as in attribute arguments. Objects can also be passed to define() now.

> Note:

> The use of a dynamic or non-string class name or an anonymous class is not allowed. The use of argument unpacking is not allowed. The use of unsupported expressions as arguments is not allowed.

Example #4 Using new in initializers

`<?php
// All allowed:
static $x = new Foo;
const C = new Foo;
function test($param = new Foo) {}
#[AnAttribute(new Foo)]
class Test {
public function __construct(
public $prop = new Foo,
) {}
}
// All not allowed (compile-time error):
function test(
$a = new (CLASS_NAME_CONSTANT)(), // dynamic class name
$b = new class {}, // anonymous class
$c = new A(...[]), // argument unpacking
$d = new B($abc), // unsupported constant expression
) {}
?>`

#### Static creation methods

PHP only supports a single constructor per class. In some cases, however, it may be desirable to allow an object to be constructed in different ways with different inputs. The recommended way to do so is by using static methods as constructor wrappers.

Example #5 Using static creation methods

`<?php
$some_json_string = '{ "id": 1004, "name": "Elephpant" }';
$some_xml_string = "<animal><id>1005</id><name>Elephpant</name></animal>";
class Product {
private ?int $id;
private ?string $name;
private function __construct(?int $id = null, ?string $name = null) {
$this->id = $id;
$this->name = $name;
}
public static function fromBasicData(int $id, string $name): static {
$new = new static($id, $name);
return $new;
}
public static function fromJson(string $json): static {
$data = json_decode($json, true);
return new static($data['id'], $data['name']);
}
public static function fromXml(string $xml): static {
$data = simplexml_load_string($xml);
$new = new static();
$new->id = (int) $data->id;
$new->name = $data->name;
return $new;
}
}
$p1 = Product::fromBasicData(5, 'Widget');
$p2 = Product::fromJson($some_json_string);
$p3 = Product::fromXml($some_xml_string);
var_dump($p1, $p2, $p3);`

The constructor may be made private or protected to prevent it from being called externally. If so, only a static method will be able to instantiate the class. Because they are in the same class definition they have access to private methods, even if not of the same object instance. The private constructor is optional and may or may not make sense depending on the use case.

The three public static methods then demonstrate different ways of instantiating the object.

- `fromBasicData()` takes the exact parameters that are needed, then creates the object by calling the constructor and returning the result.
- `fromJson()` accepts a JSON string and does some pre-processing on it itself to convert it into the format desired by the constructor. It then returns the new object.
- `fromXml()` accepts an XML string, preprocesses it, and then creates a bare object. The constructor is still called, but as all of the parameters are optional the method skips them. It then assigns values to the object properties directly before returning the result.

In all three cases, the `static` keyword is translated into the name of the class the code is in. In this case, `Product`.

### Destructor

__destruct(): void

PHP possesses 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 #6 Destructor Example

`<?php
class MyDestructableClass
{
function __construct() {
print "In constructor\n";
}
function __destruct() {
print "Destroying " . __CLASS__ . "\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.

If a destructor creates new references to its object, it will not be called a second time when the reference count reaches zero again or during the shutdown sequence.

As of PHP 8.4.0, when cycle collection occurs during the execution of a Fiber, the destructors of objects scheduled for collection are executed in a separate Fiber, called the `gc_destructor_fiber`. If this Fiber is suspended, a new one will be created to execute any remaining destructors. The previous `gc_destructor_fiber` will no longer be referenced by the garbage collector and may be collected if it is not referenced elsewhere. Objects whose destructor are suspended will not be collected until the destructor returns or the Fiber itself is collected.

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

## Visibility

The visibility of a property, a method or (as of PHP 7.1.0) a constant 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 inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member.

### Property Visibility

Class properties may be defined as public, private, or protected. Properties declared without any explicit visibility keyword are 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 properties, but not private
public $public = 'Public2';
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 Public2, Protected2, Undefined
?>`

#### Asymmetric Property Visibility

As of PHP 8.4, object properties may also have their visibility set asymmetrically, with a different scope for reading (`get`) and writing (`set`). Specifically, the `set` visibility may be specified separately, provided it is not more permissive than the default visibility.

Example #2 Asymmetric Property visibility

`<?php
class Book
{
public function __construct(
public private(set) string $title,
public protected(set) string $author,
protected private(set) int $pubYear,
) {}
}
class SpecialBook extends Book
{
public function update(string $author, int $year): void
{
$this->author = $author; // OK
$this->pubYear = $year; // Fatal Error
}
}
$b = new Book('How to PHP', 'Peter H. Peterson', 2024);
echo $b->title; // Works
echo $b->author; // Works
echo $b->pubYear; // Fatal Error
$b->title = 'How not to PHP'; // Fatal Error
$b->author = 'Pedro H. Peterson'; // Fatal Error
$b->pubYear = 2023; // Fatal Error
?>`

As of PHP 8.5, `set` visibility may also be applied to static properties of classes.

Example #3 Asymmetric Static Property Visibility

`<?php
class Manager
{
public private(set) static int $calls = 0;
public function doAThing(): string
{
self::$calls++;
// Do other stuff.
return "some string";
}
}
$m = new Manager();
$m->doAThing(); // Works
echo Manager::$calls; // Works
Manager::$calls = 5; // Fatal error
?>`

The above example will output:

    1
    Fatal error: Uncaught Error: Cannot modify private(set) property Manager::$calls from global scope in /some/file.php

There are a few caveats regarding asymmetric visibility:

- Only typed properties may have a separate `set` visibility.
- The `set` visibility must be the same as `get` or more restrictive. That is, `public protected(set)` and `protected protected(set)` are allowed, but `protected public(set)` will cause a syntax error.
- If a property is `public`, then the main visibility may be omitted. That is, `public private(set)` and `private(set)` will have the same result.
- A property with `private(set)` visibility is automatically `final`, and may not be redeclared in a child class.
- Obtaining a reference to a property follows `set` visibility, not `get`. That is because a reference may be used to modify the property value.
- Similarly, trying to write to an array property involves both a `get` and `set` operation internally, and therefore will follow the `set` visibility, as that is always the more restrictive.

> Note: Spaces are not allowed in the set-visibility declaration. `private(set)` is correct. `private( set )` is not correct and will result in a parse error.

When a class extends another, the child class may redefine any property that is not `final`. When doing so, it may widen either the main visibility or the `set` visibility, provided that the new visibility is the same or wider than the parent class. However, be aware that if a `private` property is overridden, it does not actually change the parent's property but creates a new property with a different internal name.

Example #4 Asymmetric Property inheritance

`<?php
class Book
{
protected string $title;
public protected(set) string $author;
protected private(set) int $pubYear;
}
class SpecialBook extends Book
{
public protected(set) string $title; // OK, as reading is wider and writing the same.
public string $author; // OK, as reading is the same and writing is wider.
public protected(set) int $pubYear; // Fatal Error. private(set) properties are final.
}
?>`

### Method Visibility

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Example #5 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
?>`

### Constant Visibility

As of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants declared without any explicit visibility keyword are defined as public.

Example #6 Constant Declaration as of PHP 7.1.0

`<?php
/**
* Define MyClass
*/
class MyClass
{
// Declare a public constant
public const MY_PUBLIC = 'public';
// Declare a protected constant
protected const MY_PROTECTED = 'protected';
// Declare a private constant
private const MY_PRIVATE = 'private';
public function foo()
{
echo self::MY_PUBLIC;
echo self::MY_PROTECTED;
echo self::MY_PRIVATE;
}
}
$myclass = new MyClass();
MyClass::MY_PUBLIC; // Works
MyClass::MY_PROTECTED; // Fatal Error
MyClass::MY_PRIVATE; // Fatal Error
$myclass->foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function foo2()
{
echo self::MY_PUBLIC;
echo self::MY_PROTECTED;
echo self::MY_PRIVATE; // Fatal Error
}
}
$myclass2 = new MyClass2;
echo MyClass2::MY_PUBLIC; // Works
$myclass2->foo2(); // Public and Protected work, not Private
?>`

### Visibility from other objects

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

## Object Inheritance

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 extending a class, the subclass inherits all of the public and protected methods, properties and constants 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.

Private methods of a parent class are not accessible to a child class. As a result, child classes may reimplement a private method themselves without regard for normal inheritance rules. Prior to PHP 8.0.0, however, `final` and `static` restrictions were applied to private methods. As of PHP 8.0.0, the only private method restriction that is enforced is `private final` constructors, as that is a common way to "disable" the constructor when using static factory methods instead.

The visibility of methods, properties and constants can be relaxed, e.g. a `protected` method can be marked as `public`, but they cannot be restricted, e.g. marking a `public` property as `private`. An exception are constructors, whose visibility can be restricted, e.g. a `public` constructor can be marked as `private` in a child class.

> Note:

> Unless autoloading is used, the 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.

> Note:

> It is not allowed to override a read-write property with a readonly property or vice versa.

> `<?php
> class A {
> public int $prop;
> }
> class B extends A {
> // Illegal: read-write -> readonly
> public readonly int $prop;
> }
> ?>`

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'
?>`

### Return Type Compatibility with Internal Classes

Prior to PHP 8.1, most internal classes or methods didn't declare their return types, and any return type was allowed when extending them.

As of PHP 8.1.0, most internal methods started to "tentatively" declare their return type, in that case the return type of methods should be compatible with the parent being extended; otherwise, a deprecation notice is emitted. Note that lack of an explicit return declaration is also considered a signature mismatch, and thus results in the deprecation notice.

If the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a ReturnTypeWillChange attribute can be added to silence the deprecation notice.

Example #2 The overriding method does not declare any return type

`<?php
class MyDateTime extends DateTime
{
public function modify(string $modifier) { return false; }
}
// "Deprecated: Return type of MyDateTime::modify(string $modifier) should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0
?>`

Example #3 The overriding method declares a wrong return type

`<?php
class MyDateTime extends DateTime
{
public function modify(string $modifier): ?DateTime { return null; }
}
// "Deprecated: Return type of MyDateTime::modify(string $modifier): ?DateTime should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0
?>`

Example #4 The overriding method declares a wrong return type without a deprecation notice

`<?php
class MyDateTime extends DateTime
{
/**
* @return DateTime|false
*/
#[\ReturnTypeWillChange]
public function modify(string $modifier) { return false; }
}
// No notice is triggered
?>`

## Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to a constant, static property, or static method of a class or one of its parents. Moreover, static properties or methods can be overridden via late static binding.

When referencing these items from outside the class definition, use the name of the class.

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;
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 MyClass {
const CONST_VALUE = 'A constant value';
}
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';
$classname::doubleColon();
OtherClass::doubleColon();
?>`

When an extending class overrides the parent's 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.

## Static Keyword

Tip

This page describes the use of the `static` keyword to define static methods and properties. `static` can also be used to define static variables, define static anonymous functions 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. These can also be accessed statically within an instantiated class object.

### Static methods

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside methods declared as static.

Warning

Calling non-static methods statically throws an Error.

Prior to PHP 8.0.0, calling non-static methods statically was deprecated, and generated an `E_DEPRECATED` warning.

Example #1 Static method example

`<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod();
?>`

### Static properties

Static properties are accessed using the Scope Resolution Operator (`::`) and cannot be accessed through the object operator (`->`).

It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. `self`, `parent` and `static`).

Example #2 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";
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>`

Output of the above example in PHP 8 is similar to:

    foo
    foo

    Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23

    Warning: Undefined property: Foo::$my_static in /in/V0Rvv on line 23

    foo
    foo
    foo
    foo

## Class Abstraction

PHP has abstract classes, methods, and properties. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method or property must also be abstract. Methods defined as abstract simply declare the method's signature and whether it is public or protected; they cannot define the implementation. Properties defined as abstract may declare a requirement for `get` or `set` behavior, and may provide an implementation for one, but not both, operations.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child class, and follow the usual inheritance and signature compatibility rules.

As of PHP 8.4, an abstract class may declare an abstract property, either public or protected. A protected abstract property may be satisfied by a property that is readable/writeable from either protected or public scope.

An abstract property may be satisfied either by a standard property or by a property with defined hooks, corresponding to the required operation.

Example #1 Abstract method 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 method example

`<?php
abstract class AbstractClass
{
// An abstract method only needs to define the required arguments
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
// A child class may define optional parameters which are not present 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

Example #3 Abstract property example

`<?php
abstract class A
{
// Extending classes must have a publicly-gettable property
abstract public string $readable {
get;
}
// Extending classes must have a protected- or public-writeable property
abstract protected string $writeable {
set;
}
// Extending classes must have a protected or public symmetric property
abstract protected string $both {
get;
set;
}
}
class C extends A
{
// This satisfies the requirement and also makes it settable, which is valid
public string $readable;
// This would NOT satisfy the requirement, as it is not publicly readable
protected string $readable;
// This satisfies the requirement exactly, so is sufficient.
// It may only be written to, and only from protected scope
protected string $writeable {
set => $value;
}
// This expands the visibility from protected to public, which is fine
public string $both;
}
?>`

An abstract property on an abstract class may provide implementations for any hook, but must have either `get` or `set` declared but not defined (as in the example above).

Example #4 Abstract property with hooks example

`<?php
abstract class A
{
// This provides a default (but overridable) set implementation,
// and requires child classes to provide a get implementation
abstract public string $foo {
get;
set {
$this->foo = $value;
}
}
}
?>`

## Object Interfaces

Object interfaces allow you to create code which specifies which methods and properties a class must implement, without having to define how these methods or properties are implemented. Interfaces share a namespace with classes, traits, and enumerations, so they may not use the same name.

Interfaces are defined in the same way as a class, but with the `interface` keyword replacing the `class` keyword and 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.

In practice, interfaces serve two complementary purposes:

- To allow developers to create objects of different classes that may be used interchangeably because they implement the same interface or interfaces. A common example is multiple database access services, multiple payment gateways, or different caching strategies. Different implementations may be swapped out without requiring any changes to the code that uses them.
- To allow a function or method to accept and operate on a parameter that conforms to an interface, while not caring what else the object may do or how it is implemented. These interfaces are often named like `Iterable`, `Cacheable`, `Renderable`, or so on to describe the significance of the behavior.

Interfaces may define magic methods to require implementing classes to implement those methods.

> Note:

> Although they are supported, including constructors in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent and unexpected behavior.

### `implements`

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.

Warning

A class that implements an interface may use a different name for its parameters than the interface. However, as of PHP 8.0 the language supports named arguments, which means callers may rely on the parameter name in the interface. For that reason, it is strongly recommended that developers use the same parameter names as the interface being implemented.

> Note:

> Interfaces can be extended like classes using the extends operator.

> Note:

> The class implementing the interface must declare all methods in the interface with a compatible signature. A class can implement multiple interfaces which declare a method with the same name. In this case, the implementation must follow the signature compatibility rules for all the interfaces. So covariance and contravariance can be applied.

### Constants

It's possible for interfaces to have constants. Interface constants work exactly like class constants. Prior to PHP 8.1.0, they cannot be overridden by a class/interface that inherits them.

### Properties

As of PHP 8.4.0, interfaces may also declare properties. If they do, the declaration must specify if the property is to be readable, writeable, or both. The interface declaration applies only to public read and write access.

A class may satisfy an interface property in multiple ways. It may define a public property. It may define a public virtual property that implements only the corresponding hook. Or a read property may be satisfied by a `readonly` property. However, an interface property that is settable may not be `readonly`.

Example #1 Interface properties example

`<?php
interface I
{
// An implementing class MUST have a publicly-readable property,
// but whether or not it's publicly settable is unrestricted.
public string $readable { get; }
// An implementing class MUST have a publicly-writeable property,
// but whether or not it's publicly readable is unrestricted.
public string $writeable { set; }
// An implementing class MUST have a property that is both publicly
// readable and publicly writeable.
public string $both { get; set; }
}
// This class implements all three properties as traditional, un-hooked
// properties. That's entirely valid.
class C1 implements I
{
public string $readable;
public string $writeable;
public string $both;
}
// This class implements all three properties using just the hooks
// that are requested. This is also entirely valid.
class C2 implements I
{
private string $written = '';
private string $all = '';
// Uses only a get hook to create a virtual property.
// This satisfies the "public get" requirement.
// It is not writeable, but that is not required by the interface.
public string $readable { get => strtoupper($this->writeable); }
// The interface only requires the property be settable,
// but also including get operations is entirely valid.
// This example creates a virtual property, which is fine.
public string $writeable {
get => $this->written;
set {
$this->written = $value;
}
}
// This property requires both read and write be possible,
// so we need to either implement both, or allow it to have
// the default behavior.
public string $both {
get => $this->all;
set {
$this->all = strtoupper($value);
}
}
}
?>`

### Examples

Example #2 Interface example

`<?php
// Declare the interface 'Template'
interface Template
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class WorkingTemplate implements Template
{
private $vars = [];
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 (Template::getHtml)
class BadTemplate implements Template
{
private $vars = [];
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>`

Example #3 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 #4 Variance compatibility with multiple interfaces

`<?php
class Foo {}
class Bar extends Foo {}
interface A {
public function myfunc(Foo $arg): Foo;
}
interface B {
public function myfunc(Bar $arg): Bar;
}
class MyClass implements A, B
{
public function myfunc(Foo $arg): Bar
{
return new Bar();
}
}
?>`

Example #5 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 #6 Interfaces with constants

`<?php
interface A
{
const B = 'Interface constant';
}
// Prints: Interface constant
echo A::B;
class B implements A
{
const B = 'Class constant';
}
// Prints: Class constant
// Prior to PHP 8.1.0, this will however not work because it was not
// allowed to override constants.
echo B::B;
?>`

Example #7 Interfaces with abstract classes

`<?php
interface A
{
public function foo(string $s): string;
public function bar(int $i): int;
}
// An abstract class may implement only a portion of an interface.
// Classes that extend the abstract class must implement the rest.
abstract class B implements A
{
public function foo(string $s): string
{
return $s . PHP_EOL;
}
}
class C extends B
{
public function bar(int $i): int
{
return $i * 2;
}
}
?>`

Example #8 Extending and implementing simultaneously

`<?php
class One
{
/* ... */
}
interface Usable
{
/* ... */
}
interface Updatable
{
/* ... */
}
// The keyword order here is important. 'extends' must come first.
class Two extends One implements Usable, Updatable
{
/* ... */
}
?>`

An interface, together with type declarations, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type declarations.

## Traits

PHP implements a way to reuse code 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 TraitA {
public function sayHello() {
echo 'Hello';
}
}
trait TraitB {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld
{
use TraitA, TraitB; // A class can use multiple traits
public function sayHelloWorld() {
$this->sayHello();
echo ' ';
$this->sayWorld();
echo "!\n";
}
}
$myHelloWorld = new MyHelloWorld();
$myHelloWorld->sayHelloWorld();
?>`

The above example will output:

    Hello World!

### Precedence

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

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!

### Conflict Resolution

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 choose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the `as` operator can be used to add an alias to one of the methods. Note the `as` operator does not rename the method and it does not affect any other method either.

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

### Changing Method Visibility

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

### Traits Composed from Traits

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!

### Abstract Trait Members

Traits support the use of abstract methods in order to impose requirements upon the exhibiting class. Public, protected, and private methods are supported. Prior to PHP 8.0.0, only public and protected abstract methods were supported.

Caution

As of PHP 8.0.0, the signature of a concrete method must follow the signature compatibility rules. Previously, its signature might be different.

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

### Static Trait Members

Traits can define static variables, static methods and static properties.

> Note:

> As of PHP 8.1.0, calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

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();
$p = new C2();
$p->inc();
?>`

The above example will output:

    1
    1

Example #10 Static Methods

`<?php
trait StaticExample
{
public static function doSomething()
{
return 'Doing something';
}
}
class Example
{
use StaticExample;
}
echo Example::doSomething();
?>`

The above example will output:

    Doing something

Example #11 Static Properties

Caution

Prior to PHP 8.3.0, static properties defined in a trait were shared across all classes in the same inheritance hierarchy which used that trait. As of PHP 8.3.0, if a child class uses a trait with a static property, it will be considered distinct from the one defined in the parent class.

`<?php
trait T
{
public static $counter = 1;
}
class A
{
use T;
public static function incrementCounter()
{
static::$counter++;
}
}
class B extends A
{
use T;
}
A::incrementCounter();
echo A::$counter, "\n";
echo B::$counter, "\n";
?>`

Output of the above example in PHP 8.3:

    2
    1

### Properties

Traits can also define properties.

Example #12 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 unless it is compatible (same visibility and type, readonly modifier, and initial value), otherwise a fatal error is issued.

Example #13 Conflict Resolution

`<?php
trait PropertiesTrait {
public $same = true;
public $different1 = false;
public bool $different2;
public bool $different3;
}
class PropertiesExample {
use PropertiesTrait;
public $same = true;
public $different1 = true; // Fatal error
public string $different2; // Fatal error
readonly protected bool $different3; // Fatal error
}
?>`

### Constants

Traits can, as of PHP 8.2.0, also define constants.

Example #14 Defining Constants

`<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
}
$example = new ConstantsExample;
echo $example::FLAG_MUTABLE;
?>`

The above example will output:

    1

If a trait defines a constant then a class can not define a constant with the same name unless it is compatible (same visibility, initial value, and finality), otherwise a fatal error is issued.

Example #15 Conflict Resolution

`<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
public const FLAG_IMMUTABLE = 5; // Fatal error
}
?>`

### Final methods

As of PHP 8.3.0, the final modifier can be applied using the `as` operator to methods imported from traits. This can be used to prevent child classes from overriding the method. However, the class that uses the trait can still override the method.

Example #16 Defining a method coming from a trait as `final`

`<?php
trait CommonTrait
{
public function method()
{
echo 'Hello';
}
}
class FinalExampleA
{
use CommonTrait {
CommonTrait::method as final; // The 'final' prevents child classes from overriding the method
}
}
class FinalExampleB extends FinalExampleA
{
public function method() {}
}
?>`

The above example will output something similar to:

    Fatal error: Cannot override final method FinalExampleA::method() in ...

## Anonymous classes

Anonymous classes are useful when simple, one-off objects need to be created.

`<?php
// Using an explicit class
class Logger
{
public function log($msg)
{
echo $msg;
}
}
$util->setLogger(new Logger());
// Using an anonymous class
$util->setLogger(new class {
public function log($msg)
{
echo $msg;
}
});`

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

`<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
var_dump(new class(10) extends SomeClass implements SomeInterface {
private $num;
public function __construct($num)
{
$this->num = $num;
}
use SomeTrait;
});`

The above example will output:

    object(class@anonymous)#1 (1) {
      ["Command line code0x104c5b612":"class@anonymous":private]=>
      int(10)
    }

Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class' protected properties or methods, the anonymous class can extend the outer class. To use the private properties of the outer class in the anonymous class, they must be passed through its constructor:

`<?php
class Outer
{
private $prop = 1;
protected $prop2 = 2;
protected function func1()
{
return 3;
}
public function func2()
{
return new class($this->prop) extends Outer {
private $prop3;
public function __construct($prop)
{
$this->prop3 = $prop;
}
public function func3()
{
return $this->prop2 + $this->prop3 + $this->func1();
}
};
}
}
echo (new Outer)->func2()->func3();`

The above example will output:

    6

All objects created by the same anonymous class declaration are instances of that very class.

`<?php
function anonymous_class()
{
return new class {};
}
if (get_class(anonymous_class()) === get_class(anonymous_class())) {
echo 'same class';
} else {
echo 'different class';
}`

The above example will output:

    same class

> Note:

> Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example. This name has to be regarded an implementation detail, which should not be relied upon.

> `<?php
> echo get_class(new class {});`

> The above example will output something similar to:

>     class@anonymous/in/oNi1A0x7f8636ad2021

### Readonly anonymous classes

As of PHP 8.3.0, the `readonly` modifier can be applied to anonymous classes.

Example #1 Defining a readonly anonymous class

`<?php
// Using an anonymous class
var_dump(new readonly class('[DEBUG]') {
public function __construct(private string $prefix)
{
}
public function log($msg)
{
echo $this->prefix . ' ' . $msg;
}
});`

## Overloading

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.

### Property overloading

public __set(string `$name`, mixed `$value`): void
public __get(string `$name`): mixed
public __isset(string `$name`): bool
public __unset(string `$name`): void

__set() is run when writing data to inaccessible (protected or private) or non-existing properties.

__get() is utilized for reading data from inaccessible (protected or private) or non-existing properties.

__isset() is triggered by calling isset() or empty() on inaccessible (protected or private) or non-existing properties.

__unset() is invoked when unset() is used on inaccessible (protected or private) or non-existing 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. 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;

> Note:

> PHP will not call an overloaded method from within the same overloaded method. That means, for example, writing `return $this->foo` inside of __get() will return `null` and raise an `E_WARNING` if there is no `foo` property defined, rather than calling __get() a second time. However, overload methods may invoke other overload methods implicitly (such as __set() triggering __get()).

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;
}
public function __isset($name)
{
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
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;
}
}
$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

### Method overloading

public __call(string `$name`, array `$arguments`): mixed
public static __callStatic(string `$name`, array `$arguments`): mixed

__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";
}
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');
?>`

The above example will output:

    Calling object method 'runTest' in object context
    Calling static method 'runTest' in static context

## Object Iteration

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

### See Also

- Generators
- Iterator
- IteratorAggregate
- SPL Iterators

## Magic Methods

Magic methods are special methods which override PHP's default's action when certain actions are performed on an object.

Caution

All methods names starting with `__` are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.

The following method names are considered magical: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __serialize(), __unserialize(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __debugInfo().

Warning

All magic methods, with the exception of __construct(), __destruct(), and __clone(), must be declared as `public`, otherwise an `E_WARNING` is emitted. Prior to PHP 8.0.0, no diagnostic was emitted for the magic methods __sleep(), __wakeup(), __serialize(), __unserialize(), and __set_state().

Warning

If type declarations are used in the definition of a magic method, they must be identical to the signature described in this document. Otherwise, a fatal error is emitted. Prior to PHP 8.0.0, no diagnostic was emitted. However, __construct() and __destruct() must not declare a return type; otherwise a fatal error is emitted.

### __serialize() and __unserialize()

public __serialize(): array
public __unserialize(array `$data`): void

serialize() checks if the class has a function with the magic name __serialize(). If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a TypeError will be thrown.

> Note:

> If both __serialize() and __sleep() are defined in the same object, only __serialize() will be called. __sleep() will be ignored. If the object implements the Serializable interface, the interface's `serialize()` method will be ignored and __serialize() used instead.

The intended use of __serialize() is to define a serialization-friendly arbitrary representation of the object. Elements of the array may correspond to properties of the object but that is not required.

Conversely, unserialize() checks for the presence of a function with the magic name __unserialize(). If present, this function will be passed the restored array that was returned from __serialize(). It may then restore the properties of the object from that array as appropriate.

> Note:

> If both __unserialize() and __wakeup() are defined in the same object, only __unserialize() will be called. __wakeup() will be ignored.

> Note:

> This feature is available as of PHP 7.4.0.

Example #1 Serialize and unserialize

`<?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 __serialize(): array
{
return [
'dsn' => $this->dsn,
'user' => $this->username,
'pass' => $this->password,
];
}
public function __unserialize(array $data): void
{
$this->dsn = $data['dsn'];
$this->username = $data['user'];
$this->password = $data['pass'];
$this->connect();
}
}?>`

### __sleep() and __wakeup()

Warning

This serialization mechanism is soft-deprecated as of PHP 8.5.0. It is maintained for backward compatibility. However, new and existing code should be migrated to use the __serialize() and __unserialize() magic methods instead.

public __sleep(): array
public __wakeup(): void

serialize() checks if the 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_NOTICE` level error. Use __serialize() instead.

> Note:

> As of PHP 8.0.0, returning a value which is not an array from __sleep() generates a warning. Previously, it generated a notice.

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if a very large object doesn't 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 #2 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();
}
}?>`

### __toString()

public __toString(): string

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.

Warning

As of PHP 8.0.0, the return value follows standard PHP type semantics, meaning it will be coerced into a string if possible and if strict typing is disabled.

A Stringable object will not be accepted by a string type declaration if strict typing is enabled. If such behaviour is wanted the type declaration must accept Stringable and string via a union type.

As of PHP 8.0.0, any class that contains a __toString() method will also implicitly implement the Stringable interface, and will thus pass type checks for that interface. Explicitly implementing the interface anyway is recommended.

In PHP 7.4, the returned value must be a string, otherwise an Error is thrown.

Prior to PHP 7.4.0, the returned value must be a string, otherwise a fatal `E_RECOVERABLE_ERROR` is emitted.

Warning

It was not possible to throw an exception from within a __toString() method prior to PHP 7.4.0. Doing so will result in a fatal error.

Example #3 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

### __invoke()

__invoke( `...$values`): mixed

The __invoke() method is called when a script tries to call an object as a function.

Example #4 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)

Example #5 Using __invoke()

`<?php
class Sort
{
private $key;
public function __construct(string $key)
{
$this->key = $key;
}
public function __invoke(array $a, array $b): int
{
return $a[$this->key] <=> $b[$this->key];
}
}
$customers = [
['id' => 1, 'first_name' => 'John', 'last_name' => 'Do'],
['id' => 3, 'first_name' => 'Alice', 'last_name' => 'Gustav'],
['id' => 2, 'first_name' => 'Bob', 'last_name' => 'Filipe']
];
// sort customers by first name
usort($customers, new Sort('first_name'));
print_r($customers);
// sort customers by last name
usort($customers, new Sort('last_name'));
print_r($customers);
?>`

The above example will output:

    Array
    (
        [0] => Array
            (
                [id] => 3
                [first_name] => Alice
                [last_name] => Gustav
            )

        [1] => Array
            (
                [id] => 2
                [first_name] => Bob
                [last_name] => Filipe
            )

        [2] => Array
            (
                [id] => 1
                [first_name] => John
                [last_name] => Do
            )

    )
    Array
    (
        [0] => Array
            (
                [id] => 1
                [first_name] => John
                [last_name] => Do
            )

        [1] => Array
            (
                [id] => 2
                [first_name] => Bob
                [last_name] => Filipe
            )

        [2] => Array
            (
                [id] => 3
                [first_name] => Alice
                [last_name] => Gustav
            )

    )

### __set_state()

static __set_state(array `$properties`): object

This static method is called for classes exported by var_export().

The only parameter of this method is an array containing exported properties in the form `['property' => value, ...]`.

Example #6 Using __set_state()

`<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
$b = var_export($a, true);
var_dump($b);
eval('$c = ' . $b . ';');
var_dump($c);
?>`

The above example will output:

    string(60) "A::__set_state(array(
       'var1' => 5,
       'var2' => 'foo',
    ))"
    object(A)#2 (2) {
      ["var1"]=>
      int(5)
      ["var2"]=>
      string(3) "foo"
    }

> Note: When exporting an object, var_export() does not check whether __set_state() is implemented by the object's class, so re-importing objects will result in an Error exception, if __set_state() is not implemented. Particularly, this affects some internal classes. It is the responsibility of the programmer to verify that only objects will be re-imported, whose class implements __set_state().

### __debugInfo()

__debugInfo(): array

This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.

Example #7 Using __debugInfo()

`<?php
class C {
private $prop;
public function __construct($val) {
$this->prop = $val;
}
public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new C(42));
?>`

The above example will output:

    object(C)#1 (1) {
      ["propSquared"]=>
      int(1764)
    }

## Final Keyword

The final keyword prevents child classes from overriding a method, property, or constant 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";
}
// As the class is already final, the final keyword is redundant
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)
?>`

Example #3 Final property example as of PHP 8.4.0

`<?php
class BaseClass {
final protected string $test;
}
class ChildClass extends BaseClass {
public string $test;
}
// Results in Fatal error: Cannot override final property BaseClass::$test
?>`

Example #4 Final constants example as of PHP 8.1.0

`<?php
class Foo
{
final public const X = "foo";
}
class Bar extends Foo
{
public const X = "bar";
}
// Fatal error: Bar::X cannot override final constant Foo::X
?>`

> Note: As of PHP 8.0.0, private methods may not be declared final except for the constructor.

> Note: A property that is declared `private(set)` is implicitly `final`.

## Object Cloning

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

    $copy_of_object = clone $object;

When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

__clone(): void

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
            )

    )

It is possible to access a member of a freshly cloned object in a single expression:

Example #2 Access member of freshly cloned object

`<?php
$dateTime = new DateTime();
echo (clone $dateTime)->format('Y');
?>`

The above example will output something similar to:

    2016

## Comparing Objects

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 (values are compared with `==`), 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

`<?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 __construct($flag = true) {
$this->flag = $flag;
}
}
class OtherFlag
{
public $flag;
function __construct($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 (`==`).

## Late Static Bindings

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.

### Limitations of `self::`

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' usage

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 referencing `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();
try {
$c->test();
} catch (Error $e) {
echo $e->getMessage();
}
?>`

The above example will output:

    Success!
    Success!
    Success!
    Call to private method C::foo() from scope A

> 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

## Objects and references

One of the key-points of PHP 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. In PHP, an object variable doesn't contain the object itself as value. 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

## Serializing objects - objects in sessions

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
// A.php:
class A {
public $one = 1;
public function show_one() {
echo $this->one;
}
}
// page1.php:
include "A.php";
$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 "A.php";
$s = file_get_contents('store');
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?>`

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 adding a new key to the $_SESSION superglobal array, you should include the file `A.php` 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.

## Covariance and Contravariance

In PHP 7.2.0, partial contravariance was introduced by removing type restrictions on parameters in a child method. As of PHP 7.4.0, full covariance and contravariance support was added.

Covariance allows a child's method to return a more specific type than the return type of its parent's method. Contravariance allows a parameter type to be less specific in a child method, than that of its parent.

A type declaration is considered more specific in the following case:

- A type is removed from a union type
- A type is added to an intersection type
- A class type is changed to a child class type
- iterable is changed to array or Traversable

A type class is considered less specific if the opposite is true.

### Covariance

To illustrate how covariance works, a simple abstract parent class, Animal is created. Animal will be extended by children classes, Cat, and Dog.

`<?php
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
abstract public function speak();
}
class Dog extends Animal
{
public function speak()
{
echo $this->name . " barks";
}
}
class Cat extends Animal
{
public function speak()
{
echo $this->name . " meows";
}
}`

Note that there aren't any methods which return values in this example. A few factories will be added which return a new object of class type Animal, Cat, or Dog.

`<?php
interface AnimalShelter
{
public function adopt(string $name): Animal;
}
class CatShelter implements AnimalShelter
{
public function adopt(string $name): Cat // instead of returning class type Animal, it can return class type Cat
{
return new Cat($name);
}
}
class DogShelter implements AnimalShelter
{
public function adopt(string $name): Dog // instead of returning class type Animal, it can return class type Dog
{
return new Dog($name);
}
}
$kitty = (new CatShelter)->adopt("Ricky");
$kitty->speak();
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$doggy->speak();`

The above example will output:

    Ricky meows
    Mavrick barks

### Contravariance

Continuing with the previous example with the classes Animal, Cat, and Dog, a class called Food and AnimalFood will be included, and a method eat(AnimalFood $food) is added to the Animal abstract class.

`<?php
class Food {}
class AnimalFood extends Food {}
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function eat(AnimalFood $food)
{
echo $this->name . " eats " . get_class($food);
}
}`

In order to see the behavior of contravariance, the eat method is overridden in the Dog class to allow any Food type object. The Cat class remains unchanged.

`<?php
class Dog extends Animal
{
public function eat(Food $food) {
echo $this->name . " eats " . get_class($food);
}
}`

The next example will show the behavior of contravariance.

`<?php
$kitty = (new CatShelter)->adopt("Ricky");
$catFood = new AnimalFood();
$kitty->eat($catFood);
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$banana = new Food();
$doggy->eat($banana);`

The above example will output:

    Ricky eats AnimalFood
    Mavrick eats Food

But what happens if $kitty tries to eat() the $banana?

`$kitty->eat($banana);`

The above example will output:

    Fatal error: Uncaught TypeError: Argument 1 passed to Animal::eat() must be an instance of AnimalFood, instance of Food given

### Property variance

By default, properties are neither covariant nor contravariant, hence invariant. That is, their type may not change in a child class at all. The reason for that is "get" operations must be covariant, and "set" operations must be contravariant. The only way for a property to satisfy both requirements is to be invariant.

As of PHP 8.4.0, with the addition of abstract properties (on an interface or abstract class) and virtual properties, it is possible to declare a property that has only a get or set operation. As a result, abstract properties or virtual properties that have only a "get" operation required may be covariant. Similarly, an abstract property or virtual property that has only a "set" operation required may be contravariant.

Once a property has both a get and set operation, however, it is no longer covariant or contravariant for further extension. That is, it is now invariant.

Example #1 Property type variance

`<?php
class Animal {}
class Dog extends Animal {}
class Poodle extends Dog {}
interface PetOwner
{
// Only a get operation is required, so this may be covariant.
public Animal $pet { get; }
}
class DogOwner implements PetOwner
{
// This may be a more restrictive type since the "get" side
// still returns an Animal. However, as a native property
// children of this class may not change the type anymore.
public Dog $pet;
}
class PoodleOwner extends DogOwner
{
// This is NOT ALLOWED, because DogOwner::$pet has both
// get and set operations defined and required.
public Poodle $pet;
}
?>`

## Lazy Objects

A lazy object is an object whose initialization is deferred until its state is observed or modified. Some use-case examples include dependency injection components that provide lazy services fully initialized only if needed, ORMs providing lazy entities that hydrate themselves from the database only when accessed, or a JSON parser that delays parsing until elements are accessed.

Two lazy object strategies are supported: Ghost Objects and Virtual Proxies, hereafter referred to as "lazy ghosts" and "lazy proxies". In both strategies, the lazy object is attached to an initializer or factory that is called automatically when its state is observed or modified for the first time. From an abstraction point of view, lazy ghost objects are indistinguishable from non-lazy ones: they can be used without knowing they are lazy, allowing them to be passed to and used by code that is unaware of laziness. Lazy proxies are similarly transparent, but care must be taken when their identity is used, as the proxy and its real instance have different identities.

> Note: Version Information
> Lazy objects were introduced in PHP 8.4.

### Creating Lazy Objects

It is possible to create a lazy instance of any user defined class or the stdClass class (other internal classes are not supported), or to reset an instance of these classes to make it lazy. The entry points for creating a lazy object are the ReflectionClass::newLazyGhost() and ReflectionClass::newLazyProxy() methods.

Both methods accept a function that is called when the object requires initialization. The function's expected behavior varies depending on the strategy in use, as described in the reference documentation for each method.

Example #1 Creating a Lazy Ghost

`<?php
class Example
{
public function __construct(public int $prop)
{
echo __METHOD__, "\n";
}
}
$reflector = new ReflectionClass(Example::class);
$lazyObject = $reflector->newLazyGhost(function (Example $object) {
// Initialize object in-place
$object->__construct(1);
});
var_dump($lazyObject);
var_dump(get_class($lazyObject));
// Triggers initialization
var_dump($lazyObject->prop);
?>`

The above example will output:

    lazy ghost object(Example)#3 (0) {
    ["prop"]=>
    uninitialized(int)
    }
    string(7) "Example"
    Example::__construct
    int(1)

Example #2 Creating a Lazy Proxy

`<?php
class Example
{
public function __construct(public int $prop)
{
echo __METHOD__, "\n";
}
}
$reflector = new ReflectionClass(Example::class);
$lazyObject = $reflector->newLazyProxy(function (Example $object) {
// Create and return the real instance
return new Example(1);
});
var_dump($lazyObject);
var_dump(get_class($lazyObject));
// Triggers initialization
var_dump($lazyObject->prop);
?>`

The above example will output:

    lazy proxy object(Example)#3 (0) {
      ["prop"]=>
      uninitialized(int)
    }
    string(7) "Example"
    Example::__construct
    int(1)

Any access to properties of a lazy object triggers its initialization (including via ReflectionProperty). However, certain properties might be known in advance and should not trigger initialization when accessed:

Example #3 Initializing Properties Eagerly

`<?php
class BlogPost
{
public function __construct(
public int $id,
public string $title,
public string $content,
) { }
}
$reflector = new ReflectionClass(BlogPost::class);
$post = $reflector->newLazyGhost(function ($post) {
$data = fetch_from_store($post->id);
$post->__construct($data['id'], $data['title'], $data['content']);
});
// Without this line, the following call to ReflectionProperty::setValue() would
// trigger initialization.
$reflector->getProperty('id')->skipLazyInitialization($post);
$reflector->getProperty('id')->setValue($post, 123);
// Alternatively, one can use this directly:
$reflector->getProperty('id')->setRawValueWithoutLazyInitialization($post, 123);
// The id property can be accessed without triggering initialization
var_dump($post->id);
?>`

The ReflectionProperty::skipLazyInitialization() and ReflectionProperty::setRawValueWithoutLazyInitialization() methods offer ways to bypass lazy-initialization when accessing a property.

### About Lazy Object Strategies

Lazy ghosts are objects that initialize in-place and, once initialized, are indistinguishable from an object that was never lazy. This strategy is suitable when we control both the instantiation and initialization of the object, making it unsuitable if either of these is managed by another party.

Lazy proxies, once initialized, act as proxies to a real instance: any operation on an initialized lazy proxy is forwarded to the real instance. The creation of the real instance can be delegated to another party, making this strategy useful in cases where lazy ghosts are unsuitable. Although lazy proxies are nearly as transparent as lazy ghosts, caution is needed when their identity is used, as the proxy and its real instance have distinct identities.

### Lifecycle of Lazy Objects

Objects can be made lazy at instantiation time using ReflectionClass::newLazyGhost() or ReflectionClass::newLazyProxy(), or after instantiation by using ReflectionClass::resetAsLazyGhost() or ReflectionClass::resetAsLazyProxy(). Following this, a lazy object can become initialized through one of the following operations:

- Interacting with the object in a way that triggers automatic initialization. See Initialization triggers.
- Marking all its properties as non-lazy using ReflectionProperty::skipLazyInitialization() or ReflectionProperty::setRawValueWithoutLazyInitialization().
- Calling explicitly ReflectionClass::initializeLazyObject() or ReflectionClass::markLazyObjectAsInitialized().

As lazy objects become initialized when all their properties are marked non-lazy, the above methods will not mark an object as lazy if no properties could be marked as lazy.

### Initialization Triggers

Lazy objects are designed to be fully transparent to their consumers, so normal operations that observe or modify the object's state will automatically trigger initialization before the operation is performed. This includes, but is not limited to, the following operations:

- Reading or writing a property.
- Testing if a property is set or unsetting it.
- Accessing or modifying a property via ReflectionProperty::getValue(), ReflectionProperty::getRawValue(), ReflectionProperty::setValue(), or ReflectionProperty::setRawValue().
- Listing properties with ReflectionObject::getProperties(), ReflectionObject::getProperty(), get_object_vars().
- Iterating over properties of an object that does not implement Iterator or IteratorAggregate using foreach.
- Serializing the object with serialize(), json_encode(), etc.
- Cloning the object.

Method calls that do not access the object state will not trigger initialization. Similarly, interactions with the object that invoke magic methods or hook functions will not trigger initialization if these methods or functions do not access the object's state.

#### Non-Triggering Operations

The following specific methods or low-level operations allow access or modification of lazy objects without triggering initialization:

- Marking properties as non-lazy with ReflectionProperty::skipLazyInitialization() or ReflectionProperty::setRawValueWithoutLazyInitialization().
- Retrieving the internal representation of properties using get_mangled_object_vars() or by casting the object to an array.
- Using serialize() when `ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE` is set, unless __serialize() or __sleep() trigger initialization.
- Calling to ReflectionObject::__toString().
- Using var_dump() or debug_zval_dump(), unless __debugInfo() triggers initialization.

### Initialization Sequence

This section outlines the sequence of operations performed when initialization is triggered, based on the strategy in use.

#### Ghost Objects

- The object is marked as non-lazy.
- Properties not initialized with ReflectionProperty::skipLazyInitialization() or ReflectionProperty::setRawValueWithoutLazyInitialization() are set to their default values, if any. At this stage, the object resembles one created with ReflectionClass::newInstanceWithoutConstructor(), except for already initialized properties.
- The initializer function is then called with the object as its first parameter. The function is expected, but not required, to initialize the object state, and must return `null` or no value. The object is no longer lazy at this point, so the function can access its properties directly.

After initialization, the object is indistinguishable from an object that was never lazy.

#### Proxy Objects

- The object is marked as non-lazy.
- Unlike ghost objects, the properties of the object are not modified at this stage.
- The factory function is called with the object as its first parameter and must return a non-lazy instance of a compatible class (see ReflectionClass::newLazyProxy()).
- The returned instance is referred to as the real instance and is attached to the proxy.
- The proxy's property values are discarded as though unset() was called.

After initialization, accessing any property on the proxy will yield the same result as accessing the corresponding property on the real instance; all property accesses on the proxy are forwarded to the real instance, including declared, dynamic, non-existing, or properties marked with ReflectionProperty::skipLazyInitialization() or ReflectionProperty::setRawValueWithoutLazyInitialization().

The proxy object itself is not replaced or substituted for the real instance.

While the factory receives the proxy as its first parameter, it is not expected to modify it (modifications are allowed but will be lost during the final initialization step). However, the proxy can be used for decisions based on the values of initialized properties, the class, the object itself, or its identity. For instance, the initializer might use an initialized property's value when creating the real instance.

#### Common Behavior

The scope and $this context of the initializer or factory function remains unchanged, and usual visibility constraints apply.

After successful initialization, the initializer or factory function is no longer referenced by the object and may be released if it has no other references.

If the initializer throws an exception, the object state is reverted to its pre-initialization state and the object is marked as lazy again. In other words, all effects on the object itself are reverted. Other side effects, such as effects on other objects, are not reverted. This prevents exposing a partially initialized instance in case of failure.

### Cloning

Cloning a lazy object triggers its initialization before the clone is created, resulting in an initialized object.

For proxy objects, both the proxy and its real instance are cloned, and the clone of the proxy is returned. The `__clone` method is called on the real instance, not on the proxy. The cloned proxy and real instance are linked as they are during initialization, so accesses to the proxy clone are forwarded to the real instance clone.

This behavior ensures that the clone and the original object maintain separate states. Changes to the original object or its initializer's state after cloning do not affect the clone. Cloning both the proxy and its real instance, rather than returning a clone of the real instance alone, ensures that the clone operation consistently returns an object of the same class.

### Destructors

For lazy ghosts, the destructor is only called if the object has been initialized. For proxies, the destructor is only called on the real instance, if one exists.

The ReflectionClass::resetAsLazyGhost() and ReflectionClass::resetAsLazyProxy() methods may invoke the destructor of the object being reset.

## OOP Changelog

Changes to the PHP OOP model are logged here. Descriptions and other notes regarding these features are documented within the OOP model documentation.

Version | Description
--- | ---
8.4.0 | Added: Support for Property Hooks.
8.4.0 | Added: Support for Lazy Objects.
8.1.0 | Added: Support for the final modifier for class constants. Also, interface constants become overridable by default.
8.0.0 | Added: Support for the nullsafe operator ?-> to access properties and methods on objects that may be null.
7.4.0 | Changed: It is now possible to throw exception within __toString().
7.4.0 | Added: Support for limited return type covariance and argument type contravariance. Full variance support is only available if autoloading is used. Inside a single file only non-cyclic type references are possible.
7.4.0 | Added: It is now possible to type class properties.
7.3.0 | Incompatibility: Argument unpacking of Traversables with non-int keys is no longer supported. This behaviour was not intended and thus has been removed.
7.3.0 | Incompatibility: In previous versions it was possible to separate the static properties by assigning a reference. This has been removed.
7.3.0 | Changed: The instanceof operator now allows literals as the first operand, in which case the result is always `false`.
7.2.0 | Deprecated: The __autoload() method has been deprecated in favour of spl_autoload_register().
7.2.0 | Changed: The following name cannot be used to name classes, interfaces, or traits: `object`.
7.2.0 | Changed: A trailing comma can now be added to the group-use syntax for namespaces.
7.2.0 | Changed: Parameter type widening. Parameter types from overridden methods and from interface implementations may now be omitted.
7.2.0 | Changed: Abstract methods can now be overridden when an abstract class extends another abstract class.
7.1.0 | Changed: The following names cannot be used to name classes, interfaces, or traits: `void` and `iterable`.
7.1.0 | Added: It is now possible to specify the visibility of class constants.
7.0.0 | Deprecated: Static calls to methods that are not declared static.
7.0.0 | Deprecated: PHP 4 style constructor. I.e. methods that have the same name as the class they are defined in.
7.0.0 | Added: Group use declaration: classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.
7.0.0 | Added: Support for anonymous classes has been added via `new class`.
7.0.0 | Incompatibility: Iterating over a non-Traversable object will now have the same behaviour as iterating over by-reference arrays.
7.0.0 | Changed: Defining (compatible) properties in two used traits no longer triggers an error.
5.6.0 | Added: The __debugInfo() method.
5.5.0 | Added: The ::class magic constant.
5.5.0 | Added: finally to handle exceptions.
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). As of 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.

# Namespaces

## Table of Contents

- Overview
- Namespaces
- Sub-namespaces
- Defining multiple namespaces in the same file
- Basics
- Namespaces and dynamic language features
- namespace keyword and __NAMESPACE__
- Aliasing and Importing
- Global space
- Fallback to global space
- Name resolution rules
- FAQ

## Namespaces overview

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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:

1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

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 are case-insensitive.

> Note:

> The Namespace name `PHP`, and compound names starting with this name (like `PHP\Classes`) are reserved for internal language use and should not be used in the userspace code.

## Defining namespaces

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstract classes, traits and enums), 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() { /* ... */ }
?>`

> Note: Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions.

The only code construct allowed before a namespace declaration is the `declare` statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace:

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.

## Declaring sub-namespaces

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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() { /* ... */ }
?>`
The above example creates constant `MyProject\Sub\Level\CONNECT_OK`, class `MyProject\Sub\Level\Connection` and function `MyProject\Sub\Level\connect`.

## Defining multiple namespaces in the same file

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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();
}
?>`

## Using namespaces: Basics

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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:

1. Relative file name like `foo.txt`. This resolves to `currentdirectory/foo.txt` where `currentdirectory` is the directory currently occupied. So if the current directory is `/home/foo`, the name resolves to `/home/foo/foo.txt`.
2. Relative path name like `subdirectory/foo.txt`. This resolves to `currentdirectory/subdirectory/foo.txt`.
3. Absolute path name like `/main/foo.txt`. This resolves to `/main/foo.txt`.

The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:

1. Unqualified name, or an unprefixed class name like `$a = new foo();` or `foo::staticmethod();`. If the current namespace is `currentnamespace`, this resolves to `currentnamespace\foo`. If the code is global, non-namespaced code, this resolves to `foo`. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See Using namespaces: fallback to global function/constant for details.
2. Qualified name, or a prefixed class name like `$a = new subnamespace\foo();` or `subnamespace\foo::staticmethod();`. If the current namespace is `currentnamespace`, this resolves to `currentnamespace\subnamespace\foo`. If the code is global, non-namespaced code, this resolves to `subnamespace\foo`.
3. Fully qualified name, or a prefixed name with global prefix operator like `$a = new \currentnamespace\foo();` or `\currentnamespace\foo::staticmethod();`. This always resolves to the literal name specified in the code, `currentnamespace\foo`.

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
?>`

## Namespaces and dynamic language features

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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
?>`
One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

Example #2 Dynamically accessing namespaced elements

`<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
/* 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.

## The namespace keyword and __NAMESPACE__ magic constant

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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 ""
?>`
The `__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: Aliasing/Importing"
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
?>`

## Using namespaces: Aliasing/Importing

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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 can alias(/import) constants, functions, classes, interfaces, traits, enums and namespaces.

Aliasing is accomplished with the `use` operator. Here is an example showing all 5 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;
// importing a function
use function My\Full\functionName;
// aliasing a function
use function My\Full\functionName as func;
// importing a constant
use const My\Full\CONSTANT;
$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
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>`
Note that for namespaced names (fully qualified namespace names containing namespace separator, such as `Foo\Bar` as opposed to global names that do not, such as `FooBar`), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.

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
?>`

### Scoping rules for importing

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;
function toGreenlandic()
{
use Languages\Danish;
// ...
}
?>`

> Note:

> Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

### Group `use` declarations

Classes, functions and constants being imported from the same `namespace` can be grouped together in a single `use` statement.

`<?php
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// is equivalent to the following groupped use declaration
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};`

## Global space

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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

## Using namespaces: fallback to the global space for functions and constants

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

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

## Name resolution rules

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

For the purposes of these resolution rules, here are some important definitions:

Namespace name definitions
Unqualified name

  This is an identifier without a namespace separator, such as `Foo`

Qualified name

  This is an identifier with a namespace separator, such as `Foo\Bar`

Fully qualified name

  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.

Relative name

  This is an identifier starting with `namespace`, such as `namespace\Foo\Bar`.

Names are resolved following these resolution rules:

1. Fully qualified names always resolve to the name without leading namespace separator. For instance `\A\B` resolves to `A\B`.
2. Relative names always resolve to the name with `namespace` replaced by the current namespace. If the name occurs in the global namespace, the `namespace\` prefix is stripped. For example `namespace\A` inside namespace `X\Y` resolves to `X\Y\A`. The same name inside the global namespace resolves to `A`.
3. For qualified names the first segment of the name is translated according to the current class/namespace import table. For example, if the namespace `A\B\C` is imported as `C`, the name `C\D\E` is translated to `A\B\C\D\E`.
4. For qualified names, if no import rule applies, the current namespace is prepended to the name. For example, the name `C\D\E` inside namespace `A\B`, resolves to `A\B\C\D\E`.
5. For unqualified names, the name is translated according to the current import table for the respective symbol type. This means that class-like names are translated according to the class/namespace import table, function names according to the function import table and constants according to the constant import table. For example, after `use A\B\C;` a usage such as `new C()` resolves to the name `A\B\C()`. Similarly, after `use function A\B\foo;` a usage such as `foo()` resolves to the name `A\B\foo`.
6. For unqualified names, if no import rule applies and the name refers to a class-like symbol, the current namespace is prepended. For example `new C()` inside namespace `A\B` resolves to name `A\B\C`.
7. For unqualified names, if no import rule applies and the name refers to a function or constant and the code is outside the global namespace, the name is resolved at runtime. Assuming the code is in namespace `A\B`, here is how a call to function `foo()` is resolved:
   1. It looks for a function from the current namespace: `A\B\foo()`.
   2. It tries to find and call the global function `foo()`.

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"
?>`

## FAQ: things you need to know about namespaces

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

1. If I don't use namespaces, should I care about any of this?
2. How do I use internal or global classes in a namespace?
3. How do I use namespaces classes functions, or constants in their own namespace?
4. How does a name like `\my\name` or `\name` resolve?
5. How does a name like `my\name` resolve?
6. How does an unqualified class name like `name` resolve?
7. How does an unqualified function name or unqualified constant name like `name` resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

1. Import names must not conflict with classes defined in the same file.
2. Nested namespaces are not allowed.
3. Dynamic namespace names (quoted identifiers) should escape backslash.
4. Undefined Constants referenced using any backslash die with fatal error
5. Cannot override special constants `null`, `true` or `false`

### If I don't use namespaces, should I care about any of this?

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

### How do I use internal or global classes in a namespace?

Example #3 Accessing internal classes in namespaces

`<?php
namespace foo;
$a = new \stdClass;
function test(\ArrayObject $parameter_type_example = null) {}
$a = \DirectoryIterator::CURRENT_AS_FILEINFO;
// extending an internal or global class
class MyException extends \Exception {}
?>`

### How do I use namespaces classes, functions, or constants in their own namespace?

Example #4 Accessing internal classes, functions or constants in namespaces

`<?php
namespace foo;
class MyClass {}
// using a class from the current namespace as a parameter type
function test(MyClass $parameter_type_example = null) {}
// another way to use a class from the current namespace as a parameter type
function test(\foo\MyClass $parameter_type_example = 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;
?>`

### How does a name like `\my\name` or `\name` resolve?

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"
?>`

### How does a name like `my\name` resolve?

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"
?>`

### How does an unqualified class name like `name` resolve?

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"
?>`

### How does an unqualified function name or unqualified constant name like `name` resolve?

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"
?>`

### Import names must not conflict with classes defined in the same file.

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

### Nested namespaces are not allowed.

PHP does not allow nesting namespaces

`<?php
namespace my\stuff {
namespace nested {
class foo {}
}
}
?>`
However, it is easy to simulate nested namespaces like so:
`<?php
namespace my\stuff\nested {
class foo {}
}
?>`

### Dynamic namespace names (quoted identifiers) should escape backslash

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;
?>`
Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

### Undefined Constants referenced using any backslash die with fatal error

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
?>`

### Cannot override special constants `null`, `true` or `false`

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

# Enumerations

## Table of Contents

- Enumerations overview
- Basic enumerations
- Backed enumerations
- Enumeration methods
- Enumeration static methods
- Enumeration constants
- Traits
- Enum values in constant expressions
- Differences from objects
- Value listing
- Serialization
- Why enums aren't extendable
- Examples

## Enumerations overview

(PHP 8 >= 8.1.0)

Enumerations, or "Enums", allow a developer to define a custom type that is limited to one of a discrete number of possible values. That can be especially helpful when defining a domain model, as it enables "making invalid states unrepresentable."

Enums appear in many languages with a variety of different features. In PHP, Enums are a special kind of object. The Enum itself is a class, and its possible cases are all single-instance objects of that class. That means Enum cases are valid objects and may be used anywhere an object may be used, including type checks.

The most popular example of enumerations is the built-in boolean type, which is an enumerated type with legal values `true` and `false`. Enums allows developers to define their own arbitrarily robust enumerations.

## Basic enumerations

Enums are similar to classes, and share the same namespaces as classes, interfaces, and traits. They are also autoloadable the same way. An Enum defines a new type, which has a fixed, limited number of possible legal values.

`<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
?>`

This declaration creates a new enumerated type named `Suit`, which has four and only four legal values: `Suit::Hearts`, `Suit::Diamonds`, `Suit::Clubs`, and `Suit::Spades`. Variables may be assigned to one of those legal values. A function may be type checked against an enumerated type, in which case only values of that type may be passed.

`<?php
function pick_a_card(Suit $suit)
{
/* ... */
}
$val = Suit::Diamonds;
// OK
pick_a_card($val);
// OK
pick_a_card(Suit::Clubs);
// TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given
pick_a_card('Spades');
?>`

An Enumeration may have zero or more `case` definitions, with no maximum. A zero-case enum is syntactically valid, if rather useless.

For Enumeration cases, the same syntax rules apply as to any label in PHP, see Constants.

By default, cases are not intrinsically backed by a scalar value. That is, `Suit::Hearts` is not equal to `"0"`. Instead, each case is backed by a singleton object of that name. That means that:

`<?php
$a = Suit::Spades;
$b = Suit::Spades;
$a === $b; // true
$a instanceof Suit; // true
$a !== 'Spades'; // true
?>`

It also means that enum values are never `<` or `>` each other, since those comparisons are not meaningful on objects. Those comparisons will always return `false` when working with enum values.

This type of case, with no related data, is called a "Pure Case." An Enum that contains only Pure Cases is called a Pure Enum.

All Pure Cases are implemented as instances of their enum type. The enum type is represented internally as a class.

All Cases have a read-only property, `name`, that is the case-sensitive name of the case itself.

`<?php
print Suit::Spades->name;
// prints "Spades"
?>`

It is also possible to use the defined() and constant() functions to check for the existence of or read an enum case if the name is obtained dynamically. This is, however, discouraged as using Backed enums should work for most use cases.

## Backed enumerations

By default, Enumerated Cases have no scalar equivalent. They are simply singleton objects. However, there are ample cases where an Enumerated Case needs to be able to round-trip to a database or similar datastore, so having a built-in scalar (and thus trivially serializable) equivalent defined intrinsically is useful.

To define a scalar equivalent for an Enumeration, the syntax is as follows:

`<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
?>`

A case that has a scalar equivalent is called a Backed Case, as it is "Backed" by a simpler value. An Enum that contains all Backed Cases is called a "Backed Enum." A Backed Enum may contain only Backed Cases. A Pure Enum may contain only Pure Cases.

A Backed Enum may be backed by types of `int` or `string`, and a given enumeration supports only a single type at a time (that is, no union of `int|string`). If an enumeration is marked as having a scalar equivalent, then all cases must have a unique scalar equivalent defined explicitly. There are no auto-generated scalar equivalents (e.g., sequential integers). Backed cases must be unique; two backed enum cases may not have the same scalar equivalent. However, a constant may refer to a case, effectively creating an alias. See Enumeration constants.

The equivalent values may be a constant scalar expression. Prior to PHP 8.2.0, the equivalent values had to be literals or literal expressions. This means that constants and constant expressions were not supported. That is, `1 + 1` was allowed, but `1 + SOME_CONST` was not.

Backed Cases have an additional read-only property, `value`, which is the value specified in the definition.

`<?php
print Suit::Clubs->value;
// Prints "C"
?>`

In order to enforce the `value` property as read-only, a variable cannot be assigned as a reference to it. That is, the following throws an error:

`<?php
$suit = Suit::Clubs;
$ref = &$suit->value;
// Error: Cannot acquire reference to property Suit::$value
?>`

Backed enums implement an internal BackedEnum interface, which exposes two additional methods:

- `from(int|string): self` will take a scalar and return the corresponding Enum Case. If one is not found, it will throw a ValueError. This is mainly useful in cases where the input scalar is trusted and a missing enum value should be considered an application-stopping error.
- `tryFrom(int|string): ?self` will take a scalar and return the corresponding Enum Case. If one is not found, it will return `null`. This is mainly useful in cases where the input scalar is untrusted and the caller wants to implement their own error handling or default-value logic.

The `from()` and `tryFrom()` methods follow standard weak/strong typing rules. In weak typing mode, passing an integer or string is acceptable and the system will coerce the value accordingly. Passing a float will also work and be coerced. In strict typing mode, passing an integer to `from()` on a string-backed enum (or vice versa) will result in a TypeError, as will a float in all circumstances. All other parameter types will throw a TypeError in both modes.

`<?php
$record = get_stuff_from_database($id);
print $record['suit'];
$suit = Suit::from($record['suit']);
// Invalid data throws a ValueError: "X" is not a valid scalar value for enum "Suit"
print $suit->value;
$suit = Suit::tryFrom('A') ?? Suit::Spades;
// Invalid data returns null, so Suit::Spades is used instead.
print $suit->value;
?>`

Manually defining a `from()` or `tryFrom()` method on a Backed Enum will result in a fatal error.

## Enumeration methods

Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces. If an Enum implements an interface, then any type check for that interface will also accept all cases of that Enum.

`<?php
interface Colorful
{
public function color(): string;
}
enum Suit implements Colorful
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
// Fulfills the interface contract.
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
// Not part of an interface; that's fine.
public function shape(): string
{
return "Rectangle";
}
}
function paint(Colorful $c)
{
/* ... */
}
paint(Suit::Clubs); // Works
print Suit::Diamonds->shape(); // prints "Rectangle"
?>`

In this example, all four instances of `Suit` have two methods, `color()` and `shape()`. As far as calling code and type checks are concerned, they behave exactly the same as any other object instance.

On a Backed Enum, the interface declaration goes after the backing type declaration.

`<?php
interface Colorful
{
public function color(): string;
}
enum Suit: string implements Colorful
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
// Fulfills the interface contract.
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>`

Inside a method, the `$this` variable is defined and refers to the Case instance.

Methods may be arbitrarily complex, but in practice will usually return a static value or match on `$this` to provide different results for different cases.

Note that in this case it would be a better data modeling practice to also define a `SuitColor` Enum Type with values Red and Black and return that instead. However, that would complicate this example.

The above hierarchy is logically similar to the following class structure (although this is not the actual code that runs):

`<?php
interface Colorful
{
public function color(): string;
}
final class Suit implements UnitEnum, Colorful
{
public const Hearts = new self('Hearts');
public const Diamonds = new self('Diamonds');
public const Clubs = new self('Clubs');
public const Spades = new self('Spades');
private function __construct(public readonly string $name) {}
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
public function shape(): string
{
return "Rectangle";
}
public static function cases(): array
{
// Illegal method, because manually defining a cases() method on an Enum is disallowed.
// See also "Value listing" section.
}
}
?>`

Methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.

## Enumeration static methods

Enumerations may also have static methods. The use for static methods on the enumeration itself is primarily for alternative constructors. E.g.:

`<?php
enum Size
{
case Small;
case Medium;
case Large;
public static function fromLength(int $cm): self
{
return match(true) {
$cm < 50 => self::Small,
$cm < 100 => self::Medium,
default => self::Large,
};
}
}
?>`

Static methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.

## Enumeration constants

Enumerations may include constants, which may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.

An enum constant may refer to an enum case:

`<?php
enum Size
{
case Small;
case Medium;
case Large;
public const Huge = self::Large;
}
?>`

## Traits

Enumerations may leverage traits, which will behave the same as on classes. The caveat is that traits `use`d in an enum must not contain properties. They may only include methods, static methods, and constants. A trait with properties will result in a fatal error.

`<?php
interface Colorful
{
public function color(): string;
}
trait Rectangle
{
public function shape(): string {
return "Rectangle";
}
}
enum Suit implements Colorful
{
use Rectangle;
case Hearts;
case Diamonds;
case Clubs;
case Spades;
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>`

## Enum values in constant expressions

Because cases are represented as constants on the enum itself, they may be used as static values in most constant expressions: property defaults, static variable defaults, parameter defaults, global and class constant values. They may not be used in other enum case values, but normal constants may refer to an enum case.

However, implicit magic method calls such as ArrayAccess on enums are not allowed in static or constant definitions as we cannot absolutely guarantee that the resulting value is deterministic or that the method invocation is free of side effects. Function calls, method calls, and property access continue to be invalid operations in constant expressions.

`<?php
// This is an entirely legal Enum definition.
enum Direction implements ArrayAccess
{
case Up;
case Down;
public function offsetExists($offset): bool
{
return false;
}
public function offsetGet($offset): mixed
{
return null;
}
public function offsetSet($offset, $value): void
{
throw new Exception();
}
public function offsetUnset($offset): void
{
throw new Exception();
}
}
class Foo
{
// This is allowed.
const DOWN = Direction::Down;
// This is disallowed, as it may not be deterministic.
const UP = Direction::Up['short'];
// Fatal error: Cannot use [] on enums in constant expression
}
// This is entirely legal, because it's not a constant expression.
$x = Direction::Up['short'];
var_dump("\$x is " . var_export($x, true));
$foo = new Foo();
?>`

## Differences from objects

Although Enums are built on classes and objects, they do not support all object-related functionality. In particular, Enum cases are forbidden from having state.

- Constructors and Destructors are forbidden.
- Inheritance is not supported. Enums may not extend or be extended.
- Static or object properties are not allowed.
- Cloning an Enum case is not supported, as cases must be singleton instances.
- Magic methods, except for those listed below, are disallowed.
- Enums must always be declared before they are used.

The following object functionality is available, and behaves just as it does on any other object:

- Public, private, and protected methods.
- Public, private, and protected static methods.
- Public, private, and protected constants.
- Enums may implement any number of interfaces.
- Enums and cases may have attributes attached to them. The `TARGET_CLASS` target filter includes Enums themselves. The `TARGET_CLASS_CONST` target filter includes Enum Cases.
- __call, __callStatic, and __invoke magic methods
- `__CLASS__` and `__FUNCTION__` constants behave as normal

The `::class` magic constant on an Enum type evaluates to the type name including any namespace, exactly the same as an object. The `::class` magic constant on a Case instance also evaluates to the Enum type, as it is an instance of that type.

Additionally, enum cases may not be instantiated directly with `new`, nor with ReflectionClass::newInstanceWithoutConstructor() in reflection. Both will result in an error.

`<?php
$clovers = new Suit();
// Error: Cannot instantiate enum Suit
$horseshoes = (new ReflectionClass(Suit::class))->newInstanceWithoutConstructor()
// Error: Cannot instantiate enum Suit
?>`

## Value listing

Both Pure Enums and Backed Enums implement an internal interface named UnitEnum. `UnitEnum` includes a static method `cases()`. `cases()` returns a packed array of all defined Cases in the order of declaration.

`<?php
Suit::cases();
// Produces: [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades]
?>`

Manually defining a `cases()` method on an Enum will result in a fatal error.

## Serialization

Enumerations are serialized differently from objects. Specifically, they have a new serialization code, `"E"`, that specifies the name of the enum case. The deserialization routine is then able to use that to set a variable to the existing singleton value. That ensures that:

`<?php
Suit::Hearts === unserialize(serialize(Suit::Hearts));
print serialize(Suit::Hearts);
// E:11:"Suit:Hearts";
?>`

On deserialization, if an enum and case cannot be found to match a serialized value a warning will be issued and `false` returned.

If a Pure Enum is serialized to JSON, an error will be thrown. If a Backed Enum is serialized to JSON, it will be represented by its scalar value only, in the appropriate type. The behavior of both may be overridden by implementing JsonSerializable.

For print_r(), the output of an enum case is slightly different from objects to minimize confusion.

`<?php
enum Foo {
case Bar;
}
enum Baz: int {
case Beep = 5;
}
print_r(Foo::Bar);
print_r(Baz::Beep);
/* Produces
Foo Enum (
[name] => Bar
)
Baz Enum:int {
[name] => Beep
[value] => 5
}
*/
?>`

## Why enums aren't extendable

Classes have contracts on their methods:

`<?php
class A {}
class B extends A {}
function foo(A $a) {}
function bar(B $b) {
foo($b);
}
?>`

This code is type-safe, as B follows the contract of A, and through the magic of co/contra-variance, any expectation one may have of the methods will be preserved, exceptions excepted.

Enums have contracts on their cases, not methods:

`<?php
enum ErrorCode {
case SOMETHING_BROKE;
}
function quux(ErrorCode $errorCode)
{
// When written, this code appears to cover all cases
match ($errorCode) {
ErrorCode::SOMETHING_BROKE => true,
};
}
?>`

The match statement in the function `quux` can be static analyzed to cover all of the cases in ErrorCode.

But imagine it was allowed to extend enums:

`<?php
// Thought experiment code where enums are not final.
// Note, this won't actually work in PHP.
enum MoreErrorCode extends ErrorCode {
case PEBKAC;
}
function fot(MoreErrorCode $errorCode) {
quux($errorCode);
}
fot(MoreErrorCode::PEBKAC);
?>`

Under normal inheritance rules, a class that extends another will pass the type check.

The problem would be that the match statement in `quux()` no longer covers all the cases. Because it doesn't know about `MoreErrorCode::PEBKAC` the match will throw an exception.

Because of this enums are final and can't be extended.

## Examples

Example #1 Basic limited values

`<?php
enum SortOrder
{
case Asc;
case Desc;
}
function query($fields, $filter, SortOrder $order = SortOrder::Asc)
{
/* ... */
}
?>`

The `query()` function can now proceed safe in the knowledge that `$order` is guaranteed to be either `SortOrder::Asc` or `SortOrder::Desc`. Any other value would have resulted in a TypeError, so no further error checking or testing is needed.

Example #2 Advanced exclusive values

`<?php
enum UserStatus: string
{
case Pending = 'P';
case Active = 'A';
case Suspended = 'S';
case CanceledByUser = 'C';
public function label(): string
{
return match($this) {
self::Pending => 'Pending',
self::Active => 'Active',
self::Suspended => 'Suspended',
self::CanceledByUser => 'Canceled by user',
};
}
}
?>`

In this example, a user's status may be one of, and exclusively, `UserStatus::Pending`, `UserStatus::Active`, `UserStatus::Suspended`, or `UserStatus::CanceledByUser`. A function can type a parameter against `UserStatus` and then only accept those four values, period.

All four values have a `label()` method, which returns a human-readable string. That string is independent of the "machine name" scalar equivalent string, which can be used in, for example, a database field or an HTML select box.

`<?php
foreach (UserStatus::cases() as $case) {
printf('<option value="%s">%s</option>\n', $case->value, $case->label());
}
?>`

# Errors

## Table of Contents

- Basics
- Errors in PHP 7

## Introduction

Sadly, no matter how careful we are when writing our code, errors are a fact of life. PHP will report errors, warnings and notices for many common coding and runtime problems, and knowing how to detect and handle these errors will make debugging much easier.

## Basics

PHP reports errors in response to a number of internal error conditions. These may be used to signal a number of different conditions, and can be displayed and/or logged as required.

Every error that PHP generates includes a type. A list of these error types is available, along with a short description of their behaviour and how they can be caused.

### Handling errors with PHP

If no error handler is set, then PHP will handle any errors that occur according to its configuration. Which errors are reported and which are ignored is controlled by the `error_reporting` php.ini directive, or at runtime by calling error_reporting(). It is strongly recommended that the configuration directive be set, however, as some errors can occur before execution of your script begins.

In a development environment, you should always set `error_reporting` to `E_ALL`, as you need to be aware of and fix the issues raised by PHP. In production, you may wish to set this to a less verbose level such as `E_ALL & ~E_NOTICE & ~E_DEPRECATED`, but in many cases `E_ALL` is also appropriate, as it may provide early warning of potential issues.

What PHP does with these errors depends on two further php.ini directives. `display_errors` controls whether the error is shown as part of the script's output. This should always be disabled in a production environment, as it can include confidential information such as database passwords, but is often useful to enable in development, as it ensures immediate reporting of issues.

In addition to displaying errors, PHP can log errors when the `log_errors` directive is enabled. This will log any errors to the file or syslog defined by `error_log`. This can be extremely useful in a production environment, as you can log errors that occur and then generate reports based on those errors.

### User error handlers

If PHP's default error handling is inadequate, you can also handle many types of error with your own custom error handler by installing it with set_error_handler(). While some error types cannot be handled this way, those that can be handled can then be handled in the way that your script sees fit: for example, this can be used to show a custom error page to the user and then report more directly than via a log, such as by sending an e-mail.

## Errors in PHP 7

PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.

As with normal exceptions, these Error exceptions will bubble up until they reach the first matching `catch` block. If there are no matching blocks, then any default exception handler installed with set_exception_handler() will be called, and if there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.

As the Error hierarchy does not inherit from Exception, code that uses `catch (Exception $e) { ... }` blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a `catch (Error $e) { ... }` block or a set_exception_handler() handler is required.

### Error hierarchy

- Throwable
  - Error
    - ArithmeticError
      - DivisionByZeroError
    - AssertionError
    - CompileError
      - ParseError
    - TypeError
      - ArgumentCountError
    - ValueError
    - UnhandledMatchError
    - FiberError
    - RequestParseBodyException
  - Exception
    - ...

# Exceptions

## Table of Contents

- Extending Exceptions

PHP has an exception model similar to that of other programming languages. An exception can be `throw`n, and caught ("`catch`ed") 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` or `finally` block.

If an exception is thrown and its current function scope has no `catch` block, the exception will "bubble up" the call stack to the calling function until it finds a matching `catch` block. All `finally` blocks it encounters along the way will be executed. If the call stack is unwound all the way to the global scope without encountering a matching `catch` block, the program will terminate with a fatal error unless a global exception handler has been set.

The thrown object must be an `instanceof` Throwable. Trying to throw an object that is not will result in a PHP Fatal Error.

As of PHP 8.0.0, the `throw` keyword is an expression and may be used in any expression context. In prior versions it was a statement and was required to be on its own line.

## `catch`

A `catch` block defines how to respond to a thrown exception. A `catch` block defines one or more types of exception or error it can handle, and optionally a variable to which to assign the exception. (The variable was required prior to PHP 8.0.0.) The first `catch` block a thrown exception or error encounters that matches the type of the thrown object will handle the object.

Multiple `catch` blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the `try` block) will continue after that last `catch` block defined in sequence. Exceptions can be `throw`n (or re-thrown) within a `catch` block. If not, execution will continue after the `catch` block that was triggered.

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

As of PHP 7.1.0, a `catch` block may specify multiple exceptions using the pipe (`|`) character. This is useful for when different exceptions from different class hierarchies are handled the same.

As of PHP 8.0.0, the variable name for a caught exception is optional. If not specified, the `catch` block will still execute but will not have access to the thrown object.

## `finally`

A `finally` block may also be specified after or instead of `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.

One notable interaction is between the `finally` block and a `return` statement. If a `return` statement is encountered inside either the `try` or the `catch` blocks, the `finally` block will still be executed. Moreover, the `return` statement is evaluated when encountered, but the result will be returned after the `finally` block is executed. Additionally, if the `finally` block also contains a `return` statement, the value from the `finally` block is returned.

Another notable interaction is between an exception thrown from within a `try` block, and an exception thrown from within a `finally` block. If both blocks throw an exception, then the exception thrown from the `finally` block will be the one that is propagated, and the exception thrown from the `try` block will be used as its previous exception.

## Global exception handler

If an exception is allowed to bubble up to the global scope, it may be caught by a global exception handler if set. The set_exception_handler() function can set a function that will be called in place of a `catch` block if no other block is invoked. The effect is essentially the same as if the entire program were wrapped in a `try`-`catch` block with that function as the `catch`.

## Notes

> Note:

> Internal PHP functions mainly use Error reporting, only modern Object-oriented extensions use exceptions. However, errors can be easily translated to exceptions with ErrorException. This technique only works with non-fatal errors, however.

> Example #1 Converting error reporting to exceptions

> `<?php
> function exceptions_error_handler($severity, $message, $filename, $lineno) {
> throw new ErrorException($message, 0, $severity, $filename, $lineno);
> }
> set_error_handler('exceptions_error_handler');
> ?>`

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

## Examples

Example #2 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 #3 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 #4 Interaction between the `finally` block and `return`

`<?php
function test() {
try {
throw new Exception('foo');
} catch (Exception $e) {
return 'catch';
} finally {
return 'finally';
}
}
echo test();
?>`

The above example will output:

    finally

Example #5 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!"

Example #6 Multi catch exception handling

`<?php
class MyException extends Exception { }
class MyOtherException extends Exception { }
class Test {
public function testing() {
try {
throw new MyException();
} catch (MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}
$foo = new Test;
$foo->testing();
?>`

The above example will output:

    string(11) "MyException"

Example #7 Omitting the caught variable

Only permitted in PHP 8.0.0 and later.

`<?php
class SpecificException extends Exception {}
function test() {
throw new SpecificException('Oopsie');
}
try {
test();
} catch (SpecificException) {
print "A SpecificException was thrown, but we don't care about the details.";
}
?>`

The above example will output:

    A SpecificException was thrown, but we don't care about the details.

Example #8 Throw as an expression

Only permitted in PHP 8.0.0 and later.

`<?php
function test() {
do_something_risky() or throw new Exception('It did not work');
}
function do_something_risky() {
return false; // Simulate failure
}
try {
test();
} catch (Exception $e) {
print $e->getMessage();
}
?>`

The above example will output:

    It did not work

Example #9 Exception in try and in finally

`<?php
try {
try {
throw new Exception(message: 'Third', previous: new Exception('Fourth'));
} finally {
throw new Exception(message: 'First', previous: new Exception('Second'));
}
} catch (Exception $e) {
var_dump(
$e->getMessage(),
$e->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getPrevious()->getMessage(),
);
}`

The above example will output:

    string(5) "First"
    string(6) "Second"
    string(5) "Third"
    string(6) "Fourth"

## Extending Exceptions

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 implements Throwable
{
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 = '', $code = 0, ?Throwable $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_ERROR` error.

Example #2 Extending the Exception class

`<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0, ?Throwable $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";
?>`

# Fibers

### Fibers overview

(PHP 8 >= 8.1.0)

Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.

Fibers pause the entire execution stack, so the direct caller of the function does not need to change how it invokes the function.

Execution may be interrupted anywhere in the call stack using Fiber::suspend() (that is, the call to Fiber::suspend() may be in a deeply nested function or not even exist at all).

Unlike stack-less Generators, each Fiber has its own call stack, allowing them to be paused within deeply nested function calls. A function declaring an interruption point (that is, calling Fiber::suspend()) need not change its return type, unlike a function using `yield` which must return a Generator instance.

Fibers can be suspended in any function call, including those called from within the PHP VM, such as functions provided to array_map() or methods called by `foreach` on an Iterator object.

Once suspended, execution of the fiber may be resumed with any value using Fiber::resume() or by throwing an exception into the fiber using Fiber::throw(). The value is returned (or exception thrown) from Fiber::suspend().

> Note: Prior to PHP 8.4.0, switching fibers during the execution of an object destructor was not allowed.

Example #1 Basic usage

`<?php
$fiber = new Fiber(function (): void {
$value = Fiber::suspend('fiber');
echo "Value used to resume fiber: ", $value, PHP_EOL;
});
$value = $fiber->start();
echo "Value from fiber suspending: ", $value, PHP_EOL;
$fiber->resume('test');
?>`

The above example will output:

    Value from fiber suspending: fiber
    Value used to resume fiber: test

# Generators

## Table of Contents

- Generators overview
- Generator syntax
- Comparing generators with Iterator objects

## Generators overview

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

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 offers a convenient way to provide data to `foreach` loops without having to build an array in memory ahead of time, which may cause the program to exceed a memory limit or require a considerable amount of processing time to generate. Instead, a generator function can be used, 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. Like with iterators, random data access is not possible.

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 positive');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be negative');
}
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

### Generator objects

When a generator function is called, a new object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.

## Generator syntax

A generator function looks just like a normal function, except that instead of returning a value, a generator `yield`s as many values as it needs to. Any function containing `yield` is a generator function.

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 object's iteration methods 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 can simply return, and the calling code continues just as if an array has run out of values.

> Note:

> A generator can return values, which can be retrieved using Generator::getReturn().

### yield keyword

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.

#### Yielding values with keys

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

#### Yielding null values

Yield can be called without an argument to yield a `null` value with an automatic key.

Example #3 Yielding `null`s

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

#### Yielding by reference

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

#### Generator delegation via yield from

Generator delegation allows you to yield values from another generator, Traversable object, or array by using the yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.

If a generator is used with yield from, the yield from expression will also return any value returned by the inner generator.

Caution

# Storing into an array (e.g. with iterator_to_array())

yield from does not reset the keys. It preserves the keys returned by the Traversable object, or array. Thus some values may share a common key with another yield or yield from, which, upon insertion into an array, will overwrite former values with that key.

A common case where this matters is iterator_to_array() returning a keyed array by default, leading to possibly unexpected results. iterator_to_array() has a second parameter `preserve_keys` which can be set to `false` to collect all the values while ignoring the keys returned by the Generator.

Example #5 yield from with iterator_to_array()

`<?php
function inner() {
yield 1; // key 0
yield 2; // key 1
yield 3; // key 2
}
function gen() {
yield 0; // key 0
yield from inner(); // keys 0-2
yield 4; // key 1
}
// pass false as second parameter to get an array [0, 1, 2, 3, 4]
var_dump(iterator_to_array(gen()));
?>`

The above example will output:

    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(4)
      [2]=>
      int(3)
    }

Example #6 Basic use of yield from

`<?php
function count_to_ten() {
yield 1;
yield 2;
yield from [3, 4];
yield from new ArrayIterator([5, 6]);
yield from seven_eight();
yield 9;
yield 10;
}
function seven_eight() {
yield 7;
yield from eight();
}
function eight() {
yield 8;
}
foreach (count_to_ten() as $num) {
echo "$num ";
}
?>`

The above example will output:

    1 2 3 4 5 6 7 8 9 10

Example #7 yield from and return values

`<?php
function count_to_ten() {
yield 1;
yield 2;
yield from [3, 4];
yield from new ArrayIterator([5, 6]);
yield from seven_eight();
return yield from nine_ten();
}
function seven_eight() {
yield 7;
yield from eight();
}
function eight() {
yield 8;
}
function nine_ten() {
yield 9;
return 10;
}
$gen = count_to_ten();
foreach ($gen as $num) {
echo "$num ";
}
echo $gen->getReturn();
?>`

The above example will output:

    1 2 3 4 5 6 7 8 9 10

## Comparing generators with Iterator objects

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 be rebuilt by calling the generator function again.

### See Also

- Object Iteration

# Attributes

## Table of Contents

- Attributes overview
- Attribute syntax
- Reading Attributes with the Reflection API
- Declaring Attribute Classes

## Attributes overview

(PHP 8)

PHP attributes provide structured, machine-readable metadata for classes, methods, functions, parameters, properties, and constants. They can be inspected at runtime via the Reflection API, enabling dynamic behavior without modifying code. Attributes provide a declarative way to annotate code with metadata.

Attributes enable the decoupling of a feature's implementation from its usage. While interfaces define structure by enforcing methods, attributes provide metadata across multiple elements, including methods, functions, properties, and constants. Unlike interfaces, which enforce method implementations, attributes annotate code without altering its structure.

Attributes can complement or replace optional interface methods by providing metadata instead of enforced structure. Consider an `ActionHandler` interface that represents an operation in an application. Some implementations may require a setup step while others do not. Instead of forcing all classes implementing `ActionHandler` to define a `setUp()` method, an attribute can indicate setup requirements. This approach increases flexibility, allowing attributes to be applied multiple times when necessary.

Example #1 Implementing optional methods of an interface with Attributes

`<?php
interface ActionHandler
{
public function execute();
}
#[Attribute]
class SetUp {}
class CopyFile implements ActionHandler
{
public string $fileName;
public string $targetDirectory;
#[SetUp]
public function fileExists()
{
if (!file_exists($this->fileName)) {
throw new RuntimeException("File does not exist");
}
}
#[SetUp]
public function targetDirectoryExists()
{
if (!file_exists($this->targetDirectory)) {
mkdir($this->targetDirectory);
} elseif (!is_dir($this->targetDirectory)) {
throw new RuntimeException("Target directory $this->targetDirectory is not a directory");
}
}
public function execute()
{
copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));
}
}
function executeAction(ActionHandler $actionHandler)
{
$reflection = new ReflectionObject($actionHandler);
foreach ($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(SetUp::class);
if (count($attributes) > 0) {
$methodName = $method->getName();
$actionHandler->$methodName();
}
}
$actionHandler->execute();
}
$copyAction = new CopyFile();
$copyAction->fileName = "/tmp/foo.jpg";
$copyAction->targetDirectory = "/home/user";
executeAction($copyAction);`

## Attribute syntax

Attribute syntax consists of several key components. An attribute declaration starts with `#[` and ends with `]`. Inside, one or more attributes can be listed, separated by commas. The attribute name can be unqualified, qualified, or fully-qualified, as described in Using Namespaces Basics. Arguments to the attribute are optional and enclosed in parentheses `()`. Arguments can only be literal values or constant expressions. Both positional and named argument syntax are supported.

Attribute names and their arguments are resolved to a class, and the arguments are passed to its constructor when an instance of the attribute is requested through the Reflection API. Therefore, it is recommended to introduce a class for each attribute.

Example #1 Attribute Syntax

`<?php
// a.php
namespace MyExample;
use Attribute;
#[Attribute]
class MyAttribute
{
const VALUE = 'value';
private $value;
public function __construct($value = null)
{
$this->value = $value;
}
}
// b.php
namespace Another;
use MyExample\MyAttribute;
#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}
#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}`

## Reading Attributes with the Reflection API

To access attributes from classes, methods, functions, parameters, properties, and class constants, use the getAttributes() method provided by the Reflection API. This method returns an array of ReflectionAttribute instances. These instances can be queried for the attribute name, arguments, and can be used to instantiate an instance of the represented attribute.

Separating the reflected attribute representation from its actual instance provides more control over error handling, such as missing attribute classes, mistyped arguments, or missing values. Objects of the attribute class are instantiated only after calling ReflectionAttribute::newInstance(), ensuring that argument validation occurs at that point.

Example #1 Reading Attributes using Reflection API

`<?php
#[Attribute]
class MyAttribute
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
#[MyAttribute(value: 1234)]
class Thing
{
}
function dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpAttributeData(new ReflectionClass(Thing::class));
/*
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
*/`

Instead of iterating over all attributes on the reflection instance, you can retrieve only those of a specific attribute class by passing the attribute class name as an argument.

Example #2 Reading Specific Attributes using Reflection API

`<?php
function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpMyAttributeData(new ReflectionClass(Thing::class));`

## Declaring Attribute Classes

It is recommended to define a separate class for each attribute. In the simplest case, an empty class with the `#[Attribute]` declaration is sufficient. The attribute can be imported from the global namespace using a `use` statement.

Example #1 Simple Attribute Class

`<?php
namespace Example;
use Attribute;
#[Attribute]
class MyAttribute
{
}`

To restrict the types of declarations an attribute can be applied to, pass a bitmask as the first argument to the `#[Attribute]` declaration.

Example #2 Using target specification to restrict where attributes can be used

`<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class MyAttribute
{
}`

Declaring MyAttribute on another type will now throw an exception during the call to ReflectionAttribute::newInstance()

The following targets can be specified:

- `Attribute::TARGET_CLASS`
- `Attribute::TARGET_FUNCTION`
- `Attribute::TARGET_METHOD`
- `Attribute::TARGET_PROPERTY`
- `Attribute::TARGET_CLASS_CONSTANT`
- `Attribute::TARGET_PARAMETER`
- `Attribute::TARGET_ALL`

By default, an attribute can only be used once per declaration. To allow an attribute to be repeatable, specify it in the bitmask of the `#[Attribute]` declaration using the `Attribute::IS_REPEATABLE` flag.

Example #3 Using IS_REPEATABLE to allow attribute on a declaration multiple times

`<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::IS_REPEATABLE)]
class MyAttribute
{
}`

# References Explained

## Table of Contents

- What References Are
- What References Do
- What References Are Not
- Passing by Reference
- Returning References
- Unsetting References
- Spotting References

## What References Are

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.

## What References Do

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.

### Assign By Reference

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;
?>`
it means that $a and $b point to the same content.

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

`<?php
$foo =& find_var($bar);
?>`

Using the same syntax with a function that does not return by reference will give an error, as will using it with the result of the new operator. Although objects are passed around as pointers, these are not the same as references, as explained under Objects and references.

Warning

If you assign a reference to a variable declared `global` inside a function, the reference will be visible only inside the function. You can avoid this by using the $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'
?>`
Think about `global $var;` as a shortcut to `$var =& $GLOBALS['var'];`. Thus assigning another reference to `$var` only changes the local variable's reference.

> 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! */
?>`
In other words, the reference behavior of arrays is defined in an element-by-element basis; the reference behavior of individual elements is dissociated from the reference status of the array container.

### Pass By 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);
?>`
will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. For more information on this, read the passing by reference section.

### Return By Reference

The third thing references can do is return by reference.

## What References Are Not

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.

## Passing by Reference

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.

The following things can be passed by reference:

- Variables, i.e. `foo($a)`

- References returned from functions, i.e.:

  `<?php
  function foo(&$var)
  {
  $var++;
  }
  function &bar()
  {
  $a = 5;
  return $a;
  }
  foo(bar());
  ?>`
  See more about returning by reference.

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 a notice
foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
class Foobar {}
foo(new Foobar()) // Produces a notice as of PHP 7.0.7
// Notice: Only variables should be passed by reference
?>`

## Returning References

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
?>`
In this example, the property of the object returned by the getValue function would be set, not the copy, as it would be without using reference syntax.

> Note: Unlike parameter passing, here you have to use `&` in both places - to indicate that you 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.

To use the returned reference, you must use reference assignment:

`<?php
function &collector()
{
static $collection = array();
return $collection;
}
$collection = &collector();
// Now the $collection is a referenced variable that references the static array inside the function
$collection[] = 'foo';
print_r(collector());
// Array
// (
// [0] => foo
// )
?>`

> Note: If the assignment is done without the `&` symbol, e.g. `$collection = collector();`, the $collection variable will receive a copy of the value, not the reference returned by the function.

To pass the returned reference to another function expecting a reference you can use this syntax:
`<?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.

## Unsetting References

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);
?>`
won't unset $b, just $a.

Again, it might be useful to think about this as analogous to the Unix unlink call.

## Spotting References

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:

### global References

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.

# Predefined Variables

PHP provides predefined variables that represent external variables, built-in environment variables, and other information about the execution environment, such as the number and values of the arguments passed to the script in the CLI environment.

# Superglobals

Superglobals — Built-in variables that are always available in all scopes

### Description

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:

- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_FILES
- $_COOKIE
- $_SESSION
- $_REQUEST
- $_ENV

### Notes

> 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: Variable variables

> Superglobals cannot be used as variable variables inside functions or class methods.

### See Also

- variable scope
- The variables_order directive
- The filter extension

# $GLOBALS

(PHP 4, PHP 5, PHP 7, PHP 8)

$GLOBALS — References all variables available in global scope

### Description

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.

### Examples

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

Warning

As of PHP 8.1.0, write access to the entire $GLOBALS array is no longer supported:

Example #2 writing entire $GLOBALS will result in error.

`<?php
// Generates compile-time error:
$GLOBALS = [];
$GLOBALS += [];
$GLOBALS =& $x;
$x =& $GLOBALS;
unset($GLOBALS);
array_pop($GLOBALS);
// ...and any other write/read-write operation on $GLOBALS
?>`

### Notes

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

> Note:

> As of PHP 8.1.0, $GLOBALS is now a read-only copy of the global symbol table. That is, global variables cannot be modified via its copy. Previously, $GLOBALS array is excluded from the usual by-value behavior of PHP arrays and global variables can be modified via its copy.

> `<?php
> // Before PHP 8.1.0
> $a = 1;
> $globals = $GLOBALS; // Ostensibly by-value copy
> $globals['a'] = 2;
> var_dump($a); // int(2)
> // As of PHP 8.1.0
> // this no longer modifies $a. The previous behavior violated by-value semantics.
> $globals = $GLOBALS;
> $globals['a'] = 1;
> // To restore the previous behavior, iterate its copy and assign each property back to $GLOBALS.
> foreach ($globals as $key => $value) {
> $GLOBALS[$key] = $value;
> }
> ?>`

# $_SERVER

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_SERVER — Server and execution environment information

### Description

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the » CGI/1.1 specification, and are likely to be defined.

> Note: When running PHP on the command line most of these entries will not be available or have any meaning.

In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named `HTTP_` followed by the header name, capitalized and with underscores instead of hyphens. For example, the `Accept-Language` header would be available as `$_SERVER['HTTP_ACCEPT_LANGUAGE']`.

### Indices

'PHP_SELF'
  The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name.
'argv'
  Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
  Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
  What revision of the CGI specification the server is using; e.g. `'CGI/1.1'`.
'SERVER_ADDR'
  The IP address of the server under which the current script is executing.
'SERVER_NAME'
  The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

  > Note: Under Apache 2, `UseCanonicalName = On` and `ServerName` must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

'SERVER_SOFTWARE'
  Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
  Name and revision of the information protocol via which the page was requested; e.g. `'HTTP/1.0'`;
'REQUEST_METHOD'
  Which request method was used to access the page; e.g. `'GET'`, `'HEAD'`, `'POST'`, `'PUT'`.

  > Note:

  > PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was `HEAD`.

'REQUEST_TIME'
  The timestamp when PHP started processing the request.
'REQUEST_TIME_FLOAT'
  The timestamp when PHP started processing the request, with microsecond precision.
'QUERY_STRING'
  The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
  The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTPS'
  Set to a non-empty value if the script was queried through the HTTPS protocol.
'REMOTE_ADDR'
  The IP address from which the user is viewing the current page.
'REMOTE_HOST'
  The Host name from which the user is viewing the current page. The reverse dns lookup is based on the REMOTE_ADDR of the user.

  > Note: The web server must be configured to create this variable. For example in Apache `HostnameLookups On` must be set inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
  The port being used on the user's machine to communicate with the web server.
'REMOTE_USER'
  The authenticated user.
'REDIRECT_REMOTE_USER'
  The authenticated user if the request is internally redirected.
'SCRIPT_FILENAME'

  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.

'SERVER_ADMIN'
  The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_PORT'
  The port on the server machine being used by the web server for communication. For default setups, this will be `'80'`; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

  > Note: Under Apache 2, `UseCanonicalName = On`, as well as `UseCanonicalPhysicalPort = On` must be set 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.

'SERVER_SIGNATURE'
  String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
  Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

  > Note: Apache 2 users may use `AcceptPathInfo = On` inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
  Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
  The URI which was given in order to access this page; for instance, '`/index.html`'.
'PHP_AUTH_DIGEST'
  When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
  When doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
  When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
  When doing HTTP authentication this variable is set to the authentication type.
'PATH_INFO'
  Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain `/some/stuff`.
'ORIG_PATH_INFO'
  Original version of 'PATH_INFO' before processed by PHP.

### Examples

Example #1 $_SERVER example

`<?php
echo $_SERVER['SERVER_NAME'];
?>`

The above example will output something similar to:

    www.example.com

### Notes

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

### See Also

- The filter extension

# $_GET

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_GET — Query string variables

### Description

An associative array of variables passed to the current script via the URL parameters (also known as the query string). Note that this array is populated whenever a query string is present, regardless of the HTTP request method.

### Examples

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!

### Notes

> 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 values in $_GET are automatically passed through urldecode().

### See Also

- Handling external variables
- The filter extension

# $_POST

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_POST — Form data from HTTP POST requests

### Description

An associative array of variables passed to the current script via the HTTP POST method when using `application/x-www-form-urlencoded` or `multipart/form-data` as the HTTP Content-Type in the request.

### Examples

Example #1 $_POST example

`<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>`

Assuming the user sent a POST request with `name=Hannes` in the body.

The above example will output something similar to:

    Hello Hannes!

### Notes

> 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: To read POST data sent with other content types (e.g. `application/json` or `application/xml`) php://input must be used. Unlike $_POST, which only works with `application/x-www-form-urlencoded` and `multipart/form-data`, php://input provides direct access to the raw data from the body of the request.

### See Also

- Handling external variables
- The filter extension

# $_FILES

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_FILES — HTTP File Upload variables

### Description

An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section.

### Notes

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

### See Also

- move_uploaded_file() - Moves an uploaded file to a new location
- Handling File Uploads

# $_REQUEST

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_REQUEST — HTTP Request variables

### Description

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

### Notes

> 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 request_order, and variables_order configuration directives.

### See Also

- Handling external variables
- The filter extension

# $_SESSION

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_SESSION — Session variables

### Description

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

### Notes

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

### See Also

- session_start() - Start new or resume existing session

# $_ENV

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_ENV — Environment variables

### Description

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.

### Examples

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!

### Notes

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

### See Also

- getenv() - Gets the value of a single or all environment variables
- The filter extension

# $_COOKIE

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_COOKIE — HTTP Cookies

### Description

An associative array of variables passed to the current script via HTTP Cookies.

### Examples

Example #1 $_COOKIE example

`<?php
echo 'Hello ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>`

Assuming the "name" cookie has been set earlier

The above example will output something similar to:

    Hello Hannes!

### Notes

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

### See Also

- setcookie() - Send a cookie
- Handling external variables
- The filter extension

# $php_errormsg

(PHP 4, PHP 5, PHP 7)

$php_errormsg — The previous error message

Warning

This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.

Use error_get_last() instead.

### Description

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

Warning

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns `false`.

### Changelog

Version | Description
--- | ---
8.0.0 | Directive track_errors which caused $php_errormsg to be available has been removed.
7.2.0 | Directive track_errors which caused $php_errormsg to be available has been deprecated.

### Examples

Example #1 $php_errormsg example

`<?php
@strpos();
echo $php_errormsg;
?>`

The above example will output something similar to:

    Wrong parameter count for strpos()

### See Also

- error_get_last() - Get the last occurred error

# $http_response_header

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

$http_response_header — HTTP response headers

Warning

This feature has been DEPRECATED as of PHP 8.5.0. Relying on this feature is highly discouraged.

Use http_get_last_response_headers() instead.

### Description

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.

### Examples

Example #1 $http_response_header example

`<?php
function get_contents() {
file_get_contents("http://example.com");
var_dump($http_response_header); // variable is populated in the local scope
}
get_contents();
var_dump($http_response_header); // a call to get_contents() does not populate the variable outside the function scope
?>`

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

    Warning: Undefined variable $http_response_header
    NULL

### See Also

- http_get_last_response_headers() - Retrieve last HTTP response headers
- http_clear_last_response_headers() - Clears the stored HTTP response headers

# $argc

(PHP 4, PHP 5, PHP 7, PHP 8)

$argc — The number of arguments passed to script

### Description

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.

### Examples

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)

### Notes

> Note:

> This is also available as $_SERVER['argc'].

### See Also

- getopt() - Gets options from the command line argument list
- $argv

# $argv

(PHP 4, PHP 5, PHP 7, PHP 8)

$argv — Array of arguments passed to script

### Description

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.

Warning

To test if a script is being run from the command line, php_sapi_name() should be used instead of checking whether $argv or $_SERVER['argv'] is set.

### Examples

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

### Notes

> Note:

> This is also available as $_SERVER['argv'].

### See Also

- getopt() - Gets options from the command line argument list
- $argc

## Table of Contents

- Superglobals — Built-in variables that are always available in all scopes
- $GLOBALS — References all variables available in global scope
- $_SERVER — Server and execution environment information
- $_GET — Query string variables
- $_POST — Form data from HTTP POST requests
- $_FILES — HTTP File Upload variables
- $_REQUEST — HTTP Request variables
- $_SESSION — Session variables
- $_ENV — Environment variables
- $_COOKIE — HTTP Cookies
- $php_errormsg — The previous error message
- $http_response_header — HTTP response headers
- $argc — The number of arguments passed to script
- $argv — Array of arguments passed to script

# Predefined Exceptions

## Table of Contents

- Exception
- ErrorException
- ClosedGeneratorException
- Error
- ArgumentCountError
- ArithmeticError
- AssertionError
- DivisionByZeroError
- CompileError
- ParseError
- TypeError
- ValueError
- UnhandledMatchError
- FiberError
- RequestParseBodyException

See also the SPL Exceptions.

# Exception

(PHP 5, PHP 7, PHP 8)

## Introduction

Exception is the base class for all user exceptions.

## Class synopsis

class Exception implements Throwable {
/* Properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
public __construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public getMessage(): string
final public getPrevious(): ?Throwable
final public getCode(): int
final public getFile(): string
final public getLine(): int
final public getTrace(): array
final public getTraceAsString(): string
public __toString(): string
private __clone(): void
}

## Properties

message

  The exception message

code

  The exception code

file

  The filename where the exception was created

line

  The line where the exception was created

previous

  The previously thrown exception

string

  The string representation of the stack trace

trace

  The stack trace as an array

# Exception::__construct

(PHP 5, PHP 7, PHP 8)

Exception::__construct — Construct the exception

### Description

public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)

Constructs the Exception.

### Parameters

`message`

  The Exception message to throw.

`code`

  The Exception code.

`previous`

  The previous exception used for the exception chaining.

> Note: Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set.

### Notes

> Note:

> The `message` is NOT binary safe.

# Exception::getMessage

(PHP 5, PHP 7, PHP 8)

Exception::getMessage — Gets the Exception message

### Description

final public Exception::getMessage(): string

Returns the Exception message.

### Parameters

This function has no parameters.

### Return Values

Returns the Exception message as a string.

### Examples

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

### See Also

- Throwable::getMessage() - Gets the message

# Exception::getPrevious

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Exception::getPrevious — Returns previous Throwable

### Description

final public Exception::getPrevious(): ?Throwable

Returns previous Throwable (which had been passed as the third parameter of Exception::__construct()).

### Parameters

This function has no parameters.

### Return Values

Returns the previous Throwable if available or `null` otherwise.

### Examples

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]

### See Also

- Throwable::getPrevious() - Returns the previous Throwable

# Exception::getCode

(PHP 5, PHP 7, PHP 8)

Exception::getCode — Gets the Exception code

### Description

final public Exception::getCode(): int

Returns the Exception code.

### Parameters

This function has no parameters.

### Return Values

Returns the exception code as int in Exception but possibly as other type in Exception descendants (for example as string in PDOException).

### Examples

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

### See Also

- Throwable::getCode() - Gets the exception code

# Exception::getFile

(PHP 5, PHP 7, PHP 8)

Exception::getFile — Gets the file in which the exception was created

### Description

final public Exception::getFile(): string

Get the name of the file in which the exception was created.

### Parameters

This function has no parameters.

### Return Values

Returns the filename in which the exception was created.

### Examples

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

### See Also

- Throwable::getFile() - Gets the file in which the object was created

# Exception::getLine

(PHP 5, PHP 7, PHP 8)

Exception::getLine — Gets the line in which the exception was created

### Description

final public Exception::getLine(): int

Get line number where the exception was created.

### Parameters

This function has no parameters.

### Return Values

Returns the line number where the exception was created.

### Examples

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

### See Also

- Throwable::getLine() - Gets the line on which the object was instantiated

# Exception::getTrace

(PHP 5, PHP 7, PHP 8)

Exception::getTrace — Gets the stack trace

### Description

final public Exception::getTrace(): array

Returns the Exception stack trace.

### Parameters

This function has no parameters.

### Return Values

Returns the Exception stack trace as an array.

### Examples

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) {
        }
      }
    }

### See Also

- Throwable::getTrace() - Gets the stack trace

# Exception::getTraceAsString

(PHP 5, PHP 7, PHP 8)

Exception::getTraceAsString — Gets the stack trace as a string

### Description

final public Exception::getTraceAsString(): string

Returns the Exception stack trace as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the Exception stack trace as a string.

### Examples

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}

### See Also

- Throwable::getTraceAsString() - Gets the stack trace as a string

# Exception::__toString

(PHP 5, PHP 7, PHP 8)

Exception::__toString — String representation of the exception

### Description

public Exception::__toString(): string

Returns the string representation of the exception.

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the exception.

### Examples

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}

### See Also

- Throwable::__toString() - Gets a string representation of the thrown object

# Exception::__clone

(PHP 5, PHP 7, PHP 8)

Exception::__clone — Clone the exception

### Description

private Exception::__clone(): void

Exceptions cannot be cloned, and attempting to do so will throw an Error.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

Exceptions are not clonable.

### Changelog

Version | Description
--- | ---
8.1.0 | Exception::__clone() is no longer final.

## Table of Contents

- Exception::__construct — Construct the exception
- Exception::getMessage — Gets the Exception message
- Exception::getPrevious — Returns previous Throwable
- Exception::getCode — Gets the Exception code
- Exception::getFile — Gets the file in which the exception was created
- Exception::getLine — Gets the line in which the exception was created
- Exception::getTrace — Gets the stack trace
- Exception::getTraceAsString — Gets the stack trace as a string
- Exception::__toString — String representation of the exception
- Exception::__clone — Clone the exception

# ErrorException

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

## Introduction

An Error Exception.

## Class synopsis

class ErrorException extends Exception {
/* Properties */
protected int $severity = E_ERROR;
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
public __construct(
string `$message` = "",
int `$code` = 0,
int `$severity` = `E_ERROR`,
?string `$filename` = `null`,
?int `$line` = `null`,
?Throwable `$previous` = `null`
)
final public getSeverity(): int
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

severity

  The severity of the exception

## Examples

Example #1 Use set_error_handler() to change error messages into ErrorException

`<?php
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting.
return;
}
if ($errno === E_DEPRECATED || $errno === E_USER_DEPRECATED) {
// Do not throw an Exception for deprecation warnings as new or unexpected
// deprecations would break the application.
return;
}
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Unserializing broken data triggers a warning which will be turned into an
// ErrorException by the error handler.
unserialize('broken data');
?>`

The above example will output something similar to:

    Fatal error: Uncaught ErrorException: unserialize(): Error at offset 0 of 11 bytes in test.php:16
    Stack trace:
    #0 [internal function]: {closure}(2, 'unserialize(): ...', 'test.php', 16)
    #1 test.php(16): unserialize('broken data')
    #2 {main}
      thrown in test.php on line 16

# ErrorException::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ErrorException::__construct — Constructs the exception

### Description

public ErrorException::__construct(
string `$message` = "",
int `$code` = 0,
int `$severity` = `E_ERROR`,
?string `$filename` = `null`,
?int `$line` = `null`,
?Throwable `$previous` = `null`
)

Constructs the Exception.

### Parameters

`message`

  The Exception message to throw.

`code`

  The Exception code.

`severity`

  The severity level of the exception.

  > Note:

  > While the severity can be any int value, it is intended that the error constants be used.

`filename`

  The filename where the exception is thrown.

`line`

  The line number where the exception is thrown.

`previous`

  The previous exception used for the exception chaining.

### Changelog

Version | Description
--- | ---
8.0.0 | `filename` and `line` are nullable now. Previously, their defaults were `__FILE__` and `__LINE__`, respectively.

# ErrorException::getSeverity

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ErrorException::getSeverity — Gets the exception severity

### Description

final public ErrorException::getSeverity(): int

Returns the severity of the exception.

### Parameters

This function has no parameters.

### Return Values

Returns the severity level of the exception.

### Examples

Example #1 ErrorException::getSeverity() example

`<?php
try {
throw new ErrorException("Exception message", 0, E_USER_ERROR);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
var_dump($e->getSeverity() === E_USER_ERROR);
}
?>`

The above example will output something similar to:

    This exception severity is: 256
    bool(true)

## Table of Contents

- ErrorException::__construct — Constructs the exception
- ErrorException::getSeverity — Gets the exception severity

# The ClosedGeneratorException class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

A ClosedGeneratorException is thrown when trying to retrieve a value from a closed Generator.

## Class synopsis

class ClosedGeneratorException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# Error

(PHP 7, PHP 8)

## Introduction

Error is the base class for all internal PHP errors.

## Class synopsis

class Error implements Throwable {
/* Properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
public __construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public getMessage(): string
final public getPrevious(): ?Throwable
final public getCode(): int
final public getFile(): string
final public getLine(): int
final public getTrace(): array
final public getTraceAsString(): string
public __toString(): string
private __clone(): void
}

## Properties

message

  The error message

code

  The error code

file

  The filename where the error happened

line

  The line where the error happened

previous

  The previously thrown exception

string

  The string representation of the stack trace

trace

  The stack trace as an array

# Error::__construct

(PHP 7, PHP 8)

Error::__construct — Construct the error object

### Description

public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)

Constructs the Error.

### Parameters

`message`

  The error message.

`code`

  The error code.

`previous`

  The previous throwable used for the exception chaining.

### Notes

> Note:

> The `message` is NOT binary safe.

# Error::getMessage

(PHP 7, PHP 8)

Error::getMessage — Gets the error message

### Description

final public Error::getMessage(): string

Returns the error message.

### Parameters

This function has no parameters.

### Return Values

Returns the error message as a string.

### Examples

Example #1 Error::getMessage() example

`<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo $e->getMessage();
}
?>`

The above example will output something similar to:

    Some error message

### See Also

- Throwable::getMessage() - Gets the message

# Error::getPrevious

(PHP 7, PHP 8)

Error::getPrevious — Returns previous Throwable

### Description

final public Error::getPrevious(): ?Throwable

Returns previous Throwable (the third parameter of Error::__construct()).

### Parameters

This function has no parameters.

### Return Values

Returns the previous Throwable if available or `null` otherwise.

### Examples

Example #1 Error::getPrevious() example

Looping over, and printing out, error trace.

`<?php
class MyCustomError extends Error {}
function doStuff() {
try {
throw new InvalidArgumentError("You are doing it wrong!", 112);
} catch(Error $e) {
throw new MyCustomError("Something happened", 911, $e);
}
}
try {
doStuff();
} catch(Error $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) [MyCustomError]
    /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentError]

### See Also

- Throwable::getPrevious() - Returns the previous Throwable

# Error::getCode

(PHP 7, PHP 8)

Error::getCode — Gets the error code

### Description

final public Error::getCode(): int

Returns the error code.

### Parameters

This function has no parameters.

### Return Values

Returns the error code as int

### Examples

Example #1 Error::getCode() example

`<?php
try {
throw new Error("Some error message", 30);
} catch(Error $e) {
echo "The Error code is: " . $e->getCode();
}
?>`

The above example will output something similar to:

    The Error code is: 30

### See Also

- Throwable::getCode() - Gets the exception code

# Error::getFile

(PHP 7, PHP 8)

Error::getFile — Gets the file in which the error occurred

### Description

final public Error::getFile(): string

Get the name of the file the error occurred.

### Parameters

This function has no parameters.

### Return Values

Returns the filename in which the error occurred.

### Examples

Example #1 Error::getFile() example

`<?php
try {
throw new Error;
} catch(Error $e) {
echo $e->getFile();
}
?>`

The above example will output something similar to:

    /home/bjori/tmp/ex.php

### See Also

- Throwable::getFile() - Gets the file in which the object was created

# Error::getLine

(PHP 7, PHP 8)

Error::getLine — Gets the line in which the error occurred

### Description

final public Error::getLine(): int

Get line number where the error occurred.

### Parameters

This function has no parameters.

### Return Values

Returns the line number where the error occurred.

### Examples

Example #1 Error::getLine() example

`<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo "The error was created on line: " . $e->getLine();
}
?>`

The above example will output something similar to:

    The error was created on line: 3

### See Also

- Throwable::getLine() - Gets the line on which the object was instantiated

# Error::getTrace

(PHP 7, PHP 8)

Error::getTrace — Gets the stack trace

### Description

final public Error::getTrace(): array

Returns the stack trace.

### Parameters

This function has no parameters.

### Return Values

Returns the stack trace as an array.

### Examples

Example #1 Error::getTrace() example

`<?php
function test() {
throw new Error;
}
try {
test();
} catch(Error $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) {
        }
      }
    }

### See Also

- Throwable::getTrace() - Gets the stack trace

# Error::getTraceAsString

(PHP 7, PHP 8)

Error::getTraceAsString — Gets the stack trace as a string

### Description

final public Error::getTraceAsString(): string

Returns the stack trace as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the stack trace as a string.

### Examples

Example #1 Error::getTraceAsString() example

`<?php
function test() {
throw new Error;
}
try {
test();
} catch(Error $e) {
echo $e->getTraceAsString();
}
?>`

The above example will output something similar to:

    #0 /home/bjori/tmp/ex.php(7): test()
    #1 {main}

### See Also

- Throwable::getTraceAsString() - Gets the stack trace as a string

# Error::__toString

(PHP 7, PHP 8)

Error::__toString — String representation of the error

### Description

public Error::__toString(): string

Returns the string representation of the error.

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the error.

### Examples

Example #1 Error::__toString() example

`<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo $e;
}
?>`

The above example will output something similar to:

    Error: Some error message in /home/bjori/tmp/ex.php:3
    Stack trace:
    #0 {main}

### See Also

- Throwable::__toString() - Gets a string representation of the thrown object

# Error::__clone

(PHP 7, PHP 8)

Error::__clone — Clone the error

### Description

private Error::__clone(): void

Error can not be cloned, so this method results in fatal error.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

Errors are not clonable.

### Changelog

Version | Description
--- | ---
8.1.0 | Error::__clone() is no longer final.

## Table of Contents

- Error::__construct — Construct the error object
- Error::getMessage — Gets the error message
- Error::getPrevious — Returns previous Throwable
- Error::getCode — Gets the error code
- Error::getFile — Gets the file in which the error occurred
- Error::getLine — Gets the line in which the error occurred
- Error::getTrace — Gets the stack trace
- Error::getTraceAsString — Gets the stack trace as a string
- Error::__toString — String representation of the error
- Error::__clone — Clone the error

# ArgumentCountError

(PHP 7 >= PHP 7.1.0, PHP 8)

## Introduction

ArgumentCountError is thrown when too few arguments are passed to a user-defined function or method.

This error is also thrown when too many arguments are passed to a non-variadic built-in function.

## Class synopsis

class ArgumentCountError extends TypeError {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# ArithmeticError

(PHP 7, PHP 8)

## Introduction

ArithmeticError is thrown when an error occurs while performing mathematical operations. These errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an int.

## Class synopsis

class ArithmeticError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# AssertionError

(PHP 7, PHP 8)

## Introduction

AssertionError is thrown when an assertion made via assert() fails.

## Class synopsis

class AssertionError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# DivisionByZeroError

(PHP 7, PHP 8)

## Introduction

DivisionByZeroError is thrown when an attempt is made to divide a number by zero.

## Class synopsis

class DivisionByZeroError extends ArithmeticError {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# CompileError

(PHP 7 > 7.3.0, PHP 8)

## Introduction

CompileError is thrown for some compilation errors, which formerly issued a fatal error.

## Class synopsis

class CompileError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# ParseError

(PHP 7, PHP 8)

## Introduction

ParseError is thrown when an error occurs while parsing PHP code, such as when eval() is called.

> Note: ParseError extends CompileError as of PHP 7.3.0. Formerly, it extended Error.

## Class synopsis

class ParseError extends CompileError {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# TypeError

(PHP 7, PHP 8)

## Introduction

A TypeError may be thrown when:

- The value being set for a class property does not match the property's corresponding declared type.
- The argument type being passed to a function does not match its corresponding declared parameter type.
- A value being returned from a function does not match the declared function return type.

## Class synopsis

class TypeError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

## Changelog

Version | Description
--- | ---
7.1.0 | In strict mode, passing an incorrect number of arguments to a built-in PHP function no longer results in a generic TypeError. Instead, a more specific ArgumentCountError, which extends TypeError, is thrown.

# ValueError

(PHP 8)

## Introduction

A ValueError is thrown when the type of an argument is correct but the value of it is incorrect. For example, passing a negative integer when the function expects a positive one, or passing an empty string/array when the function expects it to not be empty.

## Class synopsis

class ValueError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# UnhandledMatchError

(PHP 8)

## Introduction

An UnhandledMatchError is thrown when the subject passed to a match expression is not handled by any arm of the match expression.

## Class synopsis

class UnhandledMatchError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# FiberError

(PHP 8 >= 8.1.0)

## Introduction

FiberError is thrown when an invalid operation is performed on a Fiber.

## Class synopsis

final class FiberError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
public __construct()
/* Inherited methods */
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# FiberError::__construct

(PHP 8 >= 8.1.0)

FiberError::__construct — Constructor to disallow direct instantiation

### Description

public FiberError::__construct()

### Parameters

This function has no parameters.

### Errors/Exceptions

Throws an Error exception when called.

## Table of Contents

- FiberError::__construct — Constructor to disallow direct instantiation

# RequestParseBodyException

(PHP 8 >= 8.4.0)

## Introduction

A RequestParseBodyException is thrown in request_parse_body() when the request body is invalid, according to the `Content-Type` header.

## Class synopsis

class RequestParseBodyException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# Predefined Interfaces and Classes

## Table of Contents

- Traversable
- Iterator
- IteratorAggregate
- InternalIterator
- Throwable
- Countable
- ArrayAccess
- Serializable
- Closure
- stdClass
- Generator
- Fiber
- WeakReference
- WeakMap
- Stringable
- UnitEnum
- BackedEnum
- SensitiveParameterValue
- __PHP_Incomplete_Class

See also the SPL Interfaces and reserved classes.

# The Traversable interface

(PHP 5, PHP 7, PHP 8)

## Introduction

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.

## Interface synopsis

interface Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.

## Changelog

Version | Description
--- | ---
7.4.0 | The Traversable interface can now be implemented by abstract classes. Extending classes must implement Iterator or IteratorAggregate.

## Notes

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

> Prior to PHP 7.4.0, this internal engine interface couldn't be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

# The Iterator interface

(PHP 5, PHP 7, PHP 8)

## Introduction

Interface for external iterators or objects that can be iterated themselves internally.

## Interface synopsis

interface Iterator extends Traversable {
/* Methods */
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

## Predefined iterators

PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.

## Examples

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;
}
public function rewind(): void {
var_dump(__METHOD__);
$this->position = 0;
}
#[\ReturnTypeWillChange]
public function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
#[\ReturnTypeWillChange]
public function key() {
var_dump(__METHOD__);
return $this->position;
}
public function next(): void {
var_dump(__METHOD__);
++$this->position;
}
public function valid(): bool {
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"

## See Also

See also object iteration.

# Iterator::current

(PHP 5, PHP 7, PHP 8)

Iterator::current — Return the current element

### Description

public Iterator::current(): mixed

Returns the current element.

### Parameters

This function has no parameters.

### Return Values

Can return any type.

# Iterator::key

(PHP 5, PHP 7, PHP 8)

Iterator::key — Return the key of the current element

### Description

public Iterator::key(): mixed

Returns the key of the current element.

### Parameters

This function has no parameters.

### Return Values

Returns scalar on success, or `null` on failure.

### Errors/Exceptions

Issues `E_NOTICE` on failure.

# Iterator::next

(PHP 5, PHP 7, PHP 8)

Iterator::next — Move forward to next element

### Description

public Iterator::next(): void

Moves the current position to the next element.

> Note:

> This method is called after each `foreach` loop.

### Parameters

This function has no parameters.

### Return Values

Any returned value is ignored.

# Iterator::rewind

(PHP 5, PHP 7, PHP 8)

Iterator::rewind — Rewind the Iterator to the first element

### Description

public Iterator::rewind(): void

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.

> As `foreach` always calls rewind() before starting iteration, manually advancing the iterator position (for example via SplFileObject::seek()) will be reset. To iterate without rewinding the iterator, wrap it in a NoRewindIterator.

### Parameters

This function has no parameters.

### Return Values

Any returned value is ignored.

# Iterator::valid

(PHP 5, PHP 7, PHP 8)

Iterator::valid — Checks if current position is valid

### Description

public Iterator::valid(): bool

This method is called after Iterator::rewind() and Iterator::next() to check if the current position is valid.

### Parameters

This function has no parameters.

### Return Values

The return value will be casted to bool and then evaluated. Returns `true` on success or `false` on failure.

## Table of Contents

- Iterator::current — Return the current element
- Iterator::key — Return the key of the current element
- Iterator::next — Move forward to next element
- Iterator::rewind — Rewind the Iterator to the first element
- Iterator::valid — Checks if current position is valid

# The IteratorAggregate interface

(PHP 5, PHP 7, PHP 8)

## Introduction

Interface to create an external Iterator.

## Interface synopsis

interface IteratorAggregate extends Traversable {
/* Methods */
public getIterator(): Traversable
}

## Examples

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 $property4 = "";
public function __construct()
{
$this->property4 = "last property";
}
public function getIterator(): Traversable
{
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"

# IteratorAggregate::getIterator

(PHP 5, PHP 7, PHP 8)

IteratorAggregate::getIterator — Retrieve an external iterator or traversable

### Description

public IteratorAggregate::getIterator(): Traversable

Returns an external iterator or traversable.

### Parameters

This function has no parameters.

### Return Values

An instance of an object implementing Iterator or Traversable

### Errors/Exceptions

Throws an Exception on failure.

## Table of Contents

- IteratorAggregate::getIterator — Retrieve an external iterator or traversable

# The InternalIterator class

(PHP 8)

## Introduction

Class to ease implementing IteratorAggregate for internal classes.

## Class synopsis

final class InternalIterator implements Iterator {
/* Methods */
private __construct()
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

# InternalIterator::__construct

(PHP 8)

InternalIterator::__construct — Private constructor to disallow direct instantiation

### Description

private InternalIterator::__construct()

### Parameters

This function has no parameters.

# InternalIterator::current

(PHP 8)

InternalIterator::current — Return the current element

### Description

public InternalIterator::current(): mixed

Returns the current element.

### Parameters

This function has no parameters.

### Return Values

Returns the current element.

# InternalIterator::key

(PHP 8)

InternalIterator::key — Return the key of the current element

### Description

public InternalIterator::key(): mixed

Returns the key of the current element.

### Parameters

This function has no parameters.

### Return Values

Returns the key of the current element.

# InternalIterator::next

(PHP 8)

InternalIterator::next — Move forward to next element

### Description

public InternalIterator::next(): void

Moves the current position to the next element.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# InternalIterator::rewind

(PHP 8)

InternalIterator::rewind — Rewind the Iterator to the first element

### Description

public InternalIterator::rewind(): void

Rewinds back to the first element of the Iterator.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# InternalIterator::valid

(PHP 8)

InternalIterator::valid — Check if current position is valid

### Description

public InternalIterator::valid(): bool

Checks if current position is valid.

### Parameters

This function has no parameters.

### Return Values

Returns whether the current position is valid.

## Table of Contents

- InternalIterator::__construct — Private constructor to disallow direct instantiation
- InternalIterator::current — Return the current element
- InternalIterator::key — Return the key of the current element
- InternalIterator::next — Move forward to next element
- InternalIterator::rewind — Rewind the Iterator to the first element
- InternalIterator::valid — Check if current position is valid

# Throwable

(PHP 7, PHP 8)

## Introduction

Throwable is the base interface for any object that can be thrown via a `throw` statement, including Error and Exception.

> Note:

> PHP classes cannot implement the Throwable interface directly, and must instead extend Exception.

## Interface synopsis

interface Throwable extends Stringable {
/* Methods */
public getMessage(): string
public getCode(): int
public getFile(): string
public getLine(): int
public getTrace(): array
public getTraceAsString(): string
public getPrevious(): ?Throwable
public __toString(): string
/* Inherited methods */
public Stringable::__toString(): string
}

## Changelog

Version | Description
--- | ---
8.0.0 | Throwable implements Stringable now.

# Throwable::getMessage

(PHP 7, PHP 8)

Throwable::getMessage — Gets the message

### Description

public Throwable::getMessage(): string

Returns the message associated with the thrown object.

### Parameters

This function has no parameters.

### Return Values

Returns the message associated with the thrown object.

### See Also

- Exception::getMessage() - Gets the Exception message

# Throwable::getCode

(PHP 7, PHP 8)

Throwable::getCode — Gets the exception code

### Description

public Throwable::getCode(): int

Returns the error code associated with the thrown object.

### Parameters

This function has no parameters.

### Return Values

Returns the exception code as int in Exception but possibly as other type in Exception descendants (for example as string in PDOException).

### See Also

- Exception::getCode() - Gets the Exception code

# Throwable::getFile

(PHP 7, PHP 8)

Throwable::getFile — Gets the file in which the object was created

### Description

public Throwable::getFile(): string

Get the name of the file in which the thrown object was created.

### Parameters

This function has no parameters.

### Return Values

Returns the filename in which the thrown object was created.

### See Also

- Exception::getFile() - Gets the file in which the exception was created

# Throwable::getLine

(PHP 7, PHP 8)

Throwable::getLine — Gets the line on which the object was instantiated

### Description

public Throwable::getLine(): int

Returns the line number where the thrown object was instantiated.

### Parameters

This function has no parameters.

### Return Values

Returns the line number where the thrown object was instantiated.

### See Also

- Exception::getLine() - Gets the line in which the exception was created

# Throwable::getTrace

(PHP 7, PHP 8)

Throwable::getTrace — Gets the stack trace

### Description

public Throwable::getTrace(): array

Returns the stack trace as an array.

### Parameters

This function has no parameters.

### Return Values

Returns the stack trace as an array in the same format as debug_backtrace().

### See Also

- Exception::getTrace() - Gets the stack trace

# Throwable::getTraceAsString

(PHP 7, PHP 8)

Throwable::getTraceAsString — Gets the stack trace as a string

### Description

public Throwable::getTraceAsString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the stack trace as a string.

### See Also

- Exception::getTraceAsString() - Gets the stack trace as a string

# Throwable::getPrevious

(PHP 7, PHP 8)

Throwable::getPrevious — Returns the previous Throwable

### Description

public Throwable::getPrevious(): ?Throwable

Returns any previous Throwable (for example, one provided as the third parameter to Exception::__construct()).

### Parameters

This function has no parameters.

### Return Values

Returns the previous Throwable if available, or `null` otherwise.

### See Also

- Exception::getPrevious() - Returns previous Throwable

# Throwable::__toString

(PHP 7, PHP 8)

Throwable::__toString — Gets a string representation of the thrown object

### Description

public Throwable::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the thrown object.

### See Also

- Exception::__toString() - String representation of the exception

## Table of Contents

- Throwable::getMessage — Gets the message
- Throwable::getCode — Gets the exception code
- Throwable::getFile — Gets the file in which the object was created
- Throwable::getLine — Gets the line on which the object was instantiated
- Throwable::getTrace — Gets the stack trace
- Throwable::getTraceAsString — Gets the stack trace as a string
- Throwable::getPrevious — Returns the previous Throwable
- Throwable::__toString — Gets a string representation of the thrown object

# The Countable interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

## Introduction

Classes implementing Countable can be used with the count() function.

## Interface synopsis

interface Countable {
/* Methods */
public count(): int
}

# Countable::count

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Countable::count — Count elements of an object

### Description

public Countable::count(): int

This method is executed when the `value` for count() is an object implementing Countable.

### Parameters

This function has no parameters.

### Return Values

The custom count as an int.

### Examples

Example #1 Countable::count() example

`<?php
class Counter implements Countable
{
private $count = 0;
public function count(): int
{
return ++$this->count;
}
}
$counter = new Counter;
for ($i = 0; $i < 10; ++$i) {
echo "I have been count()ed " . count($counter) . " times\n";
}
?>`

The above example will output something similar to:

    I have been count()ed 1 times
    I have been count()ed 2 times
    I have been count()ed 3 times
    I have been count()ed 4 times
    I have been count()ed 5 times
    I have been count()ed 6 times
    I have been count()ed 7 times
    I have been count()ed 8 times
    I have been count()ed 9 times
    I have been count()ed 10 times

## Table of Contents

- Countable::count — Count elements of an object

# The ArrayAccess interface

(PHP 5, PHP 7, PHP 8)

## Introduction

Interface to provide accessing objects as arrays.

## Interface synopsis

interface ArrayAccess {
/* Methods */
public offsetExists(mixed `$offset`): bool
public offsetGet(mixed `$offset`): mixed
public offsetSet(mixed `$offset`, mixed `$value`): void
public offsetUnset(mixed `$offset`): void
}

## Examples

Example #1 Basic usage

`<?php
class Obj implements ArrayAccess {
public $container = [
"one" => 1,
"two" => 2,
"three" => 3,
];
public function offsetSet($offset, $value): void {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset): bool {
return isset($this->container[$offset]);
}
public function offsetUnset($offset): void {
unset($this->container[$offset]);
}
public function offsetGet($offset): mixed {
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
            )

    )

# ArrayAccess::offsetExists

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetExists — Whether an offset exists

### Description

public ArrayAccess::offsetExists(mixed `$offset`): bool

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

### Parameters

`offset`

  An offset to check for.

### Return Values

Returns `true` on success or `false` on failure.

> Note:

> The return value will be casted to bool if non-boolean was returned.

### Examples

Example #1 ArrayAccess::offsetExists() example

`<?php
class obj implements ArrayAccess {
public function offsetSet($offset, $value): void {
var_dump(__METHOD__);
}
public function offsetExists($var): bool {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var): void {
var_dump(__METHOD__);
}
#[\ReturnTypeWillChange]
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)

# ArrayAccess::offsetGet

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetGet — Offset to retrieve

### Description

public ArrayAccess::offsetGet(mixed `$offset`): mixed

Returns the value at specified offset.

This method is executed when checking if offset is empty().

### Parameters

`offset`

  The offset to retrieve.

### Return Values

Can return all value types.

### Notes

> Note:

> 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_NOTICE` message is raised.

### See Also

- ArrayAccess::offsetExists() - Whether an offset exists

# ArrayAccess::offsetSet

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetSet — Assign a value to the specified offset

### Description

public ArrayAccess::offsetSet(mixed `$offset`, mixed `$value`): void

Assigns a value to the specified offset.

### Parameters

`offset`

  The offset to assign the value to.

`value`

  The value to set.

### Return Values

No value is returned.

### Notes

> Note:

> The `offset` parameter will be set to `null` if 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.

# ArrayAccess::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetUnset — Unset an offset

### Description

public ArrayAccess::offsetUnset(mixed `$offset`): void

Unsets an offset.

> Note:

> This method will not be called when type-casting to (unset)

### Parameters

`offset`

  The offset to unset.

### Return Values

No value is returned.

## Table of Contents

- ArrayAccess::offsetExists — Whether an offset exists
- ArrayAccess::offsetGet — Offset to retrieve
- ArrayAccess::offsetSet — Assign a value to the specified offset
- ArrayAccess::offsetUnset — Unset an offset

# The Serializable interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

## Introduction

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

Warning

As of PHP 8.1.0, a class which implements Serializable without also implementing __serialize() and __unserialize() will generate a deprecation warning.

## Interface synopsis

interface Serializable {
/* Methods */
public serialize(): ?string
public unserialize(string `$data`): void
}

## Examples

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"

# Serializable::serialize

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Serializable::serialize — String representation of object

### Description

public Serializable::serialize(): ?string

Should return the string representation of the object.

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the object or `null`

### Errors/Exceptions

Throws Exception when returning other types than strings and `null`.

### See Also

- __sleep()
- __serialize()

# Serializable::unserialize

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Serializable::unserialize — Constructs the object

### Description

public Serializable::unserialize(string `$data`): void

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.

### Parameters

`data`

  The string representation of the object.

### Return Values

The return value from this method is ignored.

### See Also

- __wakeup()
- __unserialize()

## Table of Contents

- Serializable::serialize — String representation of object
- Serializable::unserialize — Constructs the object

# The Closure class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

Class used to represent anonymous functions.

Anonymous functions yield objects of this type. 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.

## Class synopsis

final class Closure {
/* Methods */
private __construct()
public static bind(Closure `$closure`, ?object `$newThis`, object|string|null `$newScope` = "static"): ?Closure
public bindTo(?object `$newThis`, object|string|null `$newScope` = "static"): ?Closure
public call(object `$newThis`, mixed `...$args`): mixed
public static fromCallable(callable `$callback`): Closure
public static getCurrent(): Closure
}

## Changelog

Version | Description
--- | ---
8.4.0 | The output of Closure::__debugInfo() now includes the name, line, and file of the closure.

# Closure::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Closure::__construct — Constructor that disallows instantiation

### Description

private Closure::__construct()

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.

### Parameters

This function has no parameters.

### See Also

- Anonymous functions

# Closure::bind

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Closure::bind — Duplicates a closure with a specific bound object and class scope

### Description

public static Closure::bind(Closure `$closure`, ?object `$newThis`, object|string|null `$newScope` = "static"): ?Closure

This method is a static version of Closure::bindTo(). See the documentation of that method for more information.

### Parameters

`closure`

  The anonymous functions to bind.

`newThis`

  The object to which the given anonymous function should be bound, or `null` for the closure to be unbound.

`newScope`

  The class scope to which 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. It is not allowed to pass (an object of) an internal class as this parameter.

### Return Values

Returns a new Closure object, or `null` on failure.

### Examples

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

### See Also

- Anonymous functions
- Closure::bindTo() - Duplicates the closure with a new bound object and class scope

# Closure::bindTo

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Closure::bindTo — Duplicates the closure with a new bound object and class scope

### Description

public Closure::bindTo(?object `$newThis`, object|string|null `$newScope` = "static"): ?Closure

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 method can nevertheless be used to change their class scope.

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

### Parameters

`newThis`

  The object to which the given anonymous function should be bound, or `null` for the closure to be unbound.

`newScope`

  The class scope to which 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. It is not allowed to pass (an object of) an internal class as this parameter.

### Return Values

Returns the newly created Closure object or `null` on failure.

### Examples

Example #1 Closure::bindTo() example

`<?php
class A
{
private $val;
public function __construct($val)
{
$this->val = $val;
}
public 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

### See Also

- Anonymous functions
- Closure::bind() - Duplicates a closure with a specific bound object and class scope

# Closure::call

(PHP 7, PHP 8)

Closure::call — Binds and calls the closure

### Description

public Closure::call(object `$newThis`, mixed `...$args`): mixed

Temporarily binds the closure to `newThis`, and calls it with any given parameters.

### Parameters

`newThis`

  The object to bind the closure to for the duration of the call.

`args`

  Zero or more parameters, which will be given as parameters to the closure.

### Return Values

Returns the return value of the closure.

### Examples

Example #1 Closure::call() example

`<?php
class Value {
protected $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
$three = new Value(3);
$four = new Value(4);
$closure = function ($delta) { var_dump($this->getValue() + $delta); };
$closure->call($three, 4);
$closure->call($four, 4);
?>`

The above example will output:

    int(7)
    int(8)

# Closure::fromCallable

(PHP 7 >= 7.1.0)

Closure::fromCallable — Converts a callable into a closure

### Description

public static Closure::fromCallable(callable `$callback`): Closure

Create and return a new anonymous function from given `callback` using the current scope. This method checks if the `callback` is callable in the current scope and throws a TypeError if it is not.

> Note:

> As of PHP 8.1.0, First class callable syntax has the same semantics as this method.

### Parameters

`callback`

  The callable to convert.

### Return Values

Returns the newly created Closure or throws a TypeError if the `callback` is not callable in the current scope.

### See Also

- Anonymous functions
- First class callable syntax

# Closure::getCurrent

(PHP 8 >= 8.5.0)

Closure::getCurrent — Returns the currently executing closure

### Description

public static Closure::getCurrent(): Closure

Returns the currently executing closure. This method is primarily useful for implementing recursive closures without needing to capture a reference to the closure variable using the `use` keyword.

This method must be called from within a closure; calling it outside of a closure context will result in `Error: Current function is not a closure.`

### Parameters

This function has no parameters.

### Return Values

Returns the currently executing Closure instance.

### Errors/Exceptions

Throws an Error if called outside of a closure context.

### Examples

Example #1 Closure::getCurrent() example

Using Closure::getCurrent() to implement a recursive Fibonacci function:

`<?php
$fibonacci = function (int $n) {
if ($n === 0 || $n === 1) {
return $n;
}
$fn = Closure::getCurrent();
return $fn($n - 1) + $fn($n - 2);
};
echo $fibonacci(10); // Outputs: 55
?>`

Example #2 Comparison with traditional approach

Prior to PHP 8.5, implementing recursive closures required capturing a reference to the closure variable using the `use` keyword:

`<?php
// Traditional approach (still works in PHP 8.5)
$fibonacci = function (int $n) use (&$fibonacci) {
if ($n === 0) return 0;
if ($n === 1) return 1;
return $fibonacci($n - 1) + $fibonacci($n - 2);
};
echo $fibonacci(10); // Outputs: 55
?>`

The Closure::getCurrent() approach eliminates the need to declare the variable with a reference in the `use` clause, making the code cleaner and less error-prone.

## Table of Contents

- Closure::__construct — Constructor that disallows instantiation
- Closure::bind — Duplicates a closure with a specific bound object and class scope
- Closure::bindTo — Duplicates the closure with a new bound object and class scope
- Closure::call — Binds and calls the closure
- Closure::fromCallable — Converts a callable into a closure
- Closure::getCurrent — Returns the currently executing closure

# The stdClass class

(PHP 4, PHP 5, PHP 7, PHP 8)

## Introduction

A generic empty class with dynamic properties.

Objects of this class can be instantiated with new operator or created by typecasting to object. Several PHP functions also create instances of this class, e.g. json_decode(), mysqli_fetch_object() or PDOStatement::fetchObject().

Despite not implementing __get()/__set() magic methods, this class allows dynamic properties and does not require the `#[\AllowDynamicProperties]` attribute.

This is not a base class as PHP does not have a concept of a universal base class. However, it is possible to create a custom class that extends from stdClass and as a result inherits the functionality of dynamic properties.

## Class synopsis

#[\AllowDynamicProperties]
class stdClass {
}

This class has no methods or default properties.

## Examples

Example #1 Created as a result of typecasting to object

`<?php
$obj = (object) array('foo' => 'bar');
var_dump($obj);`

The above example will output:

    object(stdClass)#1 (1) {
      ["foo"]=>
      string(3) "bar"
    }

Example #2 Created as a result of json_decode()

`<?php
$json = '{"foo":"bar"}';
var_dump(json_decode($json));`

The above example will output:

    object(stdClass)#1 (1) {
      ["foo"]=>
      string(3) "bar"
    }

Example #3 Declaring dynamic properties

`<?php
$obj = new stdClass();
$obj->foo = 42;
$obj->{1} = 42;
var_dump($obj);`

The above example will output:

    object(stdClass)#1 (2) {
      ["foo"]=>
      int(42)
      ["1"]=>
      int(42)
    }

# The Generator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

Generator objects are returned from generators.

Caution

Generator objects cannot be instantiated via new.

## Class synopsis

final class Generator implements Iterator {
/* Methods */
public current(): mixed
public getReturn(): mixed
public key(): mixed
public next(): void
public rewind(): void
public send(mixed `$value`): mixed
public throw(Throwable `$exception`): mixed
public valid(): bool
public __wakeup(): void
}

## See Also

See also object iteration.

# Generator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::current — Get the yielded value

### Description

public Generator::current(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns the yielded value.

# Generator::getReturn

(PHP 7, PHP 8)

Generator::getReturn — Get the return value of a generator

### Description

public Generator::getReturn(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns the generator's return value once it has finished executing.

### Examples

Example #1 Generator::getReturn() example

`<?php
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;`

The above example will output:

    1
    2
    3

# Generator::key

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::key — Get the yielded key

### Description

public Generator::key(): mixed

Gets the key of the yielded value.

### Parameters

This function has no parameters.

### Return Values

Returns the yielded key.

### Examples

Example #1 Generator::key() example

`<?php
function Gen()
{
yield 'key' => 'value';
}
$gen = Gen();
echo "{$gen->key()} => {$gen->current()}";`

The above example will output:

    key => value

# Generator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::next — Resume execution of the generator

### Description

public Generator::next(): void

Calling Generator::next() has the same effect as calling Generator::send() with `null` as argument.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# Generator::rewind

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::rewind — Execute the generator up to and including the first yield

### Description

public Generator::rewind(): void

Executes the generator up to and including the first `yield`. If the generator is already at the first `yield`, no action will be taken. If the generator has ever advanced beyond a `yield` expression, this method will throw an Exception.

> Note:

> This is the first method called when starting a `foreach` loop. It will not be executed after `foreach` loops.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Examples

Example #1 Generator::rewind() example

`<?php
function generator(): Generator
{
echo "I'm a generator!\n";
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
// Initialize the generator
$generator = generator();
// Rewind the generator to the beginning of the first yield expression,
// if it's not already there
$generator->rewind(); // I'm a generator!
// Nothing happens here; the generator is already rewound
$generator->rewind(); // No output (NULL)
// This rewinds the generator to the first yield expression,
// if it's not already there, and iterates over the generator
foreach ($generator as $value) {
// After yielding the first value, the generator remains at
// the first yield expression until it resumes execution and advances to the next yield
echo $value, PHP_EOL; // 1
break;
}
// Resume and rewind again. No error occurs because the generator has not advanced beyond the first yield
$generator->rewind();
echo $generator->current(), PHP_EOL; // 1
// No error occurs, the generator is still at the first yield
$generator->rewind();
// This advances the generator to the second yield expression
$generator->next();
try {
// This will throw an Exception,
// because the generator has already advanced to the second yield
$generator->rewind(); // Fatal error: Uncaught Exception: Cannot rewind a generator that was already run
} catch (Exception $e) {
echo $e->getMessage();
}
?>`

The above example will output:

    I'm a generator!
    1
    1
    Cannot rewind a generator that was already run

# Generator::send

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::send — Send a value to the generator

### Description

public Generator::send(mixed `$value`): mixed

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

### Parameters

`value`

  Value to send into the generator. This value will be the return value of the `yield` expression the generator is currently at.

### Return Values

Returns the yielded value.

### Examples

Example #1 Using Generator::send() to inject values

`<?php
function printer() {
echo "I'm printer!".PHP_EOL;
while (true) {
$string = yield;
echo $string.PHP_EOL;
}
}
$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>`

The above example will output:

    I'm printer!
    Hello world!
    Bye world!

# Generator::throw

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::throw — Throw an exception into the generator

### Description

public Generator::throw(Throwable `$exception`): mixed

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.

### Parameters

`exception`

  Exception to throw into the generator.

### Return Values

Returns the yielded value.

### Examples

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

# Generator::valid

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::valid — Check if the iterator has been closed

### Description

public Generator::valid(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `false` if the iterator has been closed. Otherwise returns `true`.

# Generator::__wakeup

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::__wakeup — Serialize callback

### Description

public Generator::__wakeup(): void

Throws an exception as generators can't be serialized.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

## Table of Contents

- Generator::current — Get the yielded value
- Generator::getReturn — Get the return value of a generator
- Generator::key — Get the yielded key
- Generator::next — Resume execution of the generator
- Generator::rewind — Execute the generator up to and including the first yield
- Generator::send — Send a value to the generator
- Generator::throw — Throw an exception into the generator
- Generator::valid — Check if the iterator has been closed
- Generator::__wakeup — Serialize callback

# The Fiber class

(PHP 8 >= 8.1.0)

## Introduction

Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.

## Class synopsis

final class Fiber {
/* Methods */
public __construct(callable `$callback`)
public start(mixed `...$args`): mixed
public resume(mixed `$value` = `null`): mixed
public throw(Throwable `$exception`): mixed
public getReturn(): mixed
public isStarted(): bool
public isSuspended(): bool
public isRunning(): bool
public isTerminated(): bool
public static suspend(mixed `$value` = `null`): mixed
public static getCurrent(): ?Fiber
}

## See Also

Fibers overview

# Fiber::__construct

(PHP 8 >= 8.1.0)

Fiber::__construct — Creates a new Fiber instance

### Description

public Fiber::__construct(callable `$callback`)

### Parameters

`callback`

  The callable to invoke when starting the fiber. Arguments given to Fiber::start() will be provided as arguments to the given callable.

# Fiber::start

(PHP 8 >= 8.1.0)

Fiber::start — Start execution of the fiber

### Description

public Fiber::start(mixed `...$args`): mixed

A variadic list of arguments to provide to the callable used when constructing the fiber.

If the fiber has already been started when this method is called, a FiberError will be thrown.

### Parameters

`args`

  The arguments to use when invoking the callable given to the fiber constructor.

### Return Values

The value provided to the first call to Fiber::suspend() or `null` if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.

# Fiber::resume

(PHP 8 >= 8.1.0)

Fiber::resume — Resumes execution of the fiber with a value

### Description

public Fiber::resume(mixed `$value` = `null`): mixed

Resumes the fiber using the given value as the result of the current Fiber::suspend() call.

If the fiber is not suspended when this method is called, a FiberError will be thrown.

### Parameters

`value`

  The value to resume the fiber. This value will be the return value of the current Fiber::suspend() call.

### Return Values

The value provided to the next call to Fiber::suspend() or `null` if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.

# Fiber::throw

(PHP 8 >= 8.1.0)

Fiber::throw — Resumes execution of the fiber with an exception

### Description

public Fiber::throw(Throwable `$exception`): mixed

Resumes the fiber by throwing the given exception from the current Fiber::suspend() call.

If the fiber is not suspended when this method is called, a FiberError will be thrown.

### Parameters

`exception`

  The exception to throw into the fiber from the current Fiber::suspend() call.

### Return Values

The value provided to the next call to Fiber::suspend() or `null` if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.

# Fiber::getReturn

(PHP 8 >= 8.1.0)

Fiber::getReturn — Gets the value returned by the Fiber

### Description

public Fiber::getReturn(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns the value returned by the callable provided to Fiber::__construct(). If the fiber has not returned a value, either because it has not been started, has not terminated, or threw an exception, a FiberError will be thrown.

# Fiber::isStarted

(PHP 8 >= 8.1.0)

Fiber::isStarted — Determines if the fiber has started

### Description

public Fiber::isStarted(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `true` only after the fiber has been started; otherwise `false` is returned.

# Fiber::isSuspended

(PHP 8 >= 8.1.0)

Fiber::isSuspended — Determines if the fiber is suspended

### Description

public Fiber::isSuspended(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the fiber is currently suspended; otherwise `false` is returned.

# Fiber::isRunning

(PHP 8 >= 8.1.0)

Fiber::isRunning — Determines if the fiber is running

### Description

public Fiber::isRunning(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `true` only if the fiber is running. A fiber is considered running after a call to Fiber::start(), Fiber::resume(), or Fiber::throw() that has not yet returned. Return `false` if the fiber is not running.

# Fiber::isTerminated

(PHP 8 >= 8.1.0)

Fiber::isTerminated — Determines if the fiber has terminated

### Description

public Fiber::isTerminated(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `true` only after the fiber has terminated, either by returning or throwing an exception; otherwise `false` is returned.

# Fiber::suspend

(PHP 8 >= 8.1.0)

Fiber::suspend — Suspends execution of the current fiber

### Description

public static Fiber::suspend(mixed `$value` = `null`): mixed

Suspends execution of the current fiber. The value provided to this method will be returned from the call to Fiber::start(), Fiber::resume(), or Fiber::throw() that switched execution into the current fiber.

When the fiber is resumed, this method returns the value provided to Fiber::resume(). If the fiber is resumed using Fiber::throw(), the exception given to that method will be thrown from the call to this method.

If this method is called from outside a fiber, a FiberError will be thrown.

### Parameters

`value`

  The value to return from the call to Fiber::start(), Fiber::resume(), or Fiber::throw() that switched execution into the current fiber.

### Return Values

The value provided to Fiber::resume().

# Fiber::getCurrent

(PHP 8 >= 8.1.0)

Fiber::getCurrent — Gets the currently executing Fiber instance

### Description

public static Fiber::getCurrent(): ?Fiber

### Parameters

This function has no parameters.

### Return Values

Returns the currently executing Fiber instance or `null` if this method is called from outside a fiber.

## Table of Contents

- Fiber::__construct — Creates a new Fiber instance
- Fiber::start — Start execution of the fiber
- Fiber::resume — Resumes execution of the fiber with a value
- Fiber::throw — Resumes execution of the fiber with an exception
- Fiber::getReturn — Gets the value returned by the Fiber
- Fiber::isStarted — Determines if the fiber has started
- Fiber::isSuspended — Determines if the fiber is suspended
- Fiber::isRunning — Determines if the fiber is running
- Fiber::isTerminated — Determines if the fiber has terminated
- Fiber::suspend — Suspends execution of the current fiber
- Fiber::getCurrent — Gets the currently executing Fiber instance

# The WeakReference class

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

Weak references allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures. If the original object has been destroyed, `null` will be returned when calling the WeakReference::get() method. The original object will be destroyed when the refcount for it drops to zero; creating weak references does not increase the `refcount` of the object being referenced.

WeakReferences cannot be serialized.

## Class synopsis

final class WeakReference {
/* Methods */
public __construct()
public static create(object `$object`): WeakReference
public get(): ?object
}

## WeakReference Examples

Example #1 Basic WeakReference Usage

`<?php
$obj = new stdClass();
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset($obj);
var_dump($weakref->get());
?>`

The above example will output something similar to:

    object(stdClass)#1 (0) {
    }
    NULL

## Changelog

Version | Description
--- | ---
8.4.0 | The output of WeakReference::__debugInfo() now includes the referenced object, or `NULL` if the reference is no longer valid.

# WeakReference::__construct

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::__construct — Constructor that disallows instantiation

### Description

public WeakReference::__construct()

This method exists only to disallow instantiation of the WeakReference class. Weak references are to be instantiated with the factory method WeakReference::create().

### Parameters

This function has no parameters.

### See Also

- WeakReference::create() - Create a new weak reference

# WeakReference::create

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::create — Create a new weak reference

### Description

public static WeakReference::create(object `$object`): WeakReference

Creates a new WeakReference.

### Parameters

`object`

  The object to be weakly referenced.

### Return Values

Returns a new WeakReference, or the existing instance if there was already a WeakReference to the same object.

# WeakReference::get

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::get — Get a weakly referenced Object

### Description

public WeakReference::get(): ?object

Gets a weakly referenced object. If the object has already been destroyed, `null` is returned.

### Parameters

This function has no parameters.

### Return Values

Returns the referenced object, or `null` if the object has been destroyed.

## Table of Contents

- WeakReference::__construct — Constructor that disallows instantiation
- WeakReference::create — Create a new weak reference
- WeakReference::get — Get a weakly referenced Object

# The WeakMap class

(PHP 8)

## Introduction

A WeakMap is map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar SplObjectStorage, an object in a key of WeakMap does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a WeakMap, the object will be garbage collected and removed from the WeakMap. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object.

WeakMap implements ArrayAccess, Traversable (via IteratorAggregate), and Countable, so in most cases it can be used in the same fashion as an associative array.

## Class synopsis

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* Methods */
public count(): int
public getIterator(): Iterator
public offsetExists(object `$object`): bool
public offsetGet(object `$object`): mixed
public offsetSet(object `$object`, mixed `$value`): void
public offsetUnset(object `$object`): void
}

## Examples

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)

# WeakMap::count

(PHP 8)

WeakMap::count — Counts the number of live entries in the map

### Description

public WeakMap::count(): int

Counts the number of live entries in the map.

### Parameters

This function has no parameters.

### Return Values

Returns the number of live entries in the map.

# WeakMap::getIterator

(PHP 8)

WeakMap::getIterator — Retrieve an external iterator

### Description

public WeakMap::getIterator(): Iterator

Returns an external iterator.

### Parameters

This function has no parameters.

### Return Values

An instance of an object implementing Iterator or Traversable

### Errors/Exceptions

Throws an Exception on failure.

# WeakMap::offsetExists

(PHP 8)

WeakMap::offsetExists — Checks whether a certain object is in the map

### Description

public WeakMap::offsetExists(object `$object`): bool

Checks whether the passed object is referenced in the map.

### Parameters

`object`

  Object to check for.

### Return Values

Returns `true` if the object is contained in the map, `false` otherwise.

# WeakMap::offsetGet

(PHP 8)

WeakMap::offsetGet — Returns the value pointed to by a certain object

### Description

public WeakMap::offsetGet(object `$object`): mixed

Returns the value pointed to by a certain object.

### Parameters

`object`

  Some object contained as key in the map.

### Return Values

Returns the value associated to the object passed as argument.

### Errors/Exceptions

Throws an Error on failure.

# WeakMap::offsetSet

(PHP 8)

WeakMap::offsetSet — Updates the map with a new key-value pair

### Description

public WeakMap::offsetSet(object `$object`, mixed `$value`): void

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.

### Parameters

`object`

  The object serving as key of the key-value pair.

`value`

  The arbitrary data serving as value of the key-value pair.

### Return Values

No value is returned.

# WeakMap::offsetUnset

(PHP 8)

WeakMap::offsetUnset — Removes an entry from the map

### Description

public WeakMap::offsetUnset(object `$object`): void

Removes an entry from the map.

### Parameters

`object`

  The key object to remove from the map.

### Return Values

No value is returned.

## Table of Contents

- WeakMap::count — Counts the number of live entries in the map
- WeakMap::getIterator — Retrieve an external iterator
- WeakMap::offsetExists — Checks whether a certain object is in the map
- WeakMap::offsetGet — Returns the value pointed to by a certain object
- WeakMap::offsetSet — Updates the map with a new key-value pair
- WeakMap::offsetUnset — Removes an entry from the map

# The Stringable interface

(PHP 8)

## Introduction

The Stringable interface denotes a class as having a __toString() method. Unlike most interfaces, Stringable is implicitly present on any class that has the magic __toString() method defined, although it can and should be declared explicitly.

Its primary value is to allow functions to type check against the union type `string|Stringable` to accept either a string primitive or an object that can be cast to a string.

## Interface synopsis

interface Stringable {
/* Methods */
public __toString(): string
}

## Stringable Examples

Example #1 Basic Stringable Usage

This uses constructor property promotion.

`<?php
class IPv4Address implements Stringable {
public function __construct(
private string $oct1,
private string $oct2,
private string $oct3,
private string $oct4,
) {}
public function __toString(): string {
return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
function showStuff(string|Stringable $value) {
// For a Stringable, this will implicitliy call __toString().
print $value;
}
$ip = new IPv4Address('123', '234', '42', '9');
showStuff($ip);
?>`

The above example will output something similar to:

    123.234.42.9

# Stringable::__toString

(PHP 8)

Stringable::__toString — Gets a string representation of the object

### Description

public Stringable::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the object.

### See Also

- __toString()

## Table of Contents

- Stringable::__toString — Gets a string representation of the object

# The UnitEnum interface

(PHP 8 >= 8.1.0)

## Introduction

The UnitEnum interface is automatically applied to all enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.

## Interface synopsis

interface UnitEnum {
/* Methods */
public static cases(): array
}

# UnitEnum::cases

(PHP 8 >= 8.1.0)

UnitEnum::cases — Generates a list of cases on an enum

### Description

public static UnitEnum::cases(): array

This method will return a packed array of all cases in an enumeration, in order of declaration.

### Parameters

This function has no parameters.

### Return Values

An array of all defined cases of this enumeration, in order of declaration.

### Examples

Example #1 Basic usage

The following example illustrates how enum cases are returned.

`<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
var_dump(Suit::cases());
?>`

The above example will output:

    array(4) {
        [0]=>
        enum(Suit::Hearts)
        [1]=>
        enum(Suit::Diamonds)
        [2]=>
        enum(Suit::Clubs)
        [3]=>
        enum(Suit::Spades)
    }

## Table of Contents

- UnitEnum::cases — Generates a list of cases on an enum

# The BackedEnum interface

(PHP 8 >= 8.1.0)

## Introduction

The BackedEnum interface is automatically applied to backed enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.

## Interface synopsis

interface BackedEnum extends UnitEnum {
/* Methods */
public static from(int|string `$value`): static
public static tryFrom(int|string `$value`): ?static
/* Inherited methods */
public static UnitEnum::cases(): array
}

# BackedEnum::from

(PHP 8 >= 8.1.0)

BackedEnum::from — Maps a scalar to an enum instance

### Description

public static BackedEnum::from(int|string `$value`): static

The from() method translates a string or int into the corresponding Enum case, if any. If there is no matching case defined, it will throw a ValueError.

### Parameters

`value`

  The scalar value to map to an enum case.

### Return Values

A case instance of this enumeration.

### Examples

Example #1 Basic usage

The following example illustrates how enum cases are returned.

`<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$h = Suit::from('H');
var_dump($h);
$b = Suit::from('B');
?>`

The above example will output:

    enum(Suit::Hearts)

    Fatal error: Uncaught ValueError: "B" is not a valid backing value for enum "Suit" in /file.php:15

### See Also

- UnitEnum::cases() - Generates a list of cases on an enum
- BackedEnum::tryFrom() - Maps a scalar to an enum instance or null

# BackedEnum::tryFrom

(PHP 8 >= 8.1.0)

BackedEnum::tryFrom — Maps a scalar to an enum instance or null

### Description

public static BackedEnum::tryFrom(int|string `$value`): ?static

The tryFrom() method translates a string or int into the corresponding Enum case, if any. If there is no matching case defined, it will return null.

### Parameters

`value`

  The scalar value to map to an enum case.

### Return Values

A case instance of this enumeration, or null if not found.

### Examples

Example #1 Basic usage

The following example illustrates how enum cases are returned.

`<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$h = Suit::tryFrom('H');
var_dump($h);
$b = Suit::tryFrom('B') ?? Suit::Spades;
var_dump($b);
?>`

The above example will output:

    enum(Suit::Hearts)
    enum(Suit::Spades)

### See Also

- UnitEnum::cases() - Generates a list of cases on an enum
- BackedEnum::from() - Maps a scalar to an enum instance

## Table of Contents

- BackedEnum::from — Maps a scalar to an enum instance
- BackedEnum::tryFrom — Maps a scalar to an enum instance or null

# The SensitiveParameterValue class

(PHP 8 >= 8.2.0)

## Introduction

The SensitiveParameterValue class allows wrapping sensitive values to protect them against accidental exposure.

Values of parameters having the SensitiveParameter attribute will automatically be wrapped inside of a SensitiveParameterValue object within stack traces.

## Class synopsis

final class SensitiveParameterValue {
/* Properties */
private readonly mixed $value;
/* Methods */
public __construct(mixed `$value`)
public __debugInfo(): array
public getValue(): mixed
}

## Properties

value

  The sensitive value to be protected against accidental exposure.

# SensitiveParameterValue::__construct

(PHP 8 >= 8.2.0)

SensitiveParameterValue::__construct — Constructs a new SensitiveParameterValue object

### Description

public SensitiveParameterValue::__construct(mixed `$value`)

Construct a SensitiveParameterValue holding a sensitive value.

### Parameters

`value`

  An arbitrary value that should be stored inside the SensitiveParameterValue object.

# SensitiveParameterValue::__debugInfo

(PHP 8 >= 8.2.0)

SensitiveParameterValue::__debugInfo — Protects the sensitive value against accidental exposure

### Description

public SensitiveParameterValue::__debugInfo(): array

Returns an empty array to protect the sensitive value against accidental exposure when using var_dump().

### Parameters

This function has no parameters.

### Return Values

An empty array.

### Examples

Example #1 Passing a SensitiveParameterValue object to var_dump()

`<?php
$s = new \SensitiveParameterValue('secret');
var_dump($s);
?>`

The above example will output:

    object(SensitiveParameterValue)#1 (0) {
    }

# SensitiveParameterValue::getValue

(PHP 8 >= 8.2.0)

SensitiveParameterValue::getValue — Returns the sensitive value

### Description

public SensitiveParameterValue::getValue(): mixed

Get the sensitive value.

### Parameters

This function has no parameters.

### Return Values

The sensitive value.

### Examples

Example #1 SensitiveParameterValue::getValue() example

`<?php
$s = new \SensitiveParameterValue('secret');
echo "The protected value is: ", $s->getValue(), "\n";
?>`

The above example will output:

    The protected value is: secret

## Table of Contents

- SensitiveParameterValue::__construct — Constructs a new SensitiveParameterValue object
- SensitiveParameterValue::__debugInfo — Protects the sensitive value against accidental exposure
- SensitiveParameterValue::getValue — Returns the sensitive value

# The __PHP_Incomplete_Class class

(PHP 4 >=4.0.1, PHP 5, PHP 7, PHP 8)

## Introduction

Created by unserialize() when trying to unserialize an undefined class or a class that is not listed in the `allowed_classes` of unserialize()'s `options` array.

Prior to PHP 7.2.0, using is_object() on the __PHP_Incomplete_Class class would return `false`. As of PHP 7.2.0, `true` will be returned.

## Class synopsis

#[\AllowDynamicProperties]
final class __PHP_Incomplete_Class {
}

This class has no default properties or methods. When created by unserialize(), in addition to all unserialized properties and values the object will have a `__PHP_Incomplete_Class_Name` property which will contain the name of the unserialized class.

## Changelog

Version | Description
--- | ---
8.0.0 | This class is now `final`.

## Examples

Example #1 Created by unserialize()

`<?php
class MyClass
{
public string $property = "myValue";
}
$myObject = new MyClass;
$foo = serialize($myObject);
// unserializes all objects into __PHP_Incomplete_Class objects
$disallowed = unserialize($foo, ["allowed_classes" => false]);
var_dump($disallowed);
// unserializes all objects into __PHP_Incomplete_Class objects except those of MyClass2 and MyClass3
$disallowed2 = unserialize($foo, ["allowed_classes" => ["MyClass2", "MyClass3"]]);
var_dump($disallowed2);
// unserializes undefined class into __PHP_Incomplete_Class object
$undefinedClass = unserialize('O:16:"MyUndefinedClass":0:{}');
var_dump($undefinedClass);`

The above example will output:

    object(__PHP_Incomplete_Class)#2 (2) {
      ["__PHP_Incomplete_Class_Name"]=>
      string(7) "MyClass"
      ["property"]=>
      string(7) "myValue"
    }
    object(__PHP_Incomplete_Class)#3 (2) {
      ["__PHP_Incomplete_Class_Name"]=>
      string(7) "MyClass"
      ["property"]=>
      string(7) "myValue"
    }
    object(__PHP_Incomplete_Class)#4 (1) {
      ["__PHP_Incomplete_Class_Name"]=>
      string(16) "MyUndefinedClass"
    }

# Predefined Attributes

## Table of Contents

- Attribute
- AllowDynamicProperties
- Deprecated
- NoDiscard
- Override
- ReturnTypeWillChange
- SensitiveParameter

PHP provides some predefined attributes that can be used.

# The Attribute attribute

(PHP 8)

## Introduction

Attributes offer the ability to add structured, machine-readable metadata information on declarations in code: Classes, methods, functions, parameters, properties and class constants can be the target of an attribute. The metadata defined by attributes can then be inspected at runtime using the Reflection APIs. Attributes could therefore be thought of as a configuration language embedded directly into code.

## Class synopsis

#[\Attribute]
final class Attribute {
/* Constants */
const int TARGET_CLASS;
const int TARGET_FUNCTION;
const int TARGET_METHOD;
const int TARGET_PROPERTY;
const int TARGET_CLASS_CONSTANT;
const int TARGET_PARAMETER;
const int TARGET_CONSTANT;
const int TARGET_ALL;
const int IS_REPEATABLE;
/* Properties */
public int $flags;
/* Methods */
public __construct(int `$flags` = `Attribute::TARGET_ALL`)
}

## Predefined Constants

`Attribute::TARGET_CLASS`

`Attribute::TARGET_FUNCTION`

`Attribute::TARGET_METHOD`

`Attribute::TARGET_PROPERTY`

`Attribute::TARGET_CLASS_CONSTANT`

`Attribute::TARGET_PARAMETER`

`Attribute::TARGET_CONSTANT`

`Attribute::TARGET_ALL`

`Attribute::IS_REPEATABLE`

## Properties

flags

## Changelog

Version | Description
--- | ---
8.5.0 | Added `Attribute::TARGET_CONSTANT`.

## See Also

Attributes overview

# Attribute::__construct

(PHP 8)

Attribute::__construct — Construct a new Attribute instance

### Description

public Attribute::__construct(int `$flags` = `Attribute::TARGET_ALL`)

Constructs a new Attribute instance.

### Parameters

`flags`

## Table of Contents

- Attribute::__construct — Construct a new Attribute instance

# The AllowDynamicProperties attribute

(PHP 8 >= 8.2.0)

## Introduction

This attribute is used to mark classes that allow dynamic properties.

> Note: Although attributes themselves are not inherited, the effect of the `AllowDynamicProperties` attribute is inherited. Child classes of a class marked with this attribute will also allow dynamic properties, even if they do not explicitly declare the attribute.

## Class synopsis

#[\Attribute]
final class AllowDynamicProperties {
/* Methods */
public __construct()
}

## Examples

Dynamic properties are deprecated as of PHP 8.2.0, thus using them without marking the class with this attribute will emit a deprecation notice.

Example #1 AllowDynamicProperties with non-existing property

`<?php
class DefaultBehaviour { }
#[\AllowDynamicProperties]
class ClassAllowsDynamicProperties { }
$o1 = new DefaultBehaviour();
$o2 = new ClassAllowsDynamicProperties();
$o1->nonExistingProp = true;
$o2->nonExistingProp = true;
?>`

Output of the above example in PHP 8.2:

    Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 10

Example #2 AllowDynamicProperties with non-existing property in inherited class

`<?php
class DefaultBehaviour { }
#[\AllowDynamicProperties]
class ClassAllowsDynamicProperties { }
class InheritedClassAllowsDynamicProperties extends ClassAllowsDynamicProperties { }
$o1 = new DefaultBehaviour();
$o2 = new InheritedClassAllowsDynamicProperties();
$o1->nonExistingProp = true;
$o2->nonExistingProp = true;
?>`

Output of the above example in PHP 8.2:

    Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 12

## See Also

Attributes overview

# AllowDynamicProperties::__construct

(PHP 8 >= 8.2.0)

AllowDynamicProperties::__construct — Construct a new AllowDynamicProperties attribute instance

### Description

public AllowDynamicProperties::__construct()

Constructs a new AllowDynamicProperties instance.

### Parameters

This function has no parameters.

## Table of Contents

- AllowDynamicProperties::__construct — Construct a new AllowDynamicProperties attribute instance

# The Deprecated attribute

(PHP 8 >= 8.4.0)

## Introduction

This attribute is used to mark functionality as deprecated. Using deprecated functionality will cause an `E_USER_DEPRECATED` error to be emitted.

## Class synopsis

#[\Attribute]
final class Deprecated {
/* Properties */
public readonly ?string $message;
public readonly ?string $since;
/* Methods */
public __construct(?string `$message` = `null`, ?string `$since` = `null`)
}

## Properties

message

  An optional message explaining the reason for the deprecation and possible replacement functionality. Will be included in the emitted deprecation message.

since

  An optional string indicating since when the functionality is deprecated. The contents are not validated by PHP and may contain a version number, a date or any other value that is considered appropriate. Will be included in the emitted deprecation message.

  Functionality that is part of PHP will use Major.Minor as the since value, for example `'8.4'`.

## Examples

`<?php
#[\Deprecated(message: "use safe_replacement() instead", since: "1.5")]
function unsafe_function()
{
echo "This is unsafe", PHP_EOL;
}
unsafe_function();
?>`

Output of the above example in PHP 8.4 is similar to:

    Deprecated: Function unsafe_function() is deprecated since 1.5, use safe_replacement() instead in example.php on line 9
    This is unsafe

## See Also

- Attributes overview
- ReflectionFunctionAbstract::isDeprecated()
- ReflectionClassConstant::isDeprecated()
- `E_USER_DEPRECATED`

# Deprecated::__construct

(PHP 8 >= 8.4.0)

Deprecated::__construct — Construct a new Deprecated attribute instance

### Description

public Deprecated::__construct(?string `$message` = `null`, ?string `$since` = `null`)

Constructs a new Deprecated instance.

### Parameters

`message`

  The value of the message property.

`since`

  The value of the since property.

## Table of Contents

- Deprecated::__construct — Construct a new Deprecated attribute instance

# The NoDiscard attribute

(PHP 8 >= 8.5.0)

## Introduction

This attribute can be used to indicate that the return value of a function or a method should not be discarded. If the return value is not used in any way, a warning will be emitted.

This is useful for functions where not checking the return value is likely to be a bug.

To intentionally discard the return value of such a function, use (void) cast to suppress the warning.

> Note: Since attributes are designed to be backwards compatible, `#[\NoDiscard]` can be added to functions and methods even when PHP 8.4 or below are supported, it just won't do anything. On PHP 8.5 and above a warning will be emitted if the result is unused. To suppress the warning without using `(void)`, which is not supported before PHP 8.5, consider using a variable like `$_`.

## Class synopsis

#[\Attribute]
final class NoDiscard {
/* Properties */
public readonly ?string $message;
/* Methods */
public __construct(?string `$message` = `null`)
}

## Properties

message
  An optional message explaining why the return value should not be discarded.

## Examples

Example #1 Basic usage

`<?php
/**
* Processes all the given items and returns an array with the results of the
* operation for each item. `null` indicates success and an Exception indicates
* an error. The keys of the result array match the keys of the $items array.
*
* @param array<string> $items
* @return array<null|Exception>
*/
#[\NoDiscard("as processing might fail for individual items")]
function bulk_process(array $items): array {
$results = [];
foreach ($items as $key => $item) {
if (\random_int(0, 9999) < 9999) {
// Pretend to do something useful with $item,
// which will succeed in 99.99% of cases.
echo "Processing {$item}", PHP_EOL;
$error = null;
} else {
$error = new \Exception("Failed to process {$item}.");
}
$results[$key] = $error;
}
return $results;
}
bulk_process($items);
?>`

Output of the above example in PHP 8.5 is similar to:

    Warning: The return value of function bulk_process() should either be used or intentionally ignored by casting it as (void), as processing might fail for individual items

Example #2 Intentionally discarding the return value

`<?php
#[\NoDiscard]
function some_command(): int {
return 1;
}
// Suppress the warning using (void) - PHP 8.5+
(void) some_command();
// For compatibility with PHP versions before 8.5, use a temporary variable
$_ = some_command();
?>`

## See Also

- Attributes overview

# NoDiscard::__construct

(PHP 8 >= 8.5.0)

NoDiscard::__construct — Construct a new NoDiscard attribute instance

### Description

public NoDiscard::__construct(?string `$message` = `null`)

Constructs a new NoDiscard instance.

### Parameters

`message`
  The value of the message property.

## Table of Contents

- NoDiscard::__construct — Construct a new NoDiscard attribute instance

# The Override attribute

(PHP 8 >= 8.3.0)

## Introduction

This attribute is used to indicate that a method or a property is intended to override a method or a property of a parent class or that it implements a method or a property defined in an interface.

If no method or property with the same name exists in a parent class or in an implemented interface a compile-time error will be emitted.

The attribute cannot be used on the __construct() method, which is exempt from signature checks.

## Class synopsis

#[\Attribute]
final class Override {
/* Methods */
public __construct()
}

## Changelog

Version | Description
--- | ---
8.5.0 | Override can be applied to properties.

## Examples

Example #1 Usage with methods

`<?php
class Base {
protected function foo(): void {}
}
final class Extended extends Base {
#[\Override]
protected function boo(): void {}
}
?>`

Output of the above example in PHP 8.3 is similar to:

    Fatal error: Extended::boo() has #[\Override] attribute, but no matching parent method exists

Example #2 Usage with properties

`<?php
class Base {
protected string $foo;
}
final class Extended extends Base {
#[\Override]
protected string $boo;
}
?>`

Output of the above example in PHP 8.5 is similar to:

    Fatal error: Extended::$boo has #[\Override] attribute, but no matching parent property exists

## See Also

- Attributes overview

# Override::__construct

(PHP 8 >= 8.3.0)

Override::__construct — Construct a new Override attribute instance

### Description

public Override::__construct()

Constructs a new Override instance.

### Parameters

This function has no parameters.

## Table of Contents

- Override::__construct — Construct a new Override attribute instance

# The ReturnTypeWillChange attribute

(PHP 8 >= 8.1.0)

## Introduction

Most non-final internal methods now require overriding methods to declare a compatible return type, otherwise a deprecated notice is emitted during inheritance validation. In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a `#[\ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

## Class synopsis

#[\Attribute]
final class ReturnTypeWillChange {
/* Methods */
public __construct()
}

## See Also

Attributes overview

# ReturnTypeWillChange::__construct

(PHP 8 >= 8.1.0)

ReturnTypeWillChange::__construct — Construct a new ReturnTypeWillChange attribute instance

### Description

public ReturnTypeWillChange::__construct()

Constructs a new ReturnTypeWillChange instance.

### Parameters

This function has no parameters.

## Table of Contents

- ReturnTypeWillChange::__construct — Construct a new ReturnTypeWillChange attribute instance

# The SensitiveParameter attribute

(PHP 8 >= 8.2.0)

## Introduction

This attribute is used to mark a parameter that is sensitive and should have its value redacted if present in a stack trace.

## Class synopsis

#[\Attribute]
final class SensitiveParameter {
/* Methods */
public __construct()
}

## Examples

`<?php
function defaultBehavior(
string $secret,
string $normal
) {
throw new Exception('Error!');
}
function sensitiveParametersWithAttribute(
#[\SensitiveParameter]
string $secret,
string $normal
) {
throw new Exception('Error!');
}
try {
defaultBehavior('password', 'normal');
} catch (Exception $e) {
echo $e, PHP_EOL, PHP_EOL;
}
try {
sensitiveParametersWithAttribute('password', 'normal');
} catch (Exception $e) {
echo $e, PHP_EOL, PHP_EOL;
}
?>`

Output of the above example in PHP 8.2 is similar to:

    Exception: Error! in example.php:7
    Stack trace:
    #0 example.php(19): defaultBehavior('password', 'normal')
    #1 {main}

    Exception: Error! in example.php:15
    Stack trace:
    #0 example.php(25): sensitiveParametersWithAttribute(Object(SensitiveParameterValue), 'normal')
    #1 {main}

## See Also

- Attributes overview
- SensitiveParameterValue

# SensitiveParameter::__construct

(PHP 8 >= 8.2.0)

SensitiveParameter::__construct — Construct a new SensitiveParameter attribute instance

### Description

public SensitiveParameter::__construct()

Constructs a new SensitiveParameter instance.

### Parameters

This function has no parameters.

## Table of Contents

- SensitiveParameter::__construct — Construct a new SensitiveParameter attribute instance

# Context options and parameters

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 options — Socket context option listing

### Description

Socket context options are available for all wrappers that work over sockets, like `tcp`, `http` and `ftp`.

### Options

`bindto`

  Used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is `ip:port` for IPv4 addresses, and `[ip]:port` for IPv6 addresses. Setting the IP or the port to `0` will let the system choose the IP and/or port.

  > Note:

  > As FTP creates two socket connections during normal operation, the port number cannot be specified using this option.

`backlog`

  Used to limit the number of outstanding connections in the socket's listen queue.

  > Note:

  > This is only applicable to stream_socket_server().

`ipv6_v6only`

  Overrides the OS default regarding mapping IPv4 into IPv6.

  > Note:

  > This is important in particular when trying to listen on IPv4 addresses separately while there exists a binding on `[::]`.

  > This is only applicable to stream_socket_server().

`so_reuseport`

  Allows multiple bindings to a same ip:port pair, even from separate processes.

  > Note:

  > This is only applicable to stream_socket_server().

`so_broadcast`

  Enables sending and receiving data to/from broadcast addresses.

  > Note:

  > This is only applicable to stream_socket_server().

`tcp_nodelay`

  Setting this option to `true` will set `SOL_TCP,NO_DELAY=1` appropriately, thus disabling the TCP Nagle algorithm.

### Changelog

Version | Description
--- | ---
7.1.0 | Added `tcp_nodelay`.
7.0.1 | Added `ipv6_v6only`.

### Examples

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 options — HTTP context option listing

### Description

Context options for `http://` and `https://` transports.

### Options

`method` string

  `GET`, `POST`, or any other HTTP method supported by the remote server.

  Defaults to `GET`.

`header` array or string

  Additional headers to be sent during request. Values in this option will override other values (such as `User-agent:`, `Host:`, and `Authentication:`), even when following `Location:` redirects. Thus it is not recommended to set a `Host:` header, if `follow_location` is enabled.

  String value should be `Key: value` pairs delimited by `\r\n`, e.g. `"Content-Type: application/json\r\nConnection: close"`. Array value should be a list of `Key: value` pairs, e.g. `["Content-Type: application/json", "Connection: close"]`.

`user_agent` string

  Value to send with `User-Agent:` header. This value will only be used if user-agent is not specified in the `header` context option above.

  By default the user_agent php.ini setting is used.

`content` string

  Additional data to be sent after the headers. Typically used with POST or PUT requests.

`proxy` string

  URI specifying address of proxy server (e.g. `tcp://proxy.example.com:5100`).

`request_fulluri` bool

  When set to `true`, the entire URI will be used when constructing the request (e.g. `GET http://www.example.com/path/to/file.html HTTP/1.0`). While this is a non-standard request format, some proxy servers require it.

  Defaults to `false`.

`follow_location` int

  Follow `Location` header redirects. Set to `0` to disable.

  Defaults to `1`.

`max_redirects` int

  The max number of redirects to follow. Value `1` or less means that no redirects are followed.

  Defaults to `20`.

`protocol_version` float

  HTTP protocol version.

  Defaults to `1.1` as of PHP 8.0.0; prior to that version the default was `1.0`.

`timeout` float

  Read timeout in seconds, specified by a float (e.g. `10.5`).

  By default the default_socket_timeout php.ini setting is used.

`ignore_errors` bool

  Fetch the content even on failure status codes.

  Defaults to `false`.

### Examples

Example #1 Fetch a page and send POST data

`<?php
$postdata = http_build_query(
[
'var1' => 'some content',
'var2' => 'doh',
]
);
$opts = [
'http' => [
'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 = [
'http' => [
'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);
?>`

### Notes

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

>     array (
>       'wrapper_data' =>
>       array (
>         0 => 'HTTP/1.0 301 Moved Permanently',
>         1 => 'Cache-Control: no-cache',
>         2 => 'Connection: close',
>         3 => 'Location: http://example.com/foo.jpg',
>         4 => 'HTTP/1.1 200 OK',
>         ...

> The first request returned a `301` (permanent redirect), so the stream wrapper automatically followed the redirect to get a `200` response (index = `4`).

### See Also

- http://
- Socket context options
- SSL context options

# FTP context options

FTP context options — FTP context option listing

### Description

Context options for `ftp://` and `ftps://` transports.

### Options

`overwrite` bool

  Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

  Defaults to `false`.

`resume_pos` int

  File offset at which to begin transfer. Applies to read mode (downloading) only.

  Defaults to `0` (Beginning of File).

`proxy` string

  Proxy FTP request via http proxy server. Applies to file read operations only. Ex: `tcp://squid.example.com:8000`.

### Notes

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

### See Also

- ftp://
- Socket context options
- SSL context options

# SSL context options

SSL context options — SSL context option listing

### Description

Context options for `ssl://` and `tls://` transports.

### Options

`peer_name` string

  Peer name to be used. If this value is not set, then the name is guessed based on the hostname used when opening the stream.

`verify_peer` bool

  Require verification of SSL certificate used.

  Defaults to `true`.

`verify_peer_name` bool

  Require verification of peer name.

  Defaults to `true`.

`allow_self_signed` bool

  Allow self-signed certificates. Requires `verify_peer`.

  Defaults to `false`

`cafile` string

  Location of Certificate Authority file on local filesystem which should be used with the `verify_peer` context option to authenticate the identity of the remote peer.

`capath` string

  If `cafile` is not specified or if the certificate is not found there, the directory pointed to by `capath` is searched for a suitable certificate. `capath` must be a correctly hashed certificate directory.

`local_cert` string

  Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers. The private key also may be contained in a separate file specified by `local_pk`.

`local_pk` string

  Path to local private key file on filesystem in case of separate files for certificate (`local_cert`) and private key.

`passphrase` string

  Passphrase with which your `local_cert` file was encoded.

`verify_depth` int

  Abort if the certificate chain is too deep.

  Defaults to no verification.

`ciphers` string

  Sets the list of available ciphers. The format of the string is described in » ciphers(1).

  Defaults to `DEFAULT`.

`capture_peer_cert` bool

  If set to `true` a `peer_certificate` context option will be created containing the peer certificate.

`capture_peer_cert_chain` bool

  If set to `true` a `peer_certificate_chain` context option will be created containing the certificate chain.

`SNI_enabled` bool

  If set to `true` server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.

`disable_compression` bool

  If set, disable TLS compression. This can help mitigate the CRIME attack vector.

`peer_fingerprint` string | array

  Aborts when the remote certificate digest doesn't match the specified hash.

  When a string is used, the length will determine which hashing algorithm is applied, either "md5" (32) or "sha1" (40).

  When an array is used, the keys indicate the hashing algorithm name and each corresponding value is the expected digest.

`security_level` int

  Sets the security level. If not specified the library default security level is used. The security levels are described in » SSL_CTX_get_security_level(3).

  Available as of PHP 7.2.0 and OpenSSL 1.1.0.

### Changelog

Version | Description
--- | ---
7.2.0 | Added `security_level`. Requires OpenSSL >= 1.1.0.

### Notes

> 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_NAME` to determine whether SNI is supported.

### See Also

- Socket context options

# Phar context options

Phar context options — Phar context option listing

### Description

Context options for `phar://` wrapper.

### Options

`compress` int

  One of Phar compression constants.

`metadata` mixed

  Phar metadata. See Phar::setMetadata().

### See Also

- phar://
- Phar stream wrapper

# Context parameters

Context parameters — Context parameter listing

### Description

These `parameters` can be set on a `context` using the stream_context_set_params() function.

### Parameters

`notification` callable

  A callable to be called when an event occurs on a stream.

  See stream_notification_callback for more details.

# Zip context options

Zip context options — Zip context option listing

### Description

Zip context options are available for `zip` wrappers.

### Options

`password`

  Used to specify password used for encrypted archive.

### Changelog

Version | Description
--- | ---
7.2.0, PECL zip 1.14.0 | Added `password`.

### Examples

Example #1 Basic `password` usage example

`<?php
// Read encrypted archive
$opts = array(
'zip' => array(
'password' => 'secret',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('zip://test.zip#test.txt', false, $context);
?>`

# Zlib context options

Zlib context options — Zlib context option listing

### Description

Zlib context options are available for `zlib` wrappers.

### Options

`level`

  Used to specify the compression level (`0` - `9`).

### Changelog

Version | Description
--- | ---
7.3.0 | `level` has been added.

## Table of Contents

- Socket context options — Socket context option listing
- HTTP context options — HTTP context option listing
- FTP context options — FTP context option listing
- SSL context options — SSL context option listing
- Phar context options — Phar context option listing
- Context parameters — Context parameter listing
- Zip context options — Zip context option listing
- Zlib context options — Zlib context option listing

# Supported Protocols and Wrappers

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

file:// — Accessing local filesystem

### Description

`file://` 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.

### Usage

- /path/to/file.ext
- relative/path/to/file.ext
- fileInCwd.ext
- C:/path/to/winfile.ext
- C:\path\to\winfile.ext
- \\smbserver\share\path\to\winfile.ext
- file:///path/to/file.ext

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | Yes
Supports stat() | Yes
Supports unlink() | Yes
Supports rename() | Yes
Supports mkdir() | Yes
Supports rmdir() | Yes

# http://

# https://

http:// -- https:// — Accessing HTTP(s) URLs

### Description

Allows read-only access to files/resources via HTTP. By default, a HTTP 1.0 GET is used. 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.

### Usage

- http://example.com
- http://example.com/file.php?var1=val1&var2=val2
- http://user:password@example.com
- https://example.com
- https://example.com/file.php?var1=val1&var2=val2
- https://user:password@example.com

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | Yes
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | N/A
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

### Examples

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

### Notes

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

### See Also

- HTTP context options
- $http_response_header
- stream_get_meta_data() - Retrieves header/meta data from streams/file pointers

# ftp://

# ftps://

ftp:// -- ftps:// — Accessing FTP(s) URLs

### Description

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.

### Usage

- ftp://example.com/pub/file.txt
- ftp://user:password@example.com/pub/file.txt
- ftps://example.com/pub/file.txt
- ftps://user:password@example.com/pub/file.txt

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | Yes
Allows Reading | Yes
Allows Writing | Yes (new files/existing files with `overwrite`)
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | filesize(), filemtime(), filetype(), file_exists(), is_file(), and is_dir() elements only.
Supports unlink() | Yes
Supports rename() | Yes
Supports mkdir() | Yes
Supports rmdir() | Yes

### Notes

> 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
> Files may be appended via the `ftp://` URL wrapper.

### See Also

- FTP context options

# php://

php:// — Accessing various I/O streams

### Description

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

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

php://input is a read-only stream that allows you to read raw data from the request body. php://input is not available in POST requests with `enctype="multipart/form-data"` if enable_post_data_reading option is enabled.

#### php://output

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

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

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. One 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.

Caution

Some PHP extensions may require a standard IO stream, and may attempt to cast a given stream to a standard IO stream. This cast can fail for memory streams as it requires the C fopencookie() function to be available. This C function is not available on Windows.

#### php://filter

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.

php://filter 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.

### Options

Wrapper Summary (for `php://filter`, refer to the summary of the wrapper being filtered)
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Restricted by allow_url_include | `php://input`, `php://stdin`, `php://memory` and `php://temp` only.
Allows Reading | `php://stdin`, `php://input`, `php://fd`, `php://memory` and `php://temp` only.
Allows Writing | `php://stdout`, `php://stderr`, `php://output`, `php://fd`, `php://memory` and `php://temp` only.
Allows Appending | `php://stdout`, `php://stderr`, `php://output`, `php://fd`, `php://memory` and `php://temp` only. (Equivalent to writing)
Allows Simultaneous Reading and Writing | `php://fd`, `php://memory` and `php://temp` only.
Supports stat() | No. However, `php://memory` and `php://temp` support fstat().
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No
Supports stream_select() | `php://stdin`, `php://stdout`, `php://stderr`, `php://fd` and `php://temp` only.

### Examples

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");
?>`

Example #5 php://memory and php://temp are not reusable

php://memory and php://temp are not reusable, i.e. after the streams have been closed there is no way to refer to them again.

`<?php
file_put_contents('php://memory', 'PHP');
echo file_get_contents('php://memory'); // prints nothing`

Example #6 php://input to read JSON data from the request body

This example demonstrates how to read raw JSON data from POST, PUT and PATCH requests using php://input.

`<?php
$input = file_get_contents("php://input");
$json_array = json_decode(
json: $input,
associative: true,
flags: JSON_THROW_ON_ERROR
);
echo "Received JSON data: ";
print_r($json_array);
?>`

# zlib://

# bzip2://

# zip://

zlib:// -- bzip2:// -- zip:// — Compression Streams

### Description

compress.zlib:// and compress.bzip2://

zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated 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. As of PHP 7.2.0 and libzip 1.2.0+, support for the passwords for encrypted archives were added, allowing passwords to be supplied by stream contexts. Passwords can be set using the `'password'` stream context option.

### Usage

- compress.zlib://file.gz
- compress.bzip2://file.bz2
- zip://archive.zip#dir/file.txt

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes (except `zip://`)
Allows Appending | Yes (except `zip://`)
Allows Simultaneous Reading and Writing | No
Supports stat() | No, use the normal `file://` wrapper to stat compressed files.
Supports unlink() | No, use the normal `file://` wrapper to unlink compressed files.
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

### See Also

- Zlib context options

# data://

data:// — Data (RFC 2397)

### Description

The data: (» RFC 2397) stream wrapper.

### Usage

- data://text/plain;base64,

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | Yes
Restricted by allow_url_include | Yes
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

### Examples

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

glob:// — Find pathnames matching pattern

### Description

The glob: stream wrapper.

### Usage

- glob://

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | No
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

### Examples

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

phar:// — PHP Archive

### Description

The phar:// stream wrapper. See Phar stream wrapper for a detailed description.

### Usage

- phar://

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | No
Allows Simultaneous Reading and Writing | Yes
Supports stat() | Yes
Supports unlink() | Yes
Supports rename() | Yes
Supports mkdir() | Yes
Supports rmdir() | Yes

### See Also

- Phar context options

# ssh2://

ssh2:// — Secure Shell 2

### Description

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// (PECL)

> Note: This wrapper is not enabled by default
> In order to use the ssh2.*:// wrappers, the » SSH2 extension available from » PECL must be installed.

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.

### Usage

- ssh2.shell://user:pass@example.com:22/xterm
- ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
- ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
- ssh2.sftp://user:pass@example.com:22/path/to/filename

### Options

Wrapper Summary
Attribute | ssh2.shell | ssh2.exec | ssh2.tunnel | ssh2.sftp | ssh2.scp
--- | --- | --- | --- | --- | ---
Restricted by allow_url_fopen | Yes | Yes | Yes | Yes | Yes
Allows Reading | Yes | Yes | Yes | Yes | Yes
Allows Writing | Yes | Yes | Yes | Yes | No
Allows Appending | No | No | No | Yes (When supported by server) | No
Allows Simultaneous Reading and Writing | Yes | Yes | Yes | Yes | No
Supports stat() | No | No | No | Yes | No
Supports unlink() | No | No | No | Yes | No
Supports rename() | No | No | No | Yes | No
Supports mkdir() | No | No | No | Yes | No
Supports rmdir() | No | No | No | Yes | No

Context options
Name | Usage | Default
--- | --- | ---
`session` | Preconnected ssh2 resource to be reused |
`sftp` | Preallocated sftp resource to be reused |
`methods` | Key exchange, hostkey, cipher, compression, and MAC methods to use |
`callbacks` |  |
`username` | Username to connect as |
`password` | Password to use with password authentication |
`pubkey_file` | Name of public key file to use for authentication |
`privkey_file` | Name of private key file to use for authentication |
`env` | Associate array of environment variables to set |
`term` | Terminal emulation type to request when allocating a pty |
`term_width` | Width of terminal requested when allocating a pty |
`term_height` | Height of terminal requested when allocating a pty |
`term_units` | Units to use with term_width and term_height | `SSH2_TERM_UNIT_CHARS`

### Examples

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, the $session resource variable must be kept. 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:// — RAR

### Description

The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterisk (`*`), 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, the » rar extension available from » PECL must be installed.

rar:// Available since PECL rar 3.0.0

### Usage

- rar://<url encoded archive name>[*][#[<url encoded entry name>]]

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | No
Supports stat() | Yes
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Context options
Name | Usage | Default
--- | --- | ---
`open_password` | The password used to encrypt the headers of the archive, if any. WinRAR will encrypt all the files with the same password as the headers password when the later is present, so for archives with encrypted headers, `file_password` will be ignored. |
`file_password` | The password used to encrypt a file, if any. If the headers are also encrypted, this option will be ignored in favor of `open_password`. The reason there are two options is to cover the possibility of supporting archives with different headers and file passwords, should those archives arise. Note that if the archive does not have its headers encrypted, `open_password` will be ignored and this option must be used instead. |
`volume_callback` | A callback to determine the path of missing volumes. See RarArchive::open() for more information. |

### Examples

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

ogg:// — Audio streams

### Description

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 written 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:// (PECL)

> Note: This wrapper is not enabled by default
> In order to use the ogg:// wrapper, the » OGG/Vorbis extension available from » PECL must be installed.

### Usage

- ogg://soundfile.ogg
- ogg:///path/to/soundfile.ogg
- ogg://http://www.example.com/path/to/soundstream.ogg

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Context options
Name | Usage | Default | Mode
--- | --- | --- | ---
`pcm_mode` | PCM encoding to apply while reading, one of: `OGGVORBIS_PCM_U8`, `OGGVORBIS_PCM_S8`, `OGGVORBIS_PCM_U16_BE`, `OGGVORBIS_PCM_S16_BE`, `OGGVORBIS_PCM_U16_LE`, and `OGGVORBIS_PCM_S16_LE`. (8 vs 16 bit, signed or unsigned, big or little `endian`) | OGGVORBIS_PCM_S16_LE | Read
`rate` | Sampling rate of input data, expressed in Hz | 44100 | Write/Append
`bitrate` | When given as an integer, the fixed bitrate at which to encode. (16000 to 131072) When given as a float, the variable bitrate quality to use. (-1.0 to 1.0) | 128000 | Write/Append
`channels` | The number of audio channels to encode, typically 1 (Mono), or 2 (Stereo). May range as high as 16. | 2 | Write/Append
`comments` | An array of string values to encode into the track header. |  | Write/Append

# expect://

expect:// — Process Interaction Streams

### Description

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, the » Expect extension available from » PECL must be installed.

expect:// (PECL)

### Usage

- expect://command

### Options

Wrapper Summary
Attribute | Supported
--- | ---
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | Yes
Allows Simultaneous Reading and Writing | No
Supports stat() | No
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

## Table of Contents

- file:// — Accessing local filesystem
- http:// — Accessing HTTP(s) URLs
- ftp:// — Accessing FTP(s) URLs
- php:// — Accessing various I/O streams
- zlib:// — Compression Streams
- data:// — Data (RFC 2397)
- glob:// — Find pathnames matching pattern
- phar:// — PHP Archive
- ssh2:// — Secure Shell 2
- rar:// — RAR
- ogg:// — Audio streams
- expect:// — Process Interaction Streams

- Basic syntax
  - PHP tags
  - Escaping from HTML
  - Instruction separation
  - Comments
- Types
  - Introduction
  - Type System
  - NULL
  - Booleans
  - Integers
  - Floating point numbers
  - Strings
  - Numeric strings
  - Arrays
  - Objects
  - Enumerations
  - Resources
  - Callables
  - Mixed
  - Void
  - Never
  - Relative class types
  - Singleton types
  - Iterables
  - Type declarations
  - Type Juggling
- Variables
  - Basics
  - Predefined Variables
  - Variable scope
  - Variable variables
  - Variables From External Sources
- Constants
  - Syntax
  - Predefined constants
  - Magic constants
- Expressions
- Operators
  - Operator Precedence
  - Arithmetic — Arithmetic Operators
  - Increment and Decrement — Incrementing/Decrementing Operators
  - Assignment — Assignment Operators
  - Bitwise — Bitwise Operators
  - Comparison — Comparison Operators
  - Error Control — Error Control Operators
  - Execution — Execution Operators
  - Logic — Logical Operators
  - String — String Operators
  - Array — Array Operators
  - Type — Type Operators
  - Functional — Functional Operators
- Control Structures
  - Introduction
  - if
  - else
  - elseif/else if
  - Alternative syntax for control structures
  - while
  - do-while
  - for
  - foreach
  - break
  - continue
  - switch
  - match
  - declare
  - return
  - require
  - include
  - require_once
  - include_once
  - goto
- Functions
  - User-defined functions
  - Function parameters and arguments
  - Returning values
  - Variable functions
  - Internal (built-in) functions
  - Anonymous functions
  - Arrow Functions
  - First class callable syntax
- Classes and Objects
  - Introduction
  - The Basics
  - Properties
  - Property Hooks
  - Class Constants
  - Autoloading Classes
  - Constructors and Destructors
  - Visibility
  - Object Inheritance
  - Scope Resolution Operator (::)
  - Static Keyword
  - Class Abstraction
  - Object Interfaces
  - Traits
  - Anonymous classes
  - Overloading
  - Object Iteration
  - Magic Methods
  - Final Keyword
  - Object Cloning
  - Comparing Objects
  - Late Static Bindings
  - Objects and references
  - Object Serialization — Serializing objects - objects in sessions
  - Covariance and Contravariance
  - Lazy Objects
  - OOP Changelog
- Namespaces
  - Overview — Namespaces overview
  - Namespaces — Defining namespaces
  - Sub-namespaces — Declaring sub-namespaces
  - Defining multiple namespaces in the same file
  - Basics — Using namespaces: Basics
  - Namespaces and dynamic language features
  - namespace keyword and __NAMESPACE__ — The namespace keyword and __NAMESPACE__ magic constant
  - Aliasing and Importing — Using namespaces: Aliasing/Importing
  - Global space
  - Fallback to global space — Using namespaces: fallback to the global space for functions and constants
  - Name resolution rules
  - FAQ — FAQ: things you need to know about namespaces
- Enumerations
  - Enumerations overview
  - Basic enumerations
  - Backed enumerations
  - Enumeration methods
  - Enumeration static methods
  - Enumeration constants
  - Traits
  - Enum values in constant expressions
  - Differences from objects
  - Value listing
  - Serialization
  - Why enums aren't extendable
  - Examples
- Errors
  - Basics
  - Errors in PHP 7
- Exceptions
  - Extending Exceptions
- Fibers
- Generators
  - Generators overview
  - Generator syntax
  - Comparing generators with Iterator objects
- Attributes
  - Attributes overview
  - Attribute syntax
  - Reading Attributes with the Reflection API
  - Declaring Attribute Classes
- References Explained
  - What References Are
  - What References Do
  - What References Are Not
  - Passing by Reference
  - Returning References
  - Unsetting References
  - Spotting References
- Predefined Variables
  - Superglobals — Built-in variables that are always available in all scopes
  - $GLOBALS — References all variables available in global scope
  - $_SERVER — Server and execution environment information
  - $_GET — Query string variables
  - $_POST — Form data from HTTP POST requests
  - $_FILES — HTTP File Upload variables
  - $_REQUEST — HTTP Request variables
  - $_SESSION — Session variables
  - $_ENV — Environment variables
  - $_COOKIE — HTTP Cookies
  - $php_errormsg — The previous error message
  - $http_response_header — HTTP response headers
  - $argc — The number of arguments passed to script
  - $argv — Array of arguments passed to script
- Predefined Exceptions
  - Exception
  - ErrorException
  - ClosedGeneratorException — The ClosedGeneratorException class
  - Error
  - ArgumentCountError
  - ArithmeticError
  - AssertionError
  - DivisionByZeroError
  - CompileError
  - ParseError
  - TypeError
  - ValueError
  - UnhandledMatchError
  - FiberError
  - RequestParseBodyException
- Predefined Interfaces and Classes
  - Traversable — The Traversable interface
  - Iterator — The Iterator interface
  - IteratorAggregate — The IteratorAggregate interface
  - InternalIterator — The InternalIterator class
  - Throwable
  - Countable — The Countable interface
  - ArrayAccess — The ArrayAccess interface
  - Serializable — The Serializable interface
  - Closure — The Closure class
  - stdClass — The stdClass class
  - Generator — The Generator class
  - Fiber — The Fiber class
  - WeakReference — The WeakReference class
  - WeakMap — The WeakMap class
  - Stringable — The Stringable interface
  - UnitEnum — The UnitEnum interface
  - BackedEnum — The BackedEnum interface
  - SensitiveParameterValue — The SensitiveParameterValue class
  - __PHP_Incomplete_Class — The __PHP_Incomplete_Class class
- Predefined Attributes
  - Attribute — The Attribute attribute
  - AllowDynamicProperties — The AllowDynamicProperties attribute
  - Deprecated — The Deprecated attribute
  - NoDiscard — The NoDiscard attribute
  - Override — The Override attribute
  - ReturnTypeWillChange — The ReturnTypeWillChange attribute
  - SensitiveParameter — The SensitiveParameter attribute
- Context options and parameters
  - Socket context options — Socket context option listing
  - HTTP context options — HTTP context option listing
  - FTP context options — FTP context option listing
  - SSL context options — SSL context option listing
  - Phar context options — Phar context option listing
  - Context parameters — Context parameter listing
  - Zip context options — Zip context option listing
  - Zlib context options — Zlib context option listing
- Supported Protocols and Wrappers
  - file:// — Accessing local filesystem
  - http:// — Accessing HTTP(s) URLs
  - ftp:// — Accessing FTP(s) URLs
  - php:// — Accessing various I/O streams
  - zlib:// — Compression Streams
  - data:// — Data (RFC 2397)
  - glob:// — Find pathnames matching pattern
  - phar:// — PHP Archive
  - ssh2:// — Secure Shell 2
  - rar:// — RAR
  - ogg:// — Audio streams
  - expect:// — Process Interaction Streams

# Security

# Introduction

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.

# General considerations

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.

# Installed as CGI binary

## Table of Contents

- Possible attacks
- Case 1: only public files served
- Case 2: using cgi.force_redirect
- Case 3: setting doc_root or user_dir
- Case 4: PHP parser outside of web tree

## Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable php binary to the web server cgi-bin directory. CERT advisory » CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the php binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

- Accessing system files: http://my.host/cgi-bin/php?/etc/passwd The query information in a URL after the question mark (`?`) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line. When invoked as a CGI binary, php refuses to interpret the command line arguments.
- Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: `Action`) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server. In PHP, runtime configuration directives cgi.force_redirect, doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.

## Case 1: only public files served

If your server does not have any content that is not restricted by password or IP based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can enable the cgi.force_redirect ini directive. 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).

## Case 2: using `cgi.force_redirect`

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.

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.

## Case 3: setting doc_root or user_dir

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.

## Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

    #!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the `#!` shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the cgi.discard_path ini directive has to be enabled.

# Installed as an Apache module

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.

# Session Security

It is important to keep your HTTP session management secure. Session related security is described in the Session Security section of Session module reference.

# Filesystem Security

## Table of Contents

- Null bytes related issues

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!";
?>`
Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were `"../etc/"` and `"passwd"`. The code would then effectively read:

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!";
?>`
There are two important measures you should take to prevent these issues.

- Only allow limited permissions to the PHP web user binary.
- Check all variables which are submitted.

Here is an improved script:

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 mechanism
$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);
?>`
However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login `"../etc/"`, the system is once again exposed. For this reason, you may prefer to write a more customized check:

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.

## Null bytes related issues

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

# Database Security

## Table of Contents

- Designing Databases
- Connecting to Database
- Encrypted Storage Model
- SQL Injection

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.

## Designing Databases

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.

## Connecting to Database

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.

## Encrypted Storage Model

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 OpenSSL and Sodium, 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.

### Hashing

In the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing should 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.

The password functions provide a convenient way to hash sensitive data and work with these hashes.

password_hash() is used to hash a given string using the strongest algorithm currently available and password_verify() checks whether the given password matches the hash stored in database.

Example #1 Hashing password field

`<?php
// storing password hash
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username),
password_hash($password, PASSWORD_DEFAULT));
$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 && password_verify($password, $row['pwd'])) {
echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}
?>`

## SQL Injection

SQL injection is a technique where an attacker exploits flaws in application code responsible for building dynamic SQL queries. The attacker can gain access to privileged sections of the application, retrieve all information from the database, tamper with existing data, or even execute dangerous system-level commands on the database host. The vulnerability occurs when developers concatenate or interpolate arbitrary input in their SQL statements.

Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)

In the following example, user input is directly interpolated into the SQL query allowing the attacker to gain a superuser account in the database.

`<?php
$offset = $_GET['offset']; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>`
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a number. However, what if someone tries to break in by appending the following to the URL

    0;
    insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
        select 'crack', usesysid, 't','t','crack'
        from pg_shadow where usename='postgres';
    --

If it happened, the script would present a superuser access to the attacker. Note that `0;` is to supply a valid offset to the original query and to terminate it.

> Note:

> It is a 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. It is strongly recommended to store only secure hashes of passwords instead of the passwords themselves.

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);
?>`
The static part of the query can be combined with another `SELECT` statement which reveals all passwords:

    '
    union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
    --

`UPDATE` and `INSERT` statements are also susceptible to such attacks.

Example #3 From resetting a password ... to gaining more privileges (any database server)

`<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>`
If a malicious user submits the value `' or uid like'%admin%` to $uid to change the admin's password, or simply sets $pwd to `hehehe', trusted=100, admin='yes` to gain more privileges, then the query will be twisted:
`<?php
// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";
// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";
?>`

While it remains obvious that an attacker must possess at least some knowledge of the database architecture to conduct a successful attack, obtaining this information is often very simple. For example, the code may be part of an open-source software and be publicly available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your own code through the display of error messages. Other methods include the use of typical table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.

Example #4 Attacking the database host operating system (MSSQL Server)

A frightening example of how operating system-level commands can be accessed on some database hosts.

`<?php
$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>`
If attacker submits the value `a%' exec master..xp_cmdshell 'net user test testpass /ADD' --` to $prod, then the $query will be:
`<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);
?>`
MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as `sa` and the MSSQLSERVER service was running with sufficient privileges, the attacker would now have an account with which to access this machine.

> Note:

> Some examples above are tied to a specific database server, but it does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.

Image courtesy of » xkcd

### Avoidance Techniques

The recommended way to avoid SQL injection is by binding all data via prepared statements. Using parameterized queries isn't enough to entirely avoid SQL injection, but it is the easiest and safest way to provide input to SQL statements. All dynamic data literals in `WHERE`, `SET`, and `VALUES` clauses must be replaced with placeholders. The actual data will be bound during the execution and sent separately from the SQL command.

Parameter binding can only be used for data. Other dynamic parts of the SQL query must be filtered against a known list of allowed values.

Example #5 Avoiding SQL injection by using PDO prepared statements

`<?php
// The dynamic SQL part is validated against expected values
$sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
$productId = $_GET['productId'];
// The SQL is prepared with a placeholder
$stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
// The value is provided with LIKE wildcards
$stmt->execute(["%{$productId}%"]);
?>`

Prepared statements are provided by PDO, by MySQLi, and by other database libraries.

SQL injection attacks are mainly based on exploiting the code not being written with security in mind. Never trust any input, especially 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 simple query can cause disasters.

A defense-in-depth strategy involves several good coding practices:

- Never connect to the database as a superuser or as the database owner. Use always customized users with minimal privileges.
- Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl Compatible Regular Expressions support.
- If the application expects numerical input, consider verifying data with ctype_digit(), silently change its type using settype(), or use its numeric representation by sprintf().
- If the database layer doesn't support binding variables then quote each non-numeric user-supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). Generic functions like addslashes() are useful only in a very specific environment (e.g. MySQL in a single-byte character set with disabled NO_BACKSLASH_ESCAPES), so it is better to avoid them.
- Do not print out any database-specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

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.

# Error Reporting

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&amp;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&amp;showerrors=1&amp;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");
}
?>`

# User Submitted Data

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:

- Will this script only affect the intended files?
- Can unusual or undesirable data be acted upon?
- Can this script be used in unintended ways?
- Can this be used in conjunction with other scripts in a negative manner?
- Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

Improve security by disabling convenience settings that obscure input data's origin, validity, or integrity. Implicit variable creation and unchecked input can lead to vulnerabilities like injection attacks and data manipulation.

Features like `register_globals` and `magic_quotes` (both removed in PHP 5.4.0) once contributed to these risks by automatically creating variables from user input and escaping data inconsistently. While no longer in PHP, similar risks persist if input handling is mismanaged.

Enable error_reporting(E_ALL) to help detect uninitialized variables and validate input. Use strict types (declare(strict_types=1), introduced in PHP 7) to enforce type safety, prevent unintended type conversions, and improving overall security.

# Hiding PHP

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

Or obscure it completely:

Example #2 Using unknown types for PHP extensions

    # Make PHP code look like unknown types
    AddType application/x-httpd-php .bop .foo .133t

Or hide it as HTML code, which has a slight performance hit because all HTML will be parsed through the PHP engine:

Example #3 Using HTML types for PHP extensions

    # Make all PHP code look like HTML
    AddType application/x-httpd-php .htm .html

For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.

# Keeping Current

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.

- Introduction
- General considerations
- Installed as CGI binary
  - Possible attacks
  - Case 1: only public files served
  - Case 2: using cgi.force_redirect
  - Case 3: setting doc_root or user_dir
  - Case 4: PHP parser outside of web tree
- Installed as an Apache module
- Session Security
- Filesystem Security
  - Null bytes related issues
- Database Security
  - Designing Databases
  - Connecting to Database
  - Encrypted Storage Model
  - SQL Injection
- Error Reporting
- User Submitted Data
- Hiding PHP
- Keeping Current

# Features

# HTTP authentication with PHP

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 array. Only the "Basic" authentication method is supported. See the header() function for more information.

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('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="My Realm"');
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>";
}
?>`

> Note: Compatibility

> 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.1 401 header line. Authentication parameters have to be comma-separated.

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.

> Note: Apache Configuration

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

> Note: Browser behavior
> HTTP Basic authentication really is basic, and it wasn't designed to support logouts. Because HTTP is a stateless protocol, most browsers will cache the provided credentials as soon as a `2xx` status code is seen, and will send them in every request, until the browser is closed. There is no defined way for a server to request a new prompt for credentials. Over the years, various workarounds for this have spread as advice on the internet, but they all depend on how different browsers have chosen to handle undefined edge cases (or even violations of the HTTP standard). It is best to avoid such workarounds and not use Basic authentication for anything serious.

> Note: IIS Configuration
> In order to get HTTP Authentication to work on IIS server with the CGI version of PHP, the php.ini directive cgi.rfc2616_headers must be set to `0` (the default value), and you must edit your IIS configuration "`Directory Security`". Click on "`Edit`" and only check "`Anonymous Access`", all other fields should be left unchecked.

# Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to server from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add `[]` to the cookie name.

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.

# Sessions

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.

# Handling file uploads

## Table of Contents

- POST method uploads
- Error Messages Explained
- Common Pitfalls
- Uploading multiple files
- PUT method support
- See Also

## POST method uploads

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 will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

  The original name of the file on the client machine.

$_FILES['userfile']['type']

  The mime type of the file, if the browser provided this information. An example would be `"image/gif"`. This mime type is however not checked on the PHP side and therefore don't take its value for granted.

$_FILES['userfile']['size']

  The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

  The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

  The error code associated with this file upload.

$_FILES['userfile']['full_path']

  The full path as submitted by the browser. This value does not always contain a real directory structure, and cannot be trusted. Available as of PHP 8.1.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
$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. Also, 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];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>`

File upload progress bar can be implemented using Session Upload Progress.

## Error Messages Explained

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

The value of this error code is one of the `UPLOAD_ERR_*` constants.

## Common Pitfalls

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.

Warning

max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of `60` seconds may be exceeded.

If post_max_size is set too small, large files cannot be uploaded. Make sure you set `post_max_size` large enough.

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.

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[]`).

## Uploading multiple files

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.

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.

Warning

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.

Example #2 Uploading an entire directory

In HTML file upload fields, it is possible to upload an entire directory with the `webkitdirectory` attribute. This feature is supported in most modern browsers.

With the `full_path` information, it is possible to store the relative paths, or reconstruct the same directory in the server.

    <form action="file-upload.php" method="post" enctype="multipart/form-data">
      Send this directory:<br />
      <input name="userfile[]" type="file" webkitdirectory multiple />
      <input type="submit" value="Send files" />
    </form>

Warning

The `webkitdirectory` attribute is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

PHP only parses the relative path information submitted by the browser/user-agent, and passes that information to the $_FILES array. There is no guarantee that the values in the `full_path` array contains a real directory structure, and the PHP application must not trust this information.

## PUT method support

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

## See Also

- Filesystem Security

# Using remote files

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 (allow_url_include must be enabled for these). See Supported Protocols and Wrappers for more information about the protocols supported by PHP.

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

# Connection handling

Internally in PHP a connection status is maintained. There are 4 possible states:

- 0 - NORMAL
- 1 - ABORTED
- 2 - TIMEOUT
- 3 - ABORTED and TIMEOUT

When a PHP script is running normally, the NORMAL state is active. If the remote client disconnects, the ABORTED state flag is turned on. A remote client disconnect is usually caused by users hitting their 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 Database Connections

### What are Persistent Connections?

Persistent connections are links that do not close when the execution of the script ends. When a persistent connection is requested, PHP checks whether an identical persistent connection (that remained open from earlier) already exists; if one does, it is reused, and if not, a new link is created. An 'identical' connection is one opened to the same host with the same username and password (where applicable).

There is no way to request a specific connection, or to guarantee whether the returned connection will be an existing one or a brand new one (if all existing connections are in use, or the request is being served by a different worker, which has a separate pool of connections).

PHP's persistent connections therefore cannot be used to, for example:

- assign a specific database session to a specific web user
- create a large transaction across multiple requests
- initiate a query on one request and collect the results on another

Persistent connections do not provide any functionality that was not possible with non-persistent connections.

### Web Requests

There are two ways in which a 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 the 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, there is nothing to be gained from using persistent connections - they simply do not persist.

The second, and most popular, method is to run PHP-FPM, or PHP as a module in a multiprocess web server (currently only Apache). These setups typically have one process (the parent) which coordinates a set of processes (its children) that 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. Once a persistent connection has been opened, any subsequent page served by the same child process can reuse the already established connection to the SQL server.

> Note:

> The method in use can be checked by looking at the value of "Server API" in the output of phpinfo() or the value of `PHP_SAPI`, run from a web request.

> If the Server API is "Apache 2 Handler" or "FPM/FastCGI", then persistent connections will be used across requests served by the same worker. For any other value, persistent connections will not persist after each request.

### Command-line Processes

As command-line PHP uses a new process for each script, persistent connections are not shared between command-line scripts, so there is no value in using them in transient scripts such as crons or commands. However, they may be useful, for example, in a long-running application server that serves many requests or tasks, each of which may need its own database connection.

### Why Use Them?

Persistent connections are beneficial when the overhead of creating a link to an SQL server is high. Whether this overhead is significant depends on many factors, such as the type of database, whether it resides on the same machine as the web server, and how loaded that machine is. When the connection overhead is high, persistent connections can help considerably: each child process connects only once for its entire lifespan, rather than every time it processes a page that requires a connection to the SQL server. This means every child that opens a persistent connection will maintain its own connection to the server. For example, if 20 different child processes each run a script that makes a persistent connection to the SQL server, there will be 20 separate connections to that server, one from each child.

### Potential Drawbacks: Connection Limits

Note, however, that this can have drawbacks when using a database with connection limits that are exceeded by persistent child connections. If the database has a limit of 16 simultaneous connections, and during a busy server session 17 child processes attempt to connect, one of them will fail. If there are bugs in the scripts that prevent connections from shutting down (such as infinite loops), a database with only 16 connections may be rapidly swamped.

Persistent connections will usually increase the number of connections open at any given time, because idle workers still hold on to the connections they opened for previous requests. If a large number of workers are spun up to handle a spike in traffic, the connections they opened will remain until the worker is terminated or the database server closes the connection.

Ensure that the maximum number of connections allowed by the database server is greater than the maximum number of web request workers (plus any other usage such as crons or administrative connections).

Check the database documentation for information on handling abandoned or idle connections (timeouts). Long timeouts may significantly increase the number of persistent connections open at any one time.

### Potential Drawbacks: Maintaining Connection State

Some database extensions perform automatic cleanup when the connection is reused; others leave this task at the discretion of the application developer. Depending on the chosen database extension and the application design, manual cleanup may be needed before the script exits. Changes that may leave connections in an unexpected state include:

- Selected / default database
- Table locks
- Uncommitted transactions
- Temporary tables
- Connection specific settings or features such as profiling

Table locks and transactions that are not cleaned up or closed may cause other queries to be blocked indefinitely and/or cause subsequent reuse of the connection to cause unexpected changes.

Having the wrong database selected will cause subsequent reuse of the connection to be unable to execute queries as expected (or execute them on the wrong database if schemas are similar enough).

If temporary tables are not cleaned up, subsequent requests will not be able to recreate the same table.

Cleanup can be implemented using class destructors or register_shutdown_function(). Dedicated connection pooling proxies that include this as part of their functionality may also be considered.

### Final Words

Given their behavior and potential drawbacks described above, persistent connections should not be used without careful consideration. They should not be used without implementing additional changes to the application and careful configuration of the database server and web server and/or PHP-FPM.

Consider alternative solutions such as investigating and fixing the causes of connection creation overheads (for example, disabling reverse DNS lookups on the database server), or dedicated connection pooling proxies.

For high volume web APIs, consider using alternative runtimes or long-running application servers.

### See Also

- ibase_pconnect()
- oci_pconnect()
- odbc_pconnect()
- pfsockopen()
- pg_connect()
- MySQLi and Persistent Connections
- PDO Connection Management

# Using PHP from the command line

## Table of Contents

- Differences to other SAPIs
- Options
- Usage
- I/O streams
- Interactive shell
- Built-in web server
- INI settings

## Introduction

The main focus of CLI 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.

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 `man`ual page is available by typing man php in the shell environment.

## Differences to other SAPIs

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:

  Overridden php.ini directives
  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 environment 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 `true` means that scripts executed via the CLI SAPI always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments). 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']. Warning The presence of $argv or $_SERVER['argv'] is not a reliable indication that a script is being run from the command line because they may be set in other contexts when register_argc_argv is enabled. The value returned by php_sapi_name() should be checked instead. `<?php if (php_sapi_name() === 'cli') { echo "This is being run from the command line!\n"; }`
  output_buffering | `false` | Although the php.ini setting is hardcoded to `false`, the Output buffering functions are available.
  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.

## Command line options

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

Command line options
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]
Example #1 Example of using `-d` to set an INI setting
    # 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 | Syntax check but do not execute the given PHP code. The input from standard input will be processed if no filenames are specified, otherwise each filename will be checked. On success, the text `No syntax errors detected in <filename>` is written to standard output. On failure, the text `Errors parsing <filename>` is written to standard output in addition to the internal parser error. If any failures are found in the specified files (or standard input), the shell return code is set to `-1`, otherwise the shell return code is set to `0`. This option won't find fatal errors (like undefined functions) that require executing the code. Note: Prior to PHP 8.3.0, it was only possible to specify one filename to be checked. Note: This option does not work together with the -r option.
-m | --modules | Example #2 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. Note: Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell. Example #3 Getting a syntax error when using double quotes
>     $ php -r "$foo = get_defined_constants();"
>     PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

>     Parse error: syntax error, unexpected '=' in Command line code on line 1
> The problem here is that sh/bash performs variable substitution even when using double quotes `"`. Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:
>     $ php -r " = get_defined_constants();"
> The correct way would be to use single quotes `'`. Variables in single-quoted strings are not expanded by sh/bash. Example #4 Using single quotes to prevent the shell's variable substitution
>     $ php -r '$foo = get_defined_constants(); var_dump($foo);'
>     array(370) {
>       ["E_ERROR"]=>
>       int(1)
>       ["E_WARNING"]=>
>       int(2)
>       ["E_PARSE"]=>
>       int(4)
>       ["E_NOTICE"]=>
>       int(8)
>       ["E_CORE_ERROR"]=>
>       [...]
If using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at » https://github.com/php/php-src/issues. It is still easy to run into trouble when trying to use variables (shell or PHP) in command-line code, or using backslashes for escaping, so take great care when doing so. You have been warned! Note: -r is available in the CLI SAPI, but not in the CGI SAPI. Note: This option is only intended for very basic code, so some configuration directives (such as auto_prepend_file and auto_append_file) are ignored in this mode.
-B | --process-begin | PHP code to execute before processing stdin.
-R | --process-code | PHP code to execute for every input line. 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.
-E | --process-end | PHP code to execute after processing the input. Example #5 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.
-t | --docroot | Specifies document root for built-in web server.
-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. Note: This option does not work together with the -r option.
-v | --version | Example #6 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. Note: This option does not work together with the -r option.
-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. Example #7 `--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). This option is only available if PHP was compiled with Reflection support. Example #8 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). This option is only available if PHP was compiled with Reflection support. Example #9 `--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). This option is only available if PHP was compiled with Reflection support. Example #10 `--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()).
--ri | --rextinfo | Show the configuration information for the given extension (the same information that is returned by phpinfo()). The core configuration information is available using "main" as extension name. Example #11 `--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.

## Executing PHP files

There are three different ways of supplying the CLI SAPI with PHP code to be executed:

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

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

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

You cannot combine any of the three ways to execute code.

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 `"Standard input code"`; prior to PHP 7.2.0, it was a dash (`"-"`) instead. 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.

> Note:

> On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because "No mapping between account names and security IDs was done".

## Input/output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

CLI specific Constants
Constant | Description
--- | ---
`STDIN` | An already opened stream to `stdin`. This saves opening it with `<?php $stdin = fopen('php://stdin', 'r'); ?>` If you want to read single line from `stdin`, you can use `<?php $line = trim(fgets(STDIN)); // reads one line from STDIN fscanf(STDIN, "%d\n", $number); // reads number from STDIN ?>`
`STDOUT` | An already opened stream to `stdout`. This saves opening it with `<?php $stdout = fopen('php://stdout', 'w'); ?>`
`STDERR` | An already opened stream to `stderr`. This saves opening it with `<?php $stderr = fopen('php://stderr', 'w'); ?>`

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

You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

> Note:

> These constants are not available if reading the PHP script from `stdin`.

## Interactive shell

The CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1.0 the interactive shell is also available on Windows, if the readline extension is enabled.

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 8.4.0, the path to the history file can be set using the PHP_HISTFILE environment variable.

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.

It is also 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:

`cli.prompt` 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.

## Interactive mode

If the readline extension is not available, prior to PHP 8.1.0, invoking the CLI SAPI with the -a option provided the interactive mode. In this mode, a complete PHP script is supposed to be given via STDIN, and after termination with ``CTRL` +`D`` (POSIX) or ``CTRL` +`Z`` followed by +`ENTER` (Windows), this script is evaluated. This is basically the same as invoking the CLI SAPI without the -a option.

As of PHP 8.1.0, invoking the CLI SAPI with the -a option fails, if the readline extension is not available.

## Built-in web server

Warning

This web server is 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.

The CLI SAPI provides a built-in web server.

The web server runs only one single-threaded process, so 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, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise 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`, `.png`, `.pps`, `.pptx`, `.qt`, `.svg`, `.swf`, `.tar`, `.text`, `.tif`, `.txt`, `.wav`, `.webm`, `.wmv`, `.xls`, `.xlsx`, `.xml`, `.xsl`, `.xsd`, `.zip` .

As of PHP 7.4.0, the built-in webserver can be configured to fork multiple workers in order to test code that requires multiple concurrent requests to the built-in webserver. Set the PHP_CLI_SERVER_WORKERS environment variable to the number of desired workers before starting the server.

> Note: This feature is not supported on Windows.

> Note: For information on PHP commandline usage and options, run php --help or man php. Not all options will apply when running the web server.

Warning

This experimental feature is not intended for production usage. Generally, the built-in Web Server is not intended for production usage.

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

Note that prior to PHP 7.4.0, symlinked statical resources have not been accessible on Windows, unless the router script would handle these.

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

Warning

The built-in Web Server should not be used on a public network.

## INI settings

CLI SAPI Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
cli_server.color | "0" | `INI_ALL` |

Here's a short explanation of the configuration directives.

`cli_server.color` bool

  Enable the built-in development web server to use ANSI color coding in terminal output.

# Garbage Collection

## Table of Contents

- Reference Counting Basics
- Collecting Cycles
- Performance Considerations

This section explains the merits of the new Garbage Collection (also known as GC) mechanism that is part of PHP 5.3.

## Reference Counting Basics

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 references (i.e. "is_ref" is `true`) with "refcount" `1`, are treated as if they are not references (i.e. as "is_ref" was `false`). If you have » Xdebug installed, you can display this information by calling xdebug_debug_zval().

Example #2 Displaying zval information

`<?php
$a = "new string";
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 a symbol is unassigned (e.g. by calling unset()). The following example shows this:

Example #4 Decreasing zval refcount

`<?php
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );
$b = 42;
xdebug_debug_zval( 'a' );
unset( $c );
xdebug_debug_zval( 'a' );
?>`

The above example will output:

    a: (refcount=3, is_ref=0)='new string'
    a: (refcount=2, 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.

### Compound Types

Things get a tad more complex with compound types such as arrays and objects. As opposed to scalar values, 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 as an element of itself

`<?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

### Cleanup Problems

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.

## Collecting Cycles

Traditionally, reference counting memory mechanisms, such as that used previously by PHP, fail to address circular reference memory leaks; however, as of 5.3.0, PHP 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_THRESHOLD_DEFAULT` 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.

## Performance Considerations

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.

### Reduced Memory Usage

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.14159265359';
public $self;
}
$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.

### Run-Time Slowdowns

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.14159265359';
public $self;
}
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.

### PHP's Internal GC Statistics

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.

### Conclusion

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 Dynamic Tracing

## Table of Contents

- Introduction to PHP and DTrace
- Using PHP and DTrace
- Using SystemTap with PHP DTrace Static Probes

## Introduction to PHP and DTrace

DTrace is an always-available, low overhead, tracing framework available on a number of platforms including Solaris, macOS, 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.

The static DTrace probes in PHP can alternatively be used with the SystemTap facility on some Linux distributions.

## Using PHP and DTrace

PHP can be configured with DTrace static probes on platforms that support DTrace Dynamic Tracing.

### Configuring PHP for DTrace Static Probes

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 makes the static probes available in core PHP. Any PHP extensions that provide their own probes should be built separately as shared extensions.

To enable probes, set USE_ZEND_DTRACE=1 environment variable to the target PHP processes.

### DTrace Static Probes in Core PHP

The following static probes are available in PHP
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.

### Listing DTrace Static Probes in PHP

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.

### DTrace with PHP Example

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 ``CTRL`+`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);
          [ . . .]
    }

### See Also

- OCI8 and DTrace Dynamic Tracing

## Using SystemTap with PHP DTrace Static Probes

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.

### Installing PHP with SystemTap

Install the SystemTap SDT development package:

    # yum install systemtap-sdt-devel

Install PHP with the DTrace probes enabled:

    # ./configure --enable-dtrace ...
    # make

### Listing Static Probes with SystemTap

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

### SystemTap with PHP Example

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

- HTTP authentication with PHP
- Cookies
- Sessions
- Handling file uploads
  - POST method uploads
  - Error Messages Explained
  - Common Pitfalls
  - Uploading multiple files
  - PUT method support
  - See Also
- Using remote files
- Connection handling
- Persistent Database Connections
- Command line usage — Using PHP from the command line
  - Differences to other SAPIs
  - Options — Command line options
  - Usage — Executing PHP files
  - I/O streams — Input/output streams
  - Interactive shell
  - Built-in web server
  - INI settings
- Garbage Collection
  - Reference Counting Basics
  - Collecting Cycles
  - Performance Considerations
- DTrace Dynamic Tracing
  - Introduction to PHP and DTrace
  - Using PHP and DTrace
  - Using SystemTap with PHP DTrace Static Probes

# Function Reference

Tip

See also Extension List/Categorization.

# Affecting PHP's Behaviour

# APC User Cache

# Introduction

APCu is an in-memory key-value store for PHP. Keys are of type string and values can be any PHP variables. APCu only supports userland caching of variables.

The APCu cache is per-process on Windows, so when using a process-based (rather than thread-based) SAPI, it will not be shared between different processes.

APCu is APC stripped of opcode caching.

The first APCu codebase was versioned 4.0.0, it was forked from the head of the APC master branch at the time. PHP 7 support is available as of APCu 5.0.0. PHP 8 support is available as of APCu 5.1.19.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

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: » https://pecl.php.net/package/apcu.

Tip

PHP 7 has a separate module (» apcu-bc) for backwards compatibility with APC.

In backward compatibility mode, APCu registers the applicable APC functions with backward compatible prototypes.

Where an APC function accepted `cache_type`, it is simply ignored by the backward compatible version, and omitted from the prototype for the APCu version.

Warning

As of PHP 8.0.0, apcu-bc is no longer supported.

> Note: On Windows, APCu 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 .

APCu sources can be found » here.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Although the default APCu settings are fine for many installations, serious users should consider tuning the following parameters.

There is one decision to be made configuring APCu. How much memory is going to be allocated to APCu. The ini directive that controls this is `apc.shm_size` Read the sections on this 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 APCu. If GD is enabled in PHP, it will even display some interesting graphs.

If APCu 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 evict entries to free up memory. During eviction, if `apc.ttl` was specified, APCu will first attempt to remove expired entries, i.e. entries whose TTL has either expired, or entries that have no TTL set and haven't been accessed in the last `apc.ttl` seconds. If `apc.ttl` was not set, or removing expired entries did not free up enough space, APCu will clear the entire cache.

The number of evictions should be minimal 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 APCu.

When APCu is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APCu 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 recommended because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.

APCu configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
apc.enabled | 1 | `INI_SYSTEM` |
apc.shm_segments | 1 | `INI_SYSTEM` |
apc.shm_size | "32M" | `INI_SYSTEM` |
apc.entries_hint | 512 * apc.shm_size | `INI_SYSTEM` | Prior to APcu 5.1.25, the default was 4096
apc.ttl | 0 | `INI_SYSTEM` |
apc.gc_ttl | 3600 | `INI_SYSTEM` |
apc.mmap_file_mask | NULL | `INI_SYSTEM` |
apc.slam_defense | 0 | `INI_SYSTEM` |
apc.enable_cli | 0 | `INI_SYSTEM` |
apc.use_request_time | 0 | `INI_ALL` | Prior to APCu 5.1.19, the default was `1`.
apc.serializer | "php" | `INI_SYSTEM` | Prior to APCu 5.1.15, the default was `"default"`.
apc.coredump_unmap | 0 | `INI_SYSTEM` |
apc.preload_path | NULL | `INI_SYSTEM` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`apc.enabled` bool
  `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` int
  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` string
  The size of each shared memory segment given by a shorthand notation as described in this FAQ. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
`apc.entries_hint` int
  A "hint" about the number of distinct variables that might be stored. Set to zero or omit if not sure.
`apc.ttl` int
  Consider cache entries without an explicit TTL to be expired if they have not been accessed in this many seconds. Effectively, this allows such entries to be removed opportunistically during a cache insert, or prior to a full expunge. Note that because removal is opportunistic, entries can still be readable even if they are older than `apc.ttl` seconds. This setting has no effect on cache entries that have an explicit TTL specified.
`apc.gc_ttl` int
  The number of seconds that a cache entry may remain on the garbage-collection list after being removed or invalidated. Entries are eligible for removal if their reference count is zero, or they exceed this time limit. If set to `0`, time-based cleanup is disabled, and entries are only removed when their reference count drops to zero.
`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 `X`s). 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` bool
  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. Setting `apc.slam_defense` to `1` can help prevent multiple processes from caching the same file simultaneously by introducing a probability mechanism. If the same key is attempted to be cached within a short period by different processes, it skips the caching for the current process to mitigate potential cache slams.
`apc.enable_cli` int
  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.serializer` string
  Used to configure APC to use a third party serializer.
`apc.coredump_unmap` bool
  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.
  Warning

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

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

`APC_ITER_ALL` (int)
`APC_ITER_ATIME` (int)
`APC_ITER_CTIME` (int)
`APC_ITER_DEVICE` (int)
`APC_ITER_DTIME` (int)
`APC_ITER_FILENAME` (int)
`APC_ITER_INODE` (int)
`APC_ITER_KEY` (int)
`APC_ITER_MD5` (int)
`APC_ITER_MEM_SIZE` (int)
`APC_ITER_MTIME` (int)
`APC_ITER_NONE` (int)
`APC_ITER_NUM_HITS` (int)
`APC_ITER_REFCOUNT` (int)
`APC_ITER_TTL` (int)
`APC_ITER_TYPE` (int)
`APC_ITER_VALUE` (int)
`APC_LIST_ACTIVE` (int)
`APC_LIST_DELETED` (int)

# APCu Functions

# apcu_add

(PECL apcu >= 4.0.0)

apcu_add — Cache a new variable in the data store

### Description

apcu_add(string `$key`, mixed `$var`, int `$ttl` = 0): bool
apcu_add(array `$values`, mixed `$unused` = NULL, int `$ttl` = 0): array

Caches a variable in the data store, only if it's not already stored.

> Note: Unlike many other mechanisms in PHP, variables stored using apcu_add() will persist between requests (until the value is removed from the cache).

### Parameters

`key`
  Store the variable using this name. `key`s are cache-unique, so attempting to use apcu_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 apcu_add() and apcu_store().)
`var`
  The 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.).
`values`
  Names in key, variables in value.

### Return Values

Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys.

### Examples

Example #1 A apcu_add() example

`<?php
$bar = 'BAR';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
?>`

The above example will output:

    string(3) "BAR"
    string(3) "BAR"

### See Also

- apcu_store() - Cache a variable in the data store
- apcu_fetch() - Fetch a stored variable from the cache
- apcu_delete() - Removes a stored variable from the cache

# apcu_cache_info

(PECL apcu >= 4.0.0)

apcu_cache_info — Retrieves cached information from APCu's data store

### Description

apcu_cache_info(bool `$limited` = `false`): array|false

Retrieves cached information and meta-data from APC's data store.

### Parameters

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

### Return Values

Array of cached data (and meta-data) or `false` on failure

> Note: apcu_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

### Changelog

Version | Description
--- | ---
PECL apcu 3.0.11 | The `limited` parameter was introduced.
PECL apcu 3.0.16 | The "`filehits`" option for the `cache_type` parameter was introduced.

### Examples

Example #1 A apcu_cache_info() example

`<?php
print_r(apcu_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/apcu_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)
    )

### See Also

- APCu configuration directives
- APCUIterator::getTotalSize() - Get total cache size
- APCUIterator::getTotalHits() - Get total cache hits
- APCUIterator::getTotalCount() - Get total count

# apcu_cas

(PECL apcu >= 4.0.0)

apcu_cas — Updates an old value with a new value

### Description

apcu_cas(string `$key`, int `$old`, int `$new`): bool

apcu_cas() updates an already existing integer value if the `old` parameter matches the currently stored value with the value of the `new` parameter.

### Parameters

`key`
  The key of the value being updated.
`old`
  The old value (the value currently stored).
`new`
  The new value to update to.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 apcu_cas() example

`<?php
apcu_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apcu_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apcu_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL;
echo '$f__bar == 1 ? 2 : 1 = ', (apcu_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
apcu_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apcu_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;
echo '$foobar = ', apcu_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

### See Also

- apcu_dec() - Decrease a stored number
- apcu_store() - Cache a variable in the data store

# apcu_clear_cache

(PECL apcu >= 4.0.0)

apcu_clear_cache — Clears the APCu cache

### Description

apcu_clear_cache(): bool

Clears the cache.

### Parameters

This function has no parameters.

### Return Values

Returns `true` always

### See Also

- apcu_cache_info() - Retrieves cached information from APCu's data store

# apcu_dec

(PECL apcu >= 4.0.0)

apcu_dec — Decrease a stored number

### Description

apcu_dec(
string `$key`,
int `$step` = 1,
bool `&$success` = ?,
int `$ttl` = 0
): int|false

Decreases a stored integer value.

### Parameters

`key`
  The key of the value being decreased.
`step`
  The step, or value to decrease.
`success`
  Optionally pass the success or fail boolean value to this referenced variable.
`ttl`
  TTL to use if the operation inserts a new value (rather than decrementing an existing one).

### Return Values

Returns the current value of `key`'s value on success, or `false` on failure

### Examples

Example #1 apcu_dec() example

`<?php
echo "Let's do something with success", PHP_EOL;
apcu_store('anumber', 42);
echo apcu_fetch('anumber'), PHP_EOL;
echo apcu_dec('anumber'), PHP_EOL;
echo apcu_dec('anumber', 10), PHP_EOL;
echo apcu_dec('anumber', 10, $success), PHP_EOL;
var_dump($success);
echo "Now, let's fail", PHP_EOL, PHP_EOL;
apcu_store('astring', 'foo');
$ret = apcu_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)

### See Also

- apcu_inc() - Increase a stored number

# apcu_delete

(PECL apcu >= 4.0.0)

apcu_delete — Removes a stored variable from the cache

### Description

apcu_delete(mixed `$key`): mixed

Removes a stored variable from the cache.

### Parameters

`key`
  A `key` used to store the value as a string for a single key, or as an array of strings for several keys, or as an APCUIterator object.

### Return Values

If `key` is an array, an indexed array of the keys is returned. Otherwise `true` is returned on success, or `false` on failure.

### Examples

Example #1 A apcu_delete() example

`<?php
$bar = 'BAR';
apcu_store('foo', $bar);
apcu_delete('foo');
// this is obviously useless in this form
// Alternatively delete multiple keys.
apcu_delete(['foo', 'bar', 'baz']);
// Or use an Iterator with a regular expression.
apcu_delete(new APCUIterator('#^myprefix_#'));
?>`

### See Also

- apcu_store() - Cache a variable in the data store
- apcu_fetch() - Fetch a stored variable from the cache
- apcu_clear_cache() - Clears the APCu cache
- APCUIterator

# apcu_enabled

(PECL apcu >= 4.0.3)

apcu_enabled — Whether APCu is usable in the current environment

### Description

apcu_enabled(): bool

Returns whether APCu is usable in the current environment.

### Parameters

This function has no parameters.

### Return Values

Returns `true` when APCu is usable in the current environment, `false` otherwise.

# apcu_entry

(PECL apcu >= 5.1.0)

apcu_entry — Atomically fetch or generate a cache entry

### Description

apcu_entry(string `$key`, callable `$callback`, int `$ttl` = 0): mixed

Atomically attempts to find `key` in the cache, if it cannot be found `callback` is called, passing `key` as the only argument. The return value of the call is then cached with the optionally specified `ttl`, and returned.

> Note: When control enters apcu_entry() the lock for the cache is acquired exclusively, it is released when control leaves apcu_entry(): In effect, this turns the body of `callback` into a critical section, disallowing two processes from executing the same code paths concurrently. In addition, it prohibits the concurrent execution of any other APCu functions, since they will acquire the same lock.

Warning

The only APCu function that can be called safely by `callback` is apcu_entry().

### Parameters

`key`
  Identity of cache entry
`callback`
  A callable that accepts `key` as the only argument and returns the value to cache.
`ttl`
  Time To Live; store the `callback`'s return value in the cache for `ttl` seconds. After the `ttl` has passed, the stored entry 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.).

### Return Values

Returns the cached value

### Examples

Example #1 An apcu_entry() example

`<?php
$config = apcu_entry("config", function($key) {
return [
"fruit" => apcu_entry("config.fruit", function($key){
return [
"apples",
"pears"
];
}),
"people" => apcu_entry("config.people", function($key){
return [
"bob",
"joe",
"niki"
];
})
];
});
var_dump($config);
?>`

The above example will output:

    array(2) {
      ["fruit"]=>
      array(2) {
        [0]=>
        string(6) "apples"
        [1]=>
        string(5) "pears"
      }
      ["people"]=>
      array(3) {
        [0]=>
        string(3) "bob"
        [1]=>
        string(3) "joe"
        [2]=>
        string(4) "niki"
      }
    }

### See Also

- apcu_store() - Cache a variable in the data store
- apcu_fetch() - Fetch a stored variable from the cache
- apcu_delete() - Removes a stored variable from the cache

# apcu_exists

(PECL apcu >= 4.0.0)

apcu_exists — Checks if entry exists

### Description

apcu_exists(string|array `$keys`): bool|array

Checks if one or more APCu entries exist.

### Parameters

`keys`
  A string, or an array of strings, that contain keys.

### Return Values

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.

### Examples

Example #1 apcu_exists() example

`<?php
$fruit = 'apple';
$veggie = 'carrot';
apcu_store('foo', $fruit);
apcu_store('bar', $veggie);
if (apcu_exists('foo')) {
echo "Foo exists: ";
echo apcu_fetch('foo');
} else {
echo "Foo does not exist";
}
echo PHP_EOL;
if (apcu_exists('baz')) {
echo "Baz exists.";
} else {
echo "Baz does not exist";
}
echo PHP_EOL;
$ret = apcu_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)
    }

### See Also

- apcu_cache_info() - Retrieves cached information from APCu's data store
- apcu_fetch() - Fetch a stored variable from the cache

# apcu_fetch

(PECL apcu >= 4.0.0)

apcu_fetch — Fetch a stored variable from the cache

### Description

apcu_fetch(mixed `$key`, bool `&$success` = ?): mixed

Fetches an entry from the cache.

### Parameters

`key`
  The `key` used to store the value (with apcu_store()). If an array is passed then each element is fetched and returned.
`success`
  Set to `true` in success and `false` in failure.

### Return Values

The stored variable or array of variables on success; `false` on failure

### Changelog

Version | Description
--- | ---
PECL apcu 3.0.17 | The `success` parameter was added.

### Examples

Example #1 A apcu_fetch() example

`<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>`

The above example will output:

    string(3) "BAR"

### See Also

- apcu_store() - Cache a variable in the data store
- apcu_delete() - Removes a stored variable from the cache
- APCUIterator

# apcu_inc

(PECL apcu >= 4.0.0)

apcu_inc — Increase a stored number

### Description

apcu_inc(
string `$key`,
int `$step` = 1,
bool `&$success` = ?,
int `$ttl` = 0
): int|false

Increases a stored number.

### Parameters

`key`
  The key of the value being increased.
`step`
  The step, or value to increase.
`success`
  Optionally pass the success or fail boolean value to this referenced variable.
`ttl`
  TTL to use if the operation inserts a new value (rather than incrementing an existing one).

### Return Values

Returns the current value of `key`'s value on success, or `false` on failure

### Examples

Example #1 apcu_inc() example

`<?php
echo "Let's do something with success", PHP_EOL;
apcu_store('anumber', 42);
echo apcu_fetch('anumber'), PHP_EOL;
echo apcu_inc('anumber'), PHP_EOL;
echo apcu_inc('anumber', 10), PHP_EOL;
echo apcu_inc('anumber', 10, $success), PHP_EOL;
var_dump($success);
echo "Now, let's fail", PHP_EOL, PHP_EOL;
apcu_store('astring', 'foo');
$ret = apcu_inc('astring', 1, $fail);
var_dump($ret);
var_dump($fail);
?>`

The above example will output something similar to:

    Let's do something with success
    42
    43
    53
    63
    bool(true)
    Now, let's fail

    bool(false)
    bool(false)

### See Also

- apcu_dec() - Decrease a stored number

# apcu_key_info

(No version information available, might only be in Git)

apcu_key_info — Get detailed information about the cache key

### Description

apcu_key_info(string `$key`): ?array

Get detailed information about the cache key

### Parameters

`key`
  Get detailed information about the cache key

### Return Values

An array containing the detailed information about the cache key, or `null` if the key does not exist.

### Examples

Example #1 A apcu_key_info() example

`<?php
apcu_add('a','b');
var_dump(apcu_key_info('a'));
?>`

The above example will output:

    array(7) {
      ["hits"]=>
      int(0)
      ["access_time"]=>
      int(1606701783)
      ["mtime"]=>
      int(1606701783)
      ["creation_time"]=>
      int(1606701783)
      ["deletion_time"]=>
      int(0)
      ["ttl"]=>
      int(0)
      ["refs"]=>
      int(0)
    }

### See Also

- apcu_store() - Cache a variable in the data store
- apcu_fetch() - Fetch a stored variable from the cache
- apcu_delete() - Removes a stored variable from the cache

# apcu_sma_info

(PECL apcu >= 4.0.0)

apcu_sma_info — Retrieves APCu Shared Memory Allocation information

### Description

apcu_sma_info(bool `$limited` = `false`): array|false

Retrieves APCu Shared Memory Allocation information.

### Parameters

`limited`
  When set to `false` (default) apcu_sma_info() will return a detailed information about each segment.

### Return Values

Array of Shared Memory Allocation data; `false` on failure.

### Examples

Example #1 A apcu_sma_info() example

`<?php
print_r(apcu_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
                            )

                    )

            )

    )

### See Also

- APCu configuration directives

# apcu_store

(PECL apcu >= 4.0.0)

apcu_store — Cache a variable in the data store

### Description

apcu_store(string `$key`, mixed `$var`, int `$ttl` = 0): bool
apcu_store(array `$values`, mixed `$unused` = NULL, int `$ttl` = 0): array

Cache a variable in the data store.

> Note: Unlike many other mechanisms in PHP, variables stored using apcu_store() will persist between requests (until the value is removed from the cache).

### Parameters

`key`
  Store the variable using this name. `key`s are cache-unique, so storing a second value with the same `key` will overwrite the original value.
`var`
  The 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.).
`values`
  Names in key, variables in value.

### Return Values

Returns `true` on success or `false` on failure. Second syntax returns array with error keys.

### Examples

Example #1 A apcu_store() example

`<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>`

The above example will output:

    string(3) "BAR"

### See Also

- apcu_add() - Cache a new variable in the data store
- apcu_fetch() - Fetch a stored variable from the cache
- apcu_delete() - Removes a stored variable from the cache

## Table of Contents

- apcu_add — Cache a new variable in the data store
- apcu_cache_info — Retrieves cached information from APCu's data store
- apcu_cas — Updates an old value with a new value
- apcu_clear_cache — Clears the APCu cache
- apcu_dec — Decrease a stored number
- apcu_delete — Removes a stored variable from the cache
- apcu_enabled — Whether APCu is usable in the current environment
- apcu_entry — Atomically fetch or generate a cache entry
- apcu_exists — Checks if entry exists
- apcu_fetch — Fetch a stored variable from the cache
- apcu_inc — Increase a stored number
- apcu_key_info — Get detailed information about the cache key
- apcu_sma_info — Retrieves APCu Shared Memory Allocation information
- apcu_store — Cache a variable in the data store

# The APCUIterator class

(PECL apcu >= 5.0.0)

## Introduction

The APCUIterator class makes it easier to iterate over large APCu 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.

## Class synopsis

class APCUIterator implements Iterator {
/* Methods */
public __construct(
array|string|null `$search` = `null`,
int `$format` = APC_ITER_ALL,
int `$chunk_size` = 100,
int `$list` = APC_LIST_ACTIVE
)
public current(): mixed
public getTotalCount(): int
public getTotalHits(): int
public getTotalSize(): int
public key(): string
public next(): bool
public rewind(): void
public valid(): bool
}

# APCUIterator::__construct

(PECL apcu >= 5.0.0)

APCUIterator::__construct — Constructs an APCUIterator iterator object

### Description

public APCUIterator::__construct(
array|string|null `$search` = `null`,
int `$format` = APC_ITER_ALL,
int `$chunk_size` = 100,
int `$list` = APC_LIST_ACTIVE
)

Constructs an APCUIterator object.

### Parameters

`search`
  Either a PCRE regular expression that matches against APCu key names, given as a string. Or an array of strings with APCu key names. Or, optionally `null` to skip the search.
`format`
  The desired format, as configured with one or more of the APC_ITER_* constants.
`chunk_size`
  The 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`.

### Examples

Example #1 A APCUIterator::__construct() example

`<?php
foreach (new APCUIterator('/^counter\./') as $counter) {
echo "$counter[key]: $counter[value]\n";
apc_dec($counter['key'], $counter['value']);
}
?>`

### See Also

- apcu_exists() - Checks if entry exists
- apcu_cache_info() - Retrieves cached information from APCu's data store

# APCUIterator::current

(PECL apcu >= 5.0.0)

APCUIterator::current — Get current item

### Description

public APCUIterator::current(): mixed

Gets the current item from the APCUIterator stack.

### Parameters

This function has no parameters.

### Return Values

Returns the current item on success, or `false` if no more items or exist, or on failure.

### See Also

- APCUIterator::next() - Move pointer to next item
- Iterator::current() - Return the current element

# APCUIterator::getTotalCount

(PECL apcu >= 5.0.0)

APCUIterator::getTotalCount — Get total count

### Description

public APCUIterator::getTotalCount(): int

Get the total count.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The total count.

### See Also

- APCUIterator::getTotalHits() - Get total cache hits
- APCUIterator::getTotalSize() - Get total cache size
- apcu_cache_info() - Retrieves cached information from APCu's data store

# APCUIterator::getTotalHits

(PECL apcu >= 5.0.0)

APCUIterator::getTotalHits — Get total cache hits

### Description

public APCUIterator::getTotalHits(): int

Gets the total number of cache hits.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The number of hits on success, or `false` on failure.

### See Also

- APCUIterator::getTotalCount() - Get total count
- APCUIterator::getTotalSize() - Get total cache size
- apcu_cache_info() - Retrieves cached information from APCu's data store

# APCUIterator::getTotalSize

(PECL apcu >= 5.0.0)

APCUIterator::getTotalSize — Get total cache size

### Description

public APCUIterator::getTotalSize(): int

Gets the total cache size.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The total cache size.

### See Also

- APCUIterator::getTotalCount() - Get total count
- APCUIterator::getTotalHits() - Get total cache hits
- apc_cache_info()

# APCUIterator::key

(PECL apcu >= 5.0.0)

APCUIterator::key — Get iterator key

### Description

public APCUIterator::key(): string

Gets the current iterator key.

### Parameters

This function has no parameters.

### Return Values

Returns the key on success, or `false` upon failure.

### See Also

- APCUIterator::current() - Get current item
- Iterator::key() - Return the key of the current element

# APCUIterator::next

(PECL apcu >= 5.0.0)

APCUIterator::next — Move pointer to next item

### Description

public APCUIterator::next(): bool

Moves the iterator pointer to the next element.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- APCUIterator::current() - Get current item
- APCUIterator::rewind() - Rewinds iterator
- Iterator::next() - Move forward to next element

# APCUIterator::rewind

(PECL apcu >= 5.0.0)

APCUIterator::rewind — Rewinds iterator

### Description

public APCUIterator::rewind(): void

Rewinds back the iterator to the first element.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- APCUIterator::next() - Move pointer to next item
- Iterator::next() - Move forward to next element

# APCUIterator::valid

(PECL apcu >= 5.0.0)

APCUIterator::valid — Checks if current position is valid

### Description

public APCUIterator::valid(): bool

Checks if the current iterator position is valid.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the current iterator position is valid, otherwise `false`.

### See Also

- APCUIterator::current() - Get current item
- Iterator::valid() - Checks if current position is valid

## Table of Contents

- APCUIterator::__construct — Constructs an APCUIterator iterator object
- APCUIterator::current — Get current item
- APCUIterator::getTotalCount — Get total count
- APCUIterator::getTotalHits — Get total cache hits
- APCUIterator::getTotalSize — Get total cache size
- APCUIterator::key — Get iterator key
- APCUIterator::next — Move pointer to next item
- APCUIterator::rewind — Rewinds iterator
- APCUIterator::valid — Checks if current position is valid

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Predefined Constants
- APCu Functions
  - apcu_add — Cache a new variable in the data store
  - apcu_cache_info — Retrieves cached information from APCu's data store
  - apcu_cas — Updates an old value with a new value
  - apcu_clear_cache — Clears the APCu cache
  - apcu_dec — Decrease a stored number
  - apcu_delete — Removes a stored variable from the cache
  - apcu_enabled — Whether APCu is usable in the current environment
  - apcu_entry — Atomically fetch or generate a cache entry
  - apcu_exists — Checks if entry exists
  - apcu_fetch — Fetch a stored variable from the cache
  - apcu_inc — Increase a stored number
  - apcu_key_info — Get detailed information about the cache key
  - apcu_sma_info — Retrieves APCu Shared Memory Allocation information
  - apcu_store — Cache a variable in the data store
- APCUIterator — The APCUIterator class
  - APCUIterator::__construct — Constructs an APCUIterator iterator object
  - APCUIterator::current — Get current item
  - APCUIterator::getTotalCount — Get total count
  - APCUIterator::getTotalHits — Get total cache hits
  - APCUIterator::getTotalSize — Get total cache size
  - APCUIterator::key — Get iterator key
  - APCUIterator::next — Move pointer to next item
  - APCUIterator::rewind — Rewinds iterator
  - APCUIterator::valid — Checks if current position is valid

# Componere

# Introduction

Componere (latin, English: compose) targets production environments and provides an API for composition of classes, monkey patching, and casting.

##### Composition:

Componere\Definition is used to define (or redefine) a class at runtime; The class can then be registered, and in the case of redefinition it replaces the original class for as long as the Componere\Definition exists.

public Componere\Definition::__construct(string `$name`)
public Componere\Definition::__construct(string `$name`, string `$parent`)
public Componere\Definition::__construct(string `$name`, array `$interfaces`)
public Componere\Definition::__construct(string `$name`, string `$parent`, array `$interfaces`)

##### Patching:

Componere\Patch is used to change the class of a specific instance of an object at runtime; Upon application the patch will remain applied for as long as the Componere\Patch exists, and can be reverted explicitly.

public Componere\Patch::__construct(object `$instance`)
public Componere\Patch::__construct(object `$instance`, array `$interfaces`)

##### Casting:

Componere\ casting functions can cast among user defined compatible types; Where compatible means Type is sub or super to the type of `object`.

Componere\cast(string `$type`, object `$object`): object
Componere\cast_by_ref(string `$type`, object `$object`): object

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

Reflection is required

## Installation

Componere source and releases are available on » github

# The Componere\Abstract\Definition class

(Componere 2 >= 2.1.0)

## Introduction

This final abstract represents a class entry, and should not be used by the programmer.

## Class synopsis

final abstract class Componere\Abstract\Definition {
/* Methods */
public addInterface(string `$interface`): Definition
public addMethod(string `$name`, Componere\Method `$method`): Definition
public addTrait(string `$trait`): Definition
public getReflector(): ReflectionClass
}

# Componere\Abstract\Definition::addInterface

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addInterface — Add Interface

### Description

public Componere\Abstract\Definition::addInterface(string `$interface`): Definition

Shall implement the given interface on the current definition

### Parameters

`interface`
  The case insensitive name of an interface

### Return Values

The current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

# Componere\Abstract\Definition::addMethod

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addMethod — Add Method

### Description

public Componere\Abstract\Definition::addMethod(string `$name`, Componere\Method `$method`): Definition

Shall create or override a method on the current definition.

### Parameters

`name`
  The case insensitive name for method
`method`
  Componere\Method not previously added to another Definition

### Return Values

The current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if Method was added to another Definition

# Componere\Abstract\Definition::addTrait

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addTrait — Add Trait

### Description

public Componere\Abstract\Definition::addTrait(string `$trait`): Definition

Shall use the given trait for the current definition

### Parameters

`trait`
  The case insensitive name of a trait

### Return Values

The current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

# Componere\Abstract\Definition::getReflector

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::getReflector — Reflection

### Description

public Componere\Abstract\Definition::getReflector(): ReflectionClass

Shall create or return a ReflectionClass

### Return Values

A ReflectionClass for the current definition (cached)

## Table of Contents

- Componere\Abstract\Definition::addInterface — Add Interface
- Componere\Abstract\Definition::addMethod — Add Method
- Componere\Abstract\Definition::addTrait — Add Trait
- Componere\Abstract\Definition::getReflector — Reflection

# The Componere\Definition class

(Componere 2 >= 2.1.0)

## Introduction

The Definition class allows the programmer to build and register a type at runtime.

Should a Definition replace an existing class, the existing class will be restored when the Definition is destroyed.

## Class synopsis

final class Componere\Definition extends Componere\Abstract\Definition {
/* Constructors */
public __construct(string `$name`)
public __construct(string `$name`, string `$parent`)
public __construct(string `$name`, array `$interfaces`)
public __construct(string `$name`, string `$parent`, array `$interfaces`)
/* Methods */
public addConstant(string `$name`, Componere\Value `$value`): Definition
public addProperty(string `$name`, Componere\Value `$value`): Definition
public register(): void
public isRegistered(): bool
public getClosure(string `$name`): Closure
public getClosures(): array
/* Inherited methods */
public Componere\Abstract\Definition::addInterface(string `$interface`): Definition
public Componere\Abstract\Definition::addMethod(string `$name`, Componere\Method `$method`): Definition
public Componere\Abstract\Definition::addTrait(string `$trait`): Definition
public Componere\Abstract\Definition::getReflector(): ReflectionClass
}

# Componere\Definition::__construct

(Componere 2 >= 2.1.0)

Componere\Definition::__construct — Definition Construction

### Description

public Componere\Definition::__construct(string `$name`)
public Componere\Definition::__construct(string `$name`, string `$parent`)
public Componere\Definition::__construct(string `$name`, array `$interfaces`)
public Componere\Definition::__construct(string `$name`, string `$parent`, array `$interfaces`)

### Parameters

`name`
  A case insensitive class name
`parent`
  A case insensitive class name
`interfaces`
  An array of case insensitive class names

### Exceptions

Warning

Shall throw InvalidArgumentException if an attempt is made to replace an internal class

Warning

Shall throw InvalidArgumentException if an attempt is made to replace an interface

Warning

Shall throw InvalidArgumentException if an attempt is made to replace a trait

Warning

Shall throw RuntimeException if a class in `interfaces` cannot be found

Warning

Shall throw RuntimeException if a class in `interfaces` is not an interface

# Componere\Definition::addConstant

(Componere 2 >= 2.1.0)

Componere\Definition::addConstant — Add Constant

### Description

public Componere\Definition::addConstant(string `$name`, Componere\Value `$value`): Definition

Shall declare a class constant on the current Definition

### Parameters

`name`
  The case sensitive name for the constant
`value`
  The Value for the constant, must not be undefined or static

### Return Values

The current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if `name` is already declared as a constant

Warning

Shall throw RuntimeException if `value` is static

Warning

Shall throw RuntimeException if `value` is undefined

# Componere\Definition::addProperty

(Componere 2 >= 2.1.0)

Componere\Definition::addProperty — Add Property

### Description

public Componere\Definition::addProperty(string `$name`, Componere\Value `$value`): Definition

Shall declare a class property on the current Definition

### Parameters

`name`
  The case sensitive name for the property
`value`
  The default Value for the property

### Return Values

The current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if `name` is already declared as a property

# Componere\Definition::register

(Componere 2 >= 2.1.0)

Componere\Definition::register — Registration

### Description

public Componere\Definition::register(): void

Shall register the current Definition

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

# Componere\Definition::isRegistered

(Componere 2 >= 2.1.0)

Componere\Definition::isRegistered — State Detection

### Description

public Componere\Definition::isRegistered(): bool

Shall detect the registration state of this Definition

### Return Values

Shall return true if this Definition is registered

# Componere\Definition::getClosure

(Componere 2 >= 2.1.0)

Componere\Definition::getClosure — Get Closure

### Description

public Componere\Definition::getClosure(string `$name`): Closure

Shall return a Closure for the method specified by name

### Parameters

`name`
  The case insensitive name of the method

### Return Values

A Closure bound to the correct scope

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if `name` could not be found

# Componere\Definition::getClosures

(Componere 2 >= 2.1.0)

Componere\Definition::getClosures — Get Closures

### Description

public Componere\Definition::getClosures(): array

Shall return an array of Closures

### Return Values

Shall return all methods as an array of Closure objects bound to the correct scope

### Exceptions

Warning

Shall throw RuntimeException if Definition was registered

## Table of Contents

- Componere\Definition::__construct — Definition Construction
- Componere\Definition::addConstant — Add Constant
- Componere\Definition::addProperty — Add Property
- Componere\Definition::register — Registration
- Componere\Definition::isRegistered — State Detection
- Componere\Definition::getClosure — Get Closure
- Componere\Definition::getClosures — Get Closures

# The Componere\Patch class

(Componere 2 >= 2.1.0)

## Introduction

The Patch class allows the programmer to change the type of an instance at runtime without registering a new Definition

When a Patch is destroyed it is reverted, so that instances that were patched during the lifetime of the Patch are restored to their formal type.

## Class synopsis

final class Componere\Patch extends Componere\Abstract\Definition {
/* Constructors */
public __construct(object `$instance`)
public __construct(object `$instance`, array `$interfaces`)
/* Methods */
public apply(): void
public revert(): void
public isApplied(): bool
public derive(object `$instance`): Patch
public getClosure(string `$name`): Closure
public getClosures(): array
/* Inherited methods */
public Componere\Abstract\Definition::addInterface(string `$interface`): Definition
public Componere\Abstract\Definition::addMethod(string `$name`, Componere\Method `$method`): Definition
public Componere\Abstract\Definition::addTrait(string `$trait`): Definition
public Componere\Abstract\Definition::getReflector(): ReflectionClass
}

# Componere\Patch::__construct

(Componere 2 >= 2.1.0)

Componere\Patch::__construct — Patch Construction

### Description

public Componere\Patch::__construct(object `$instance`)
public Componere\Patch::__construct(object `$instance`, array `$interfaces`)

### Parameters

`instance`
  The target for this Patch
`interfaces`
  A case insensitive array of class names

### Exceptions

Warning

Shall throw RuntimeException if a class in `interfaces` cannot be found

Warning

Shall throw RuntimeException if a class in `interfaces` is not an interface

# Componere\Patch::apply

(Componere 2 >= 2.1.0)

Componere\Patch::apply — Application

### Description

public Componere\Patch::apply(): void

Shall apply the current patch

# Componere\Patch::revert

(Componere 2 >= 2.1.0)

Componere\Patch::revert — Reversal

### Description

public Componere\Patch::revert(): void

Shall revert the current patch

# Componere\Patch::isApplied

(Componere 2 >= 2.1.0)

Componere\Patch::isApplied — State Detection

### Description

public Componere\Patch::isApplied(): bool

# Componere\Patch::derive

(Componere 2 >= 2.1.1)

Componere\Patch::derive — Patch Derivation

### Description

public Componere\Patch::derive(object `$instance`): Patch

Shall derive a Patch for the given `instance`

### Parameters

`instance`
  The target for the derived Patch

### Return Values

Patch for `instance` derived from the current Patch

### Exceptions

Warning

Shall throw InvalidArgumentException if `instance` is not compatible

# Componere\Patch::getClosure

(Componere 2 >= 2.1.0)

Componere\Patch::getClosure — Get Closure

### Description

public Componere\Patch::getClosure(string `$name`): Closure

Shall return a Closure for the method specified by name

### Parameters

`name`
  The case insensitive name of the method

### Return Values

A Closure bound to the correct scope and object

### Exceptions

Warning

Shall throw RuntimeException if `name` could not be found

# Componere\Patch::getClosures

(Componere 2 >= 2.1.0)

Componere\Patch::getClosures — Get Closures

### Description

public Componere\Patch::getClosures(): array

Shall return an array of Closures

### Return Values

Shall return all methods as an array of Closure objects bound to the correct scope and object

## Table of Contents

- Componere\Patch::__construct — Patch Construction
- Componere\Patch::apply — Application
- Componere\Patch::revert — Reversal
- Componere\Patch::isApplied — State Detection
- Componere\Patch::derive — Patch Derivation
- Componere\Patch::getClosure — Get Closure
- Componere\Patch::getClosures — Get Closures

# The Componere\Method class

(Componere 2 >= 2.1.0)

## Introduction

A Method represents a function with modifiable accessibility flags

## Class synopsis

final class Componere\Method {
/* Constructor */
public __construct(Closure `$closure`)
/* Methods */
public setPrivate(): Method
public setProtected(): Method
public setStatic(): Method
public getReflector(): ReflectionMethod
}

# Componere\Method::__construct

(Componere 2 >= 2.1.0)

Componere\Method::__construct — Method Construction

### Description

public Componere\Method::__construct(Closure `$closure`)

### Parameters

`closure`

# Componere\Method::setPrivate

(Componere 2 >= 2.1.0)

Componere\Method::setPrivate — Accessibility Modification

### Description

public Componere\Method::setPrivate(): Method

### Return Values

The current Method

### Exceptions

Warning

Shall throw RuntimeException if access level was previously set

# Componere\Method::setProtected

(Componere 2 >= 2.1.0)

Componere\Method::setProtected — Accessibility Modification

### Description

public Componere\Method::setProtected(): Method

### Return Values

The current Method

### Exceptions

Warning

Shall throw RuntimeException if access level was previously set

# Componere\Method::setStatic

(Componere 2 >= 2.1.0)

Componere\Method::setStatic — Accessibility Modification

### Description

public Componere\Method::setStatic(): Method

### Return Values

The current Method

# Componere\Method::getReflector

(Componere 2 >= 2.1.0)

Componere\Method::getReflector — Reflection

### Description

public Componere\Method::getReflector(): ReflectionMethod

Shall create or return a ReflectionMethod

### Return Values

A ReflectionMethod for the current method (cached)

## Table of Contents

- Componere\Method::__construct — Method Construction
- Componere\Method::setPrivate — Accessibility Modification
- Componere\Method::setProtected — Accessibility Modification
- Componere\Method::setStatic — Accessibility Modification
- Componere\Method::getReflector — Reflection

# The Componere\Value class

(Componere 2 >= 2.1.0)

## Introduction

A Value represents a PHP variable of all types, including undefined

## Class synopsis

final class Componere\Value {
/* Constructor */
public __construct(mixed `$default` = ?)
/* Methods */
public setPrivate(): Value
public setProtected(): Value
public setStatic(): Value
public isPrivate(): bool
public isProtected(): bool
public isStatic(): bool
public hasDefault(): bool
}

# Componere\Value::__construct

(Componere 2 >= 2.1.0)

Componere\Value::__construct — Value Construction

### Description

public Componere\Value::__construct(mixed `$default` = ?)

### Parameters

`default`

### Exceptions

Warning

Shall throw InvalidArgumentException if `default` does not have a suitable value

# Componere\Value::setPrivate

(Componere 2 >= 2.1.0)

Componere\Value::setPrivate — Accessibility Modification

### Description

public Componere\Value::setPrivate(): Value

### Return Values

The current Value

### Exceptions

Warning

Shall throw RuntimeException if access level was previously set

# Componere\Value::setProtected

(Componere 2 >= 2.1.0)

Componere\Value::setProtected — Accessibility Modification

### Description

public Componere\Value::setProtected(): Value

### Return Values

The current Value

### Exceptions

Warning

Shall throw RuntimeException if access level was previously set

# Componere\Value::setStatic

(Componere 2 >= 2.1.0)

Componere\Value::setStatic — Accessibility Modification

### Description

public Componere\Value::setStatic(): Value

### Return Values

The current Value

# Componere\Value::isPrivate

(Componere 2 >= 2.1.0)

Componere\Value::isPrivate — Accessibility Detection

### Description

public Componere\Value::isPrivate(): bool

# Componere\Value::isProtected

(Componere 2 >= 2.1.0)

Componere\Value::isProtected — Accessibility Detection

### Description

public Componere\Value::isProtected(): bool

# Componere\Value::isStatic

(Componere 2 >= 2.1.0)

Componere\Value::isStatic — Accessibility Detection

### Description

public Componere\Value::isStatic(): bool

# Componere\Value::hasDefault

(Componere 2 >= 2.1.0)

Componere\Value::hasDefault — Value Interaction

### Description

public Componere\Value::hasDefault(): bool

## Table of Contents

- Componere\Value::__construct — Value Construction
- Componere\Value::setPrivate — Accessibility Modification
- Componere\Value::setProtected — Accessibility Modification
- Componere\Value::setStatic — Accessibility Modification
- Componere\Value::isPrivate — Accessibility Detection
- Componere\Value::isProtected — Accessibility Detection
- Componere\Value::isStatic — Accessibility Detection
- Componere\Value::hasDefault — Value Interaction

# Componere Functions

# Componere\cast

(Componere 2 >= 2.1.2)

Componere\cast — Casting

### Description

Componere\cast(string `$type`, object `$object`): object

### Parameters

`type`
  A user defined type
`object`
  An object with a user defined type compatible with Type

### Return Values

An object of type Type, cast from `object`

### Errors/Exceptions

Warning

Shall throw InvalidArgumentException if the type of `object` is or is derived from an internal class

Warning

Shall throw InvalidArgumentException if Type is an interface

Warning

Shall throw InvalidArgumentException if Type is a trait

Warning

Shall throw InvalidArgumentException if Type is an abstract

Warning

Shall throw InvalidArgumentException if Type is not compatible with the type of `object`

### See Also

- Componere\cast_by_ref

# Componere\cast_by_ref

(Componere 2 >= 2.1.2)

Componere\cast_by_ref — Casting

### Description

Componere\cast_by_ref(string `$type`, object `$object`): object

### Parameters

type
  A user defined type
`object`
  An object with a user defined type compatible with Type

### Return Values

An object of type Type, cast from `object`, where members are references to `object` members

### Errors/Exceptions

Warning

Shall throw InvalidArgumentException if the type of `object` is or is derived from an internal class

Warning

Shall throw InvalidArgumentException if Type is an interface

Warning

Shall throw InvalidArgumentException if Type is a trait

Warning

Shall throw InvalidArgumentException if Type is an abstract

Warning

Shall throw InvalidArgumentException if Type is not compatible with the type of `object`

### See Also

- Componere\cast

## Table of Contents

- Componere\cast — Casting
- Componere\cast_by_ref — Casting

- Installing/Configuring
  - Requirements
  - Installation
- Componere\Abstract\Definition — The Componere\Abstract\Definition class
  - Componere\Abstract\Definition::addInterface — Add Interface
  - Componere\Abstract\Definition::addMethod — Add Method
  - Componere\Abstract\Definition::addTrait — Add Trait
  - Componere\Abstract\Definition::getReflector — Reflection
- Componere\Definition — The Componere\Definition class
  - Componere\Definition::__construct — Definition Construction
  - Componere\Definition::addConstant — Add Constant
  - Componere\Definition::addProperty — Add Property
  - Componere\Definition::register — Registration
  - Componere\Definition::isRegistered — State Detection
  - Componere\Definition::getClosure — Get Closure
  - Componere\Definition::getClosures — Get Closures
- Componere\Patch — The Componere\Patch class
  - Componere\Patch::__construct — Patch Construction
  - Componere\Patch::apply — Application
  - Componere\Patch::revert — Reversal
  - Componere\Patch::isApplied — State Detection
  - Componere\Patch::derive — Patch Derivation
  - Componere\Patch::getClosure — Get Closure
  - Componere\Patch::getClosures — Get Closures
- Componere\Method — The Componere\Method class
  - Componere\Method::__construct — Method Construction
  - Componere\Method::setPrivate — Accessibility Modification
  - Componere\Method::setProtected — Accessibility Modification
  - Componere\Method::setStatic — Accessibility Modification
  - Componere\Method::getReflector — Reflection
- Componere\Value — The Componere\Value class
  - Componere\Value::__construct — Value Construction
  - Componere\Value::setPrivate — Accessibility Modification
  - Componere\Value::setProtected — Accessibility Modification
  - Componere\Value::setStatic — Accessibility Modification
  - Componere\Value::isPrivate — Accessibility Detection
  - Componere\Value::isProtected — Accessibility Detection
  - Componere\Value::isStatic — Accessibility Detection
  - Componere\Value::hasDefault — Value Interaction
- Componere Functions
  - Componere\cast — Casting
  - Componere\cast_by_ref — Casting

# Error Handling and Logging

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Runtime Configuration

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Errors and Logging Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
error_reporting | NULL | `INI_ALL` |
display_errors | "1" | `INI_ALL` |
display_startup_errors | "1" | `INI_ALL` | Prior to PHP 8.0.0, the default value was `"0"`.
log_errors | "0" | `INI_ALL` |
log_errors_max_len | "1024" | `INI_ALL` | Had no effect as of PHP 8.0.0, removed as of PHP 8.1.0.
ignore_repeated_errors | "0" | `INI_ALL` |
ignore_repeated_source | "0" | `INI_ALL` |
report_memleaks | "1" | `INI_ALL` |
track_errors | "0" | `INI_ALL` | Deprecated as of PHP 7.2.0, removed as of PHP 8.0.0.
html_errors | "1" | `INI_ALL` |
xmlrpc_errors | "0" | `INI_SYSTEM` |
xmlrpc_error_number | "0" | `INI_ALL` |
docref_root | "" | `INI_ALL` |
docref_ext | "" | `INI_ALL` |
error_prepend_string | NULL | `INI_ALL` |
error_append_string | NULL | `INI_ALL` |
error_log | NULL | `INI_ALL` |
error_log_mode | 0o644 | `INI_ALL` | Available as of PHP 8.2.0
syslog.facility | "LOG_USER" | `INI_SYSTEM` | Available as of PHP 7.3.0.
syslog.filter | "no-ctrl" | `INI_ALL` | Available as of PHP 7.3.0.
syslog.ident | "php" | `INI_SYSTEM` | Available as of PHP 7.3.0.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`error_reporting` int

  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.

  The default value is `E_ALL`.

  Prior to PHP 8.0.0, the default value was: ``E_ALL` & ~`E_NOTICE` & ~`E_STRICT` & ~`E_DEPRECATED``. This means diagnostics of level `E_NOTICE`, `E_STRICT` and `E_DEPRECATED` were not shown.

  > 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 int values are required. And since error levels will be added over time, the maximum value (for `E_ALL`) will likely change. So in place of `E_ALL` consider using a larger value to cover all bit fields from now and well into the future, a numeric value like `2147483647` (includes all errors, not just `E_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`.

  > 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 effect if the script has fatal errors. This is because the desired runtime action does not get executed.

`display_startup_errors` bool

  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` bool

  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` int

  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, but not to explicitly called functions such as error_log().

  When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
`ignore_repeated_errors` bool

  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` bool

  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` bool

  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 sent to stderr on Posix platforms. On Windows, it will be sent 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` bool

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

`html_errors` bool

  If enabled, error messages will include HTML tags. The 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.

  If disabled, error message will be solely plain text.

`xmlrpc_errors` bool

  If enabled, turns off normal error reporting and formats errors as XML-RPC error message.

`xmlrpc_error_number` int

  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. Only used when the error message is displayed on screen. The main purpose is to be able to prepend additional HTML markup to the error message.

`error_append_string` string

  String to output after an error message. Only used when the error message is displayed on screen. The main purpose is to be able to append additional HTML markup to the 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 it means the event log. 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().

`error_log_mode` int

  File mode for the file described set in error_log.

`syslog.facility` string

  Specifies what type of program is logging the message. Only effective if error_log is set to "syslog".

`syslog.filter` string

  Specifies the filter type to filter the logged messages. Allowed characters are passed unmodified; all others are written in their hexadecimal representation prefixed with `\x`.

  - `all` – the logged string will be split at newline characters, and all characters are passed unaltered
  - `ascii` – the logged string will be split at newline characters, and any non-printable 7-bit ASCII characters will be escaped
  - `no-ctrl` – the logged string will be split at newline characters, and any non-printable characters will be escaped
  - `raw` – all characters are passed to the system logger unaltered, without splitting at newlines (identical to PHP before 7.3)
  This setting will affect logging via error_log set to "syslog" and calls to syslog().

  > Note:

  > The `raw` filter type is available as of PHP 7.3.8 and PHP 7.4.0.

  This directive is not supported on Windows.
`syslog.ident` string

  Specifies the ident string which is prepended to every message. Only effective if error_log is set to "syslog".

# Predefined Constants

The constants below are always available as part of the PHP core.

The following constants (either the corresponding numerical value or their symbolic name) are used as a bitmask to specify which errors to report. It is possible to use bitwise operators to combine these values or mask out certain types of errors.

Tip

The name of the constants can be used within php.ini, instead of the raw numerical values to which they correspond to. However, only the `|`, `~`, `^`, `!`, `&` operators are understood within php.ini.

Warning

It is not possible to use the symbolic names outside of PHP. For example in httpd.conf the computed bitmask value must be used instead.

`E_ERROR` (int)
  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. Value of the constant: `1`
`E_WARNING` (int)
  Run-time warnings (non-fatal errors). Execution of the script is not halted. Value of the constant: `2`
`E_PARSE` (int)
  Compile-time parse errors. Parse errors should only be generated by the parser. Value of the constant: `4`
`E_NOTICE` (int)
  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. Value of the constant: `8`
`E_CORE_ERROR` (int)
  Fatal errors that occur during PHP's initial startup. This is like an `E_ERROR`, except it is generated by the core of PHP. Value of the constant: `16`
`E_CORE_WARNING` (int)
  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. Value of the constant: `32`
`E_COMPILE_ERROR` (int)
  Fatal compile-time errors. This is like an `E_ERROR`, except it is generated by the Zend Scripting Engine. Value of the constant: `64`
`E_COMPILE_WARNING` (int)
  Compile-time warnings (non-fatal errors). This is like an `E_WARNING`, except it is generated by the Zend Scripting Engine. Value of the constant: `128`
`E_DEPRECATED` (int)
  Run-time deprecation notices. Enable this to receive warnings about code that will not work in future versions. Value of the constant: `8192`
`E_USER_ERROR` (int)
  User-generated error message. This is like an `E_ERROR`, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: `256`
  Warning

  Usage of this constant with trigger_error() is deprecated as of PHP 8.4.0. It is recommended to either `throw` an Exception or call exit() instead.

`E_USER_WARNING` (int)
  User-generated warning message. This is like an `E_WARNING`, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: `512`
`E_USER_NOTICE` (int)
  User-generated notice message. This is like an `E_NOTICE`, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: `1024`
`E_USER_DEPRECATED` (int)
  User-generated deprecation message. This is like an `E_DEPRECATED`, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: `16384`
`E_STRICT` (int)
  Run-time suggestions emitted by PHP about the executed code to ensure forward compatibility. Value of the constant: `2048`
  Warning

  This error level is unused, and has been deprecated as of PHP 8.4.0.

`E_RECOVERABLE_ERROR` (int)
  Legacy engine "exceptions" which correspond to catchable fatal error. Similar to Error but must be caught via a user defined error handler (see set_error_handler()). If not handled, this behaves like `E_ERROR`. Value of the constant: `4096`

  > Note: This error level is effectively unused, the only case where this can happen is when interpreting an object as a bool fails. This can only happen for internal objects. The most common example, prior to PHP 8.4.0, is using a GMP instance in a conditional.

`E_ALL` (int)
  Bit-mask that contains every single error, warning, and notice. Value of the constant: `30719`
  Warning

  Prior to PHP 8.4, the constant value was: `32767`

# Examples

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";
?>`

# Error Handling Functions

# See Also

See also syslog().

# debug_backtrace

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

debug_backtrace — Generates a backtrace

### Description

debug_backtrace(int `$options` = `DEBUG_BACKTRACE_PROVIDE_OBJECT`, int `$limit` = 0): array

debug_backtrace() generates a PHP backtrace.

### Parameters

`options`

  This parameter is a bitmask for the following options:

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

  > Note:

  > There are four possible combinations:

  > debug_backtrace() options
  > `debug_backtrace()` | Populates both indexes
  > `debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT)`
  > `debug_backtrace(1)`
  > `debug_backtrace(0)` | Omits index `"object"` and populates index `"args"`.
  > `debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)` | Omits index `"object"` and index `"args"`.
  > `debug_backtrace(2)`
  > `debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT|DEBUG_BACKTRACE_IGNORE_ARGS)` | Populate index `"object"` and omit index `"args"`.
  > `debug_backtrace(3)`

`limit`

  This parameter can be used to limit the number of stack frames returned. By default (`limit`=`0`) it returns all stack frames.

### Return Values

Returns an array of associative arrays. The possible returned elements are as follows:

Possible returned elements from debug_backtrace()
Name | Type | Description
--- | --- | ---
function | string | The current function name. See also __FUNCTION__.
line | int | 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).

### Examples

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

### See Also

- trigger_error() - Generates a user-level error/warning/notice message
- debug_print_backtrace() - Prints a backtrace

# debug_print_backtrace

(PHP 5, PHP 7, PHP 8)

debug_print_backtrace — Prints a backtrace

### Description

debug_print_backtrace(int `$options` = 0, int `$limit` = 0): void

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

### Parameters

`options`

  This parameter is a bitmask for the following options:

  debug_print_backtrace() options
  DEBUG_BACKTRACE_IGNORE_ARGS | Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory.

`limit`

  This parameter can be used to limit the number of stack frames printed. By default (`limit`=`0`) it prints all stack frames.

### Return Values

No value is returned.

### Examples

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]

### See Also

- debug_backtrace() - Generates a backtrace

# error_clear_last

(PHP 7, PHP 8)

error_clear_last — Clear the most recent error

### Description

error_clear_last(): void

### Parameters

This function has no parameters.

### Return Values

Clears the most recent errors, making it unable to be retrieved with error_get_last().

### Examples

Example #1 An error_clear_last() example

`<?php
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
@$a = $b;
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
?>`

The above example will output something similar to:

    NULL
    NULL
    array(4) {
      ["type"]=>
      int(8)
      ["message"]=>
      string(21) "Undefined variable: b"
      ["file"]=>
      string(9) "%s"
      ["line"]=>
      int(6)
    }
    NULL

### See Also

- Error constants

# error_get_last

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

error_get_last — Get the last occurred error

### Description

error_get_last(): ?array

Gets information about the last error that occurred.

### Parameters

This function has no parameters.

### Return Values

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.

### Examples

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
    )

### See Also

- Error constants
- Variable $php_errormsg
- error_clear_last() - Clear the most recent error
- Directive `display_errors`
- Directive `html_errors`
- Directive `xmlrpc_errors`

# error_log

(PHP 4, PHP 5, PHP 7, PHP 8)

error_log — Send an error message to the defined error handling routines

### Description

error_log(
string `$message`,
int `$message_type` = 0,
?string `$destination` = `null`,
?string `$additional_headers` = `null`
): bool

Sends an error message to the web server's error log or to a file.

### Parameters

`message`

  The error message that should be logged.

`message_type`

  Says where the error should go. The possible message types are as follows:

  error_log() log types
  0 | `message` is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
  1 | `message` is sent by email to the address in the `destination` parameter. This is the only message type where the fourth parameter, `additional_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.

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

### Return Values

Returns `true` on success or `false` on failure. If `message_type` is zero, this function always returns `true`, regardless of whether the error could be logged or not.

### Changelog

Version | Description
--- | ---
8.0.0 | `destination` and `additional_headers` are now nullable.

### Examples

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");
?>`

### Notes

Warning

error_log() is not binary safe. `message` will be truncated by null character.

Tip

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

# error_reporting

(PHP 4, PHP 5, PHP 7, PHP 8)

error_reporting — Sets which PHP errors are reported

### Description

error_reporting(?int `$error_level` = `null`): int

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 `error_level` is not set, error_reporting() will just return the current error reporting level.

### Parameters

`error_level`

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

### Return Values

Returns the error_reporting level, before it is changed to `error_level`.

> Note: The error control `@`-operator changes the `error_level` during error handling.

### Changelog

Version | Description
--- | ---
8.0.0 | `error_level` is nullable now.

### Examples

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
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
?>`

### Notes

Tip

Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP versions. The behavior is equivalent to passing `E_ALL` constant.

### See Also

- The display_errors directive
- The html_errors directive
- The xmlrpc_errors directive
- The error control operator
- ini_set() - Sets the value of a configuration option

# get_error_handler

(PHP 8 >= 8.5.0)

get_error_handler — Gets the user-defined error handler function

### Description

get_error_handler(): ?callable

Returns the current error handler function, if any.

### Parameters

This function has no parameters.

### Return Values

Returns the currently defined error handler (if any). If the built-in error handler is used `null` is returned.

The returned handler is the exact callable value that was passed to set_error_handler() to define it.

### Examples

Example #1 get_error_handler() example

`<?php
$handler = function (int $errno, string $errstr, ?string $errfile, ?int $errline) {
echo "Error: " . $errstr . "\n";
};
var_dump(get_error_handler()); // NULL
set_error_handler($handler);
var_dump(get_error_handler() === $handler); // bool(true)
?>`

### Notes

Tip

Prior to PHP 8.5.0, this functionality can be provided by the following polyfill:

`<?php
if (!function_exists('get_error_handler')) {
function noop_error_handler() {
}
function get_error_handler(): ?callable {
$handler = set_error_handler('noop_error_handler');
restore_error_handler();
return $handler;
}
}
?>`

### See Also

- error_reporting() - Sets which PHP errors are reported
- set_error_handler() - Sets a user-defined error handler function
- restore_error_handler() - Restores the previous error handler function
- trigger_error() - Generates a user-level error/warning/notice message
- error level constants

# get_exception_handler

(PHP 8 >= 8.5.0)

get_exception_handler — Gets the user-defined exception handler function

### Description

get_exception_handler(): ?callable

Returns the current exception handler function, if any.

### Parameters

This function has no parameters.

### Return Values

Returns the currently defined exception handler. If no handler is defined, `null` is returned.

The returned handler is the exact callable value that was passed to set_exception_handler() to define it.

### Examples

Example #1 get_exception_handler() example

`<?php
$handler = function (Throwable $ex) {
echo "Exception: " . $ex::class . ": " . $ex->getMessage() . "\n";
};
var_dump(get_exception_handler()); // NULL
set_exception_handler($handler);
var_dump(get_exception_handler() === $handler); // bool(true)
?>`

### Notes

Tip

Prior to PHP 8.5.0, this functionality can be provided by the following polyfill:

`<?php
if (!function_exists('get_exception_handler')) {
function noop_exception_handler() {
}
function get_exception_handler(): ?callable {
$handler = set_exception_handler('noop_exception_handler');
restore_exception_handler();
return $handler;
}
}
?>`

### See Also

- set_exception_handler() - Sets a user-defined exception handler function
- restore_exception_handler() - Restores the previously defined exception handler function
- restore_error_handler() - Restores the previous error handler function
- error_reporting() - Sets which PHP errors are reported
- Exceptions

# restore_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

restore_error_handler — Restores the previous error handler function

### Description

restore_error_handler(): true

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

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Examples

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.

### See Also

- error_reporting() - Sets which PHP errors are reported
- set_error_handler() - Sets a user-defined error handler function
- get_error_handler() - Gets the user-defined error handler function
- restore_exception_handler() - Restores the previously defined exception handler function
- trigger_error() - Generates a user-level error/warning/notice message

# restore_exception_handler

(PHP 5, PHP 7, PHP 8)

restore_exception_handler — Restores the previously defined exception handler function

### Description

restore_exception_handler(): true

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

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Examples

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

### See Also

- set_exception_handler() - Sets a user-defined exception handler function
- get_exception_handler() - Gets the user-defined exception handler function
- set_error_handler() - Sets a user-defined error handler function
- restore_error_handler() - Restores the previous error handler function
- error_reporting() - Sets which PHP errors are reported

# set_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

set_error_handler — Sets a user-defined error handler function

### Description

set_error_handler(?callable `$callback`, int `$error_levels` = `E_ALL`): ?callable

Sets a user function (`callback`) to handle errors in a script.

This function can be used to define custom error handlers during runtime, for example in applications which need to do file/data cleanup when a critical error happens, or when triggering an error in response to 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_levels` unless the callback function returns `false`. error_reporting() settings will have no effect and the error handler will be called regardless - however, it's still possible to read the current value of error_reporting and act appropriately.

Also note that it is the handler's responsibility to stop the script's execution if necessary by calling exit(). 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` independent of where they were raised, 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.

### Parameters

`callback`

  If `null` is passed, the handler is reset to its default state. Otherwise, the handler is a callback with the following signature:

  handler(
  int `$errno`,
  string `$errstr`,
  string `$errfile` = ?,
  int `$errline` = ?,
  array `$errcontext` = ?
  ): bool
  `errno`
    The first parameter, `errno`, will be passed the level of the error raised, as an integer.
  `errstr`
    The second parameter, `errstr`, will be passed the error message, as a string.
  `errfile`
    If the callback accepts a third parameter, `errfile`, it will be passed the filename that the error was raised in, as a string.
  `errline`
    If the callback accepts a fourth parameter, `errline`, it will be passed the line number where the error was raised, as an integer.
  `errcontext`
    If the callback accepts a fifth parameter, `errcontext`, it will be passed 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 handlers must not modify the error context.
    Warning

    This parameter has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. If the function defines this parameter without a default, an error of "too few arguments" will be raised when it is called.

  If the function returns `false` then the normal error handler continues.

`error_levels`

  Can be used to mask the triggering of the `callback` function just like the error_reporting ini setting controls which errors are shown. Without this mask set the `callback` will be called for every error regardless to the setting of the error_reporting setting.

### Return Values

Returns the previously defined error handler (if any) as a callable. If the built-in error handler is used `null` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `errcontext` was removed, and will no longer be passed to user callbacks.
7.2.0 | `errcontext` became deprecated. Usage of this parameter now emits an `E_DEPRECATED` notice.

### Examples

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, so let it fall
// through to the standard PHP error handler
return false;
}
// $errstr may need to be escaped:
$errstr = htmlspecialchars($errstr);
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);
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 />

### See Also

- ErrorException
- error_reporting() - Sets which PHP errors are reported
- restore_error_handler() - Restores the previous error handler function
- get_error_handler() - Gets the user-defined error handler function
- trigger_error() - Generates a user-level error/warning/notice message
- error level constants

# set_exception_handler

(PHP 5, PHP 7, PHP 8)

set_exception_handler — Sets a user-defined exception handler function

### Description

set_exception_handler(?callable `$callback`): ?callable

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the `callback` is called.

### Parameters

`callback`

  The function to be called when an uncaught exception occurs. This handler function needs to accept one parameter, which will be the Throwable object that was thrown. Both Error and Exception implement the Throwable interface. This is the handler signature:

  handler(Throwable `$ex`): void

  `null` may be passed instead, to reset this handler to its default state.

### Return Values

Returns the previously defined exception handler, or `null` on error. If no previous handler was defined, `null` is also returned.

### Examples

Example #1 set_exception_handler() example

`<?php
function exception_handler(Throwable $exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>`

### See Also

- get_exception_handler() - Gets the user-defined exception handler function
- restore_exception_handler() - Restores the previously defined exception handler function
- restore_error_handler() - Restores the previous error handler function
- error_reporting() - Sets which PHP errors are reported
- Exceptions

# trigger_error

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

trigger_error — Generates a user-level error/warning/notice message

### Description

trigger_error(string `$message`, int `$error_level` = `E_USER_NOTICE`): true

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.

### Parameters

`message`

  The designated error message for this error. It's limited to 1024 bytes in length. Any additional characters beyond 1024 bytes will be truncated.

`error_level`

  The designated error type for this error. It only works with the `E_USER_*` family of constants, and will default to `E_USER_NOTICE`.

  Warning

  Passing `E_USER_ERROR` as the `error_level` is now deprecated. Throw an Exception or call exit() instead.

### Return Values

Always returns `true`.

### Errors/Exceptions

This function throws a ValueError if `error_level` is not one of `E_USER_ERROR`, `E_USER_WARNING`, `E_USER_NOTICE`, `E_USER_DEPRECATED`.

### Changelog

Version | Description
--- | ---
8.4.0 | Passing `E_USER_ERROR` as the `error_level` is now deprecated. Throw an Exception or call exit() instead.
8.4.0 | The function now has a return type of true instead of bool.
8.0.0 | The function now throws a ValueError if an invalid `error_level` is specified. Previously, it returned `false`.

### Examples

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

`<?php
$password = $_POST['password'] ?? '';
if ($password === '') {
trigger_error("Using an empty password is unsafe", E_USER_WARNING);
}
$hash = password_hash($password, PASSWORD_DEFAULT);
?>`

### Notes

Warning

HTML entities in `message` are not escaped. Use htmlentities() on the message if the error is to be displayed in a browser.

### See Also

- error_reporting() - Sets which PHP errors are reported
- set_error_handler() - Sets a user-defined error handler function
- restore_error_handler() - Restores the previous error handler function
- The error level constants
- The Deprecated attribute

# user_error

(PHP 4, PHP 5, PHP 7, PHP 8)

user_error — Alias of trigger_error()

### Description

This function is an alias of: trigger_error().

## Table of Contents

- debug_backtrace — Generates a backtrace
- debug_print_backtrace — Prints a backtrace
- error_clear_last — Clear the most recent error
- error_get_last — Get the last occurred error
- error_log — Send an error message to the defined error handling routines
- error_reporting — Sets which PHP errors are reported
- get_error_handler — Gets the user-defined error handler function
- get_exception_handler — Gets the user-defined exception handler function
- restore_error_handler — Restores the previous error handler function
- restore_exception_handler — Restores the previously defined exception handler function
- set_error_handler — Sets a user-defined error handler function
- set_exception_handler — Sets a user-defined exception handler function
- trigger_error — Generates a user-level error/warning/notice message
- user_error — Alias of trigger_error

- Installing/Configuring
  - Runtime Configuration
- Predefined Constants
- Examples
- Error Handling Functions
  - debug_backtrace — Generates a backtrace
  - debug_print_backtrace — Prints a backtrace
  - error_clear_last — Clear the most recent error
  - error_get_last — Get the last occurred error
  - error_log — Send an error message to the defined error handling routines
  - error_reporting — Sets which PHP errors are reported
  - get_error_handler — Gets the user-defined error handler function
  - get_exception_handler — Gets the user-defined exception handler function
  - restore_error_handler — Restores the previous error handler function
  - restore_exception_handler — Restores the previously defined exception handler function
  - set_error_handler — Sets a user-defined error handler function
  - set_exception_handler — Sets a user-defined exception handler function
  - trigger_error — Generates a user-level error/warning/notice message
  - user_error — Alias of trigger_error

# Foreign Function Interface

# Introduction

This extension allows the loading of shared libraries (.DLL or .so), calling of C functions and accessing of C data structures in pure PHP, without having to have deep knowledge of the Zend extension API, and without having to learn a third “intermediate” language. The public API is implemented as a single class FFI with several static methods (some of them may be called dynamically), and overloaded object methods, which perform the actual interaction with C data.

Caution

FFI is dangerous, since it allows to interface with the system on a very low level. The FFI extension should only be used by developers having a working knowledge of C and the used C APIs. To minimize the risk, the FFI API usage may be restricted with the ffi.enable php.ini directive.

> Note: The FFI extension does not render the classic PHP extension API obsolete; it is merely provided for ad-hoc interfacing with C functions and data structures.

Tip

Currently, accessing FFI data structures is significantly (about 2 times) slower than accessing native PHP arrays and objects. Therefore, it makes no sense to use the FFI extension for speed; however, it may make sense to use it to reduce memory consumption.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

This extension requires the » libffi library to be installed.

## Installation

To enable the FFI extension, PHP has to be configured with --with-ffi.

Windows users have to include php_ffi.dll into php.ini to enable the FFI extension.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

FFI Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
ffi.enable | "preload" | `INI_SYSTEM` |
ffi.preload | "" | `INI_SYSTEM` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`ffi.enable` string
  Allows enabling (`"true"`) or disabling (`"false"`) FFI API usage, or restricting it only to the CLI SAPI and preloaded files (`"preload"`). The FFI API restrictions only affect the FFI class, but not overloaded functions of FFI\CData objects. This means that it is possible to create some FFI\CData objects in preloaded files, and then to use these directly in PHP scripts.
`ffi.preload` string
  Allows preloading of FFI bindings during startup, which is not possible with FFI::load() if opcache.preload_user is set. This directive accepts a `DIRECTORY_SEPARATOR` delimited list of filenames. The preloaded bindings can be accessed by calling FFI::scope().

# Examples

## Table of Contents

- Basic FFI usage
- PHP Callbacks
- A Complete PHP/FFI/preloading Example

## Basic FFI usage

Before diving into the details of the FFI API, lets take a look at a few examples demonstrating the simplicity of the FFI API usage for regular tasks.

> Note: Some of these examples require libc.so.6 and as such will not work on systems where it is not available.

Example #1 Calling a function from shared library

`<?php
// create FFI object, loading libc and exporting function printf()
$ffi = FFI::cdef(
"int printf(const char *format, ...);", // this is a regular C declaration
"libc.so.6");
// call C's printf()
$ffi->printf("Hello %s!\n", "world");
?>`

The above example will output:

    Hello world!

> Note: Note that some C functions need specific calling conventions, e.g. `__fastcall`, `__stdcall` or `,__vectorcall`.

Example #2 Calling a function, returning a structure through an argument

`<?php
// create gettimeofday() binding
$ffi = FFI::cdef("
typedef unsigned int time_t;
typedef unsigned int suseconds_t;
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz);
", "libc.so.6");
// create C data structures
$tv = $ffi->new("struct timeval");
$tz = $ffi->new("struct timezone");
// call C's gettimeofday()
var_dump($ffi->gettimeofday(FFI::addr($tv), FFI::addr($tz)));
// access field of C data structure
var_dump($tv->tv_sec);
// print the whole C data structure
var_dump($tz);
?>`

The above example will output something similar to:

    int(0)
    int(1555946835)
    object(FFI\CData:struct timezone)#3 (2) {
      ["tz_minuteswest"]=>
      int(0)
      ["tz_dsttime"]=>
      int(0)
    }

Example #3 Accessing existing C variables

`<?php
// create FFI object, loading libc and exporting errno variable
$ffi = FFI::cdef(
"int errno;", // this is a regular C declaration
"libc.so.6");
// print C's errno
var_dump($ffi->errno);
?>`

The above example will output:

    int(0)

Example #4 Creating and Modifying C variables

`<?php
// create a new C int variable
$x = FFI::new("int");
var_dump($x->cdata);
// simple assignment
$x->cdata = 5;
var_dump($x->cdata);
// compound assignment
$x->cdata += 2;
var_dump($x->cdata);
?>`

The above example will output:

    int(0)
    int(5)
    int(7)

Example #5 Working with C arrays

`<?php
// create C data structure
$a = FFI::new("long[1024]");
// work with it like with a regular PHP array
for ($i = 0; $i < count($a); $i++) {
$a[$i] = $i;
}
var_dump($a[25]);
$sum = 0;
foreach ($a as $n) {
$sum += $n;
}
var_dump($sum);
var_dump(count($a));
var_dump(FFI::sizeof($a));
?>`

The above example will output:

    int(25)
    int(523776)
    int(1024)
    int(8192)

Example #6 Working with C enums

`<?php
$a = FFI::cdef('typedef enum _zend_ffi_symbol_kind {
ZEND_FFI_SYM_TYPE,
ZEND_FFI_SYM_CONST = 2,
ZEND_FFI_SYM_VAR,
ZEND_FFI_SYM_FUNC
} zend_ffi_symbol_kind;
');
var_dump($a->ZEND_FFI_SYM_TYPE);
var_dump($a->ZEND_FFI_SYM_CONST);
var_dump($a->ZEND_FFI_SYM_VAR);
?>`

The above example will output:

    int(0)
    int(2)
    int(3)

## PHP Callbacks

It is possible to assign a PHP closure to a native variable of function pointer type or to pass it as a function argument:

Example #1 Assigning a PHP Closure to a C function pointer

`<?php
$zend = FFI::cdef("
typedef int (*zend_write_func_t)(const char *str, size_t str_length);
extern zend_write_func_t zend_write;
");
echo "Hello World 1!\n";
$orig_zend_write = clone $zend->zend_write;
$zend->zend_write = function($str, $len) {
global $orig_zend_write;
$orig_zend_write("{\n\t", 3);
$ret = $orig_zend_write($str, $len);
$orig_zend_write("}\n", 2);
return $ret;
};
echo "Hello World 2!\n";
$zend->zend_write = $orig_zend_write;
echo "Hello World 3!\n";
?>`

The above example will output:

    Hello World 1!
    {
            Hello World 2!
    }
    Hello World 3!

Although this works, this functionality is not supported on all libffi platforms, is not efficient and leaks resources by the end of request.
Tip

It is therefore recommended to minimize the usage of PHP callbacks.

## A Complete PHP/FFI/preloading Example

php.ini

    ffi.enable=preload
    opcache.preload=preload.php

preload.php

`<?php
FFI::load(__DIR__ . "/dummy.h");
opcache_compile_file(__DIR__ . "/dummy.php");
?>`

dummy.h

    #define FFI_SCOPE "DUMMY"
    #define FFI_LIB "libc.so.6"

    int printf(const char *format, ...);

dummy.php

`<?php
final class Dummy {
private static $ffi = null;
function __construct() {
if (is_null(self::$ffi)) {
self::$ffi = FFI::scope("DUMMY");
}
}
function printf($format, ...$args) {
return (int) self::$ffi->printf($format, ...$args);
}
}
?>`

test.php

`<?php
$d = new Dummy();
$d->printf("Hello %s!\n", "world");
?>`

# Main interface to C code and data

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

Objects of this class are created by the factory methods FFI::cdef(), FFI::load() or FFI::scope(). Defined C variables are made available as properties of the FFI instance, and defined C functions are made available as methods of the FFI instance. Declared C types can be used to create new C data structures using FFI::new() and FFI::type().

FFI definition parsing and shared library loading may take significant time. It is not useful to do it on each HTTP request in a Web environment. However, it is possible to preload FFI definitions and libraries at PHP startup, and to instantiate FFI objects when necessary. Header files may be extended with special `FFI_SCOPE` defines (e.g. `#define FFI_SCOPE "foo"`; the default scope is "C") and then loaded by FFI::load() during preloading. This leads to the creation of a persistent binding, that will be available to all the following requests through FFI::scope(). Refer to the complete PHP/FFI/preloading example for details.

It is possible to preload more than one C header file into the same scope.

## Class synopsis

final class FFI {
/* Constants */
public const int __BIGGEST_ALIGNMENT__;
/* Methods */
public static addr(FFI\CData `&$ptr`): FFI\CData
public static alignof(FFI\CData|FFI\CType `&$ptr`): int
public static arrayType(FFI\CType `$type`, array `$dimensions`): FFI\CType
public cast(FFI\CType|string `$type`, FFI\CData|int|float|bool|null `&$ptr`): ?FFI\CData
public static cdef(string `$code` = "", ?string `$lib` = `null`): FFI
public static free(FFI\CData `&$ptr`): void
public static isNull(FFI\CData `&$ptr`): bool
public static load(string `$filename`): ?FFI
public static memcmp(string|FFI\CData `&$ptr1`, string|FFI\CData `&$ptr2`, int `$size`): int
public static memcpy(FFI\CData `&$to`, FFI\CData|string `&$from`, int `$size`): void
public static memset(FFI\CData `&$ptr`, int `$value`, int `$size`): void
public new(FFI\CType|string `$type`, bool `$owned` = `true`, bool `$persistent` = `false`): ?FFI\CData
public static scope(string `$name`): FFI
public static sizeof(FFI\CData|FFI\CType `&$ptr`): int
public static string(FFI\CData `&$ptr`, ?int `$size` = `null`): string
public type(string `$type`): ?FFI\CType
public static typeof(FFI\CData `&$ptr`): FFI\CType
}

## Predefined Constants

`FFI::__BIGGEST_ALIGNMENT__`

# FFI::addr

(PHP 7 >= 7.4.0, PHP 8)

FFI::addr — Creates an unmanaged pointer to C data

### Description

public static FFI::addr(FFI\CData `&$ptr`): FFI\CData

Creates an unmanaged pointer to the C data represented by the given FFI\CData. The source `ptr` must survive the resulting pointer. This function is mainly useful to pass arguments to C functions by pointer.

### Parameters

`ptr`
  The handle of the pointer to a C data structure.

### Return Values

Returns the freshly created FFI\CData object.

# FFI::alignof

(PHP 7 >= 7.4.0, PHP 8)

FFI::alignof — Gets the alignment

### Description

public static FFI::alignof(FFI\CData|FFI\CType `&$ptr`): int

Gets the alignment of the given FFI\CData or FFI\CType object.

### Parameters

`ptr`
  The handle of the C data or type.

### Return Values

Returns the alignment of the given FFI\CData or FFI\CType object.

# FFI::arrayType

(PHP 7 >= 7.4.0, PHP 8)

FFI::arrayType — Dynamically constructs a new C array type

### Description

public static FFI::arrayType(FFI\CType `$type`, array `$dimensions`): FFI\CType

Dynamically constructs a new C array type with elements of type defined by `type`, and dimensions specified by `dimensions`. In the following example `$t1` and `$t2` are equivalent array types:

`<?php
$t1 = FFI::type("int[2][3]");
$t2 = FFI::arrayType(FFI::type("int"), [2, 3]);
?>`

### Parameters

`type`
  A valid C declaration as string, or an instance of FFI\CType which has already been created.
`dimensions`
  The dimensions of the type as array.

### Return Values

Returns the freshly created FFI\CType object.

# FFI::cast

(PHP 7 >= 7.4.0, PHP 8)

FFI::cast — Performs a C type cast

### Description

public FFI::cast(FFI\CType|string `$type`, FFI\CData|int|float|bool|null `&$ptr`): ?FFI\CData

FFI::cast() creates a new FFI\CData object, that references the same C data structure, but is associated with a different type. The resulting object does not own the C data, and the source `ptr` must survive the result. The C type may be specified as a string with any valid C type declaration or as FFI\CType object, created before. Any type declared for the instance is allowed.

### Parameters

`type`
  A valid C declaration as string, or an instance of FFI\CType which has already been created.
`ptr`
  The handle of the pointer to a C data structure.

### Return Values

Returns the freshly created FFI\CData object.

### Changelog

Version | Description
--- | ---
8.3.0 | Calling FFI::cast() statically is now deprecated.

# FFI::cdef

(PHP 7 >= 7.4.0, PHP 8)

FFI::cdef — Creates a new FFI object

### Description

public static FFI::cdef(string `$code` = "", ?string `$lib` = `null`): FFI

Creates a new FFI object.

### Parameters

`code`
  A string containing a sequence of declarations in regular C language (types, structures, functions, variables, etc). Actually, this string may be copy-pasted from C header files.

  > Note: C preprocessor directives are not supported, i.e. `#include`, `#define` and CPP macros do not work.

`lib`
  The name of a shared library file, to be loaded and linked with the definitions.

  > Note: If `lib` is omitted or `null`, platforms supporting `RTLD_DEFAULT` attempt to lookup symbols declared in `code` in the normal global scope. Other systems will fail to resolve these symbols.

### Return Values

Returns the freshly created FFI object.

### Changelog

Version | Description
--- | ---
8.3.0 | C functions returning `void` return a PHP null instead of FFI\CType::TYPE_VOID.
8.0.0 | `lib` is nullable now.

# FFI::free

(PHP 7 >= 7.4.0, PHP 8)

FFI::free — Releases an unmanaged data structure

### Description

public static FFI::free(FFI\CData `&$ptr`): void

Manually releases a previously created unmanaged data structure.

### Parameters

`ptr`
  The handle of the unmanaged pointer to a C data structure.

### Return Values

No value is returned.

# FFI::isNull

(PHP 7 >= 7.4.0, PHP 8)

FFI::isNull — Checks whether a FFI\CData is a null pointer

### Description

public static FFI::isNull(FFI\CData `&$ptr`): bool

Checks whether a FFI\CData is a null pointer.

### Parameters

`ptr`
  The handle of the pointer to a C data structure.

### Return Values

Returns whether a FFI\CData is a null pointer.

# FFI::load

(PHP 7 >= 7.4.0, PHP 8)

FFI::load — Loads C declarations from a C header file

### Description

public static FFI::load(string `$filename`): ?FFI

Loads C declarations from a C header file. It is possible to specify shared libraries that should be loaded, using special `FFI_LIB` defines in the loaded C header file.

### Parameters

`filename`
  The name of a C header file. C preprocessor directives are not supported, i.e. `#include`, `#define` and CPP macros do not work, except for special cases listed below. The header file should contain a `#define` statement for the `FFI_SCOPE` variable, e.g.: `#define FFI_SCOPE "MYLIB"`. Refer to the class introduction for details. The header file may contain a `#define` statement for the `FFI_LIB` variable to specify the library it exposes. If it is a system library only the file name is required, e.g.: `#define FFI_LIB "libc.so.6"`. If it is a custom library, a relative path is required, e.g.: `#define FFI_LIB "./mylib.so"`.

### Return Values

Returns the freshly created FFI object, or `null` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | FFI::load() is now allowed in preload scripts when the current system user is the same as the one defined in the `opcache.preload_user` configuration directive.

### See Also

- FFI::scope() - Instantiates an FFI object with C declarations parsed during preloading

# FFI::memcmp

(PHP 7 >= 7.4.0, PHP 8)

FFI::memcmp — Compares memory areas

### Description

public static FFI::memcmp(string|FFI\CData `&$ptr1`, string|FFI\CData `&$ptr2`, int `$size`): int

Compares `size` bytes from the memory areas `ptr1` and `ptr2`. Both `ptr1` and `ptr2` can be any native data structures (FFI\CData) or PHP strings.

### Parameters

`ptr1`
  The start of one memory area.
`ptr2`
  The start of another memory area.
`size`
  The number of bytes to compare.

### Return Values

Returns a value less than `0` if the contents of the memory area starting at `ptr1` are considered less than the contents of the memory area starting at `ptr2`, a value greater than `0` if the contents of the first memory area are considered greater than the second, and `0` if they are equal.

# FFI::memcpy

(PHP 7 >= 7.4.0, PHP 8)

FFI::memcpy — Copies one memory area to another

### Description

public static FFI::memcpy(FFI\CData `&$to`, FFI\CData|string `&$from`, int `$size`): void

Copies `size` bytes from the memory area `from` to the memory area `to`.

### Parameters

`to`
  The start of the memory area to copy to.
`from`
  The start of the memory area to copy from.
`size`
  The number of bytes to copy.

### Return Values

No value is returned.

# FFI::memset

(PHP 7 >= 7.4.0, PHP 8)

FFI::memset — Fills a memory area

### Description

public static FFI::memset(FFI\CData `&$ptr`, int `$value`, int `$size`): void

Fills `size` bytes of the memory area pointed to by `ptr` with the given byte `value`.

### Parameters

`ptr`
  The start of the memory area to fill.
`value`
  The byte to fill with.
`size`
  The number of bytes to fill.

### Return Values

No value is returned.

# FFI::new

(PHP 7 >= 7.4.0, PHP 8)

FFI::new — Creates a C data structure

### Description

public FFI::new(FFI\CType|string `$type`, bool `$owned` = `true`, bool `$persistent` = `false`): ?FFI\CData

Creates a native data structure of the given C type. Any type declared for the instance is allowed.

### Parameters

`type`
  `type` is a valid C declaration as string, or an instance of FFI\CType which has already been created.
`owned`
  Whether to create owned (i.e. managed) or unmanaged data. Managed data lives together with the returned FFI\CData object, and is released when the last reference to that object is released by regular PHP reference counting or GC. Unmanaged data should be released by calling FFI::free(), when no longer needed.
`persistent`
  Whether to allocate the C data structure permanently on the system heap (using malloc()), or on the PHP request heap (using emalloc()).

### Return Values

Returns the freshly created FFI\CData object, or `null` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | Calling FFI::new() statically is now deprecated.

# FFI::scope

(PHP 7 >= 7.4.0, PHP 8)

FFI::scope — Instantiates an FFI object with C declarations parsed during preloading

### Description

public static FFI::scope(string `$name`): FFI

Instantiates an FFI object with C declarations parsed during preloading.

The FFI::scope() method is safe to call multiple times for the same scope. Multiple references to the same scope may be loaded at the same time.

### Parameters

`name`
  The scope name defined by a special `FFI_SCOPE` define.

### Return Values

Returns the freshly created FFI object.

### See Also

- FFI::load() - Loads C declarations from a C header file

# FFI::sizeof

(PHP 7 >= 7.4.0, PHP 8)

FFI::sizeof — Gets the size of C data or types

### Description

public static FFI::sizeof(FFI\CData|FFI\CType `&$ptr`): int

Returns the size of the given FFI\CData or FFI\CType object.

### Parameters

`ptr`
  The handle of the C data or type.

### Return Values

The size of the memory area pointed at by `ptr`.

# FFI::string

(PHP 7 >= 7.4.0, PHP 8)

FFI::string — Creates a PHP string from a memory area

### Description

public static FFI::string(FFI\CData `&$ptr`, ?int `$size` = `null`): string

Creates a PHP string from `size` bytes of the memory area pointed to by `ptr`.

### Parameters

`ptr`
  The start of the memory area from which to create a string.
`size`
  The number of bytes to copy to the string. If `size` is omitted or `null`, `ptr` must be a zero terminated array of C `char`.

### Return Values

The freshly created PHP string.

### Changelog

Version | Description
--- | ---
8.0.0 | `size` is nullable now; previously, its default was `0`.

# FFI::type

(PHP 7 >= 7.4.0, PHP 8)

FFI::type — Creates an FFI\CType object from a C declaration

### Description

public FFI::type(string `$type`): ?FFI\CType

This function creates and returns a FFI\CType object for the given string containing a C type declaration. Any type declared for the instance is allowed.

### Parameters

`type`
  A valid C declaration as string.

### Return Values

Returns the freshly created FFI\CType object, or `null` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | Calling FFI::type() statically is now deprecated.

# FFI::typeof

(PHP 7 >= 7.4.0, PHP 8)

FFI::typeof — Gets the FFI\CType of FFI\CData

### Description

public static FFI::typeof(FFI\CData `&$ptr`): FFI\CType

Gets the FFI\CType object representing the type of the given FFI\CData object.

### Parameters

`ptr`
  The handle of the pointer to a C data structure.

### Return Values

Returns the FFI\CType object representing the type of the given FFI\CData object.

## Table of Contents

- FFI::addr — Creates an unmanaged pointer to C data
- FFI::alignof — Gets the alignment
- FFI::arrayType — Dynamically constructs a new C array type
- FFI::cast — Performs a C type cast
- FFI::cdef — Creates a new FFI object
- FFI::free — Releases an unmanaged data structure
- FFI::isNull — Checks whether a FFI\CData is a null pointer
- FFI::load — Loads C declarations from a C header file
- FFI::memcmp — Compares memory areas
- FFI::memcpy — Copies one memory area to another
- FFI::memset — Fills a memory area
- FFI::new — Creates a C data structure
- FFI::scope — Instantiates an FFI object with C declarations parsed during preloading
- FFI::sizeof — Gets the size of C data or types
- FFI::string — Creates a PHP string from a memory area
- FFI::type — Creates an FFI\CType object from a C declaration
- FFI::typeof — Gets the FFI\CType of FFI\CData

# C Data Handles

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

FFI\CData objects can be used in a number of ways as a regular PHP data:

- C data of scalar types can be read and assigned via the $cdata property, e.g. `$x = FFI::new('int'); $x->cdata = 42;`
- C struct and union fields can be accessed as regular PHP object property, e.g. `$cdata->field`
- C array elements can be accessed as regular PHP array elements, e.g. `$cdata[$offset]`
- C arrays can be iterated using `foreach` statements.
- C arrays can be used as arguments of count().
- C pointers can be dereferenced as arrays, e.g. `$cdata[0]`
- C pointers can be compared using regular comparison operators (`<`, `<=`, `==`, `!=`, `>=`, `>`).
- C pointers can be incremented and decremented using regular `+`/`-`/ `++`/`--` operations, e.g. `$cdata += 5`
- C pointers can be subtracted from another using regular `-` operations.
- C pointers to functions can be called as a regular PHP closure, e.g. `$cdata()`
- Any C data can be duplicated using the clone operator, e.g. `$cdata2 = clone $cdata;`
- Any C data can be visualized using var_dump(), print_r(), etc.
- FFI\CData can now be assigned to structs and fields as of PHP 8.3.0.

> Note: Notable limitations are that FFI\CData instances do not support isset(), empty() and unset(), and that wrapped C structs and unions do not implement Traversable.

## Class synopsis

namespace FFI;
final class CData {
}

## Changelog

Version | Description
--- | ---
8.3.0 | FFI\CData can now be assigned to structs and fields.

# C Type Handles

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

## Class synopsis

namespace FFI;
final class CType {
/* Constants */
public const int FFI\CType::TYPE_VOID;
public const int FFI\CType::TYPE_FLOAT;
public const int FFI\CType::TYPE_DOUBLE;
public const int FFI\CType::TYPE_LONGDOUBLE;
public const int FFI\CType::TYPE_UINT8;
public const int FFI\CType::TYPE_SINT8;
public const int FFI\CType::TYPE_UINT16;
public const int FFI\CType::TYPE_SINT16;
public const int FFI\CType::TYPE_UINT32;
public const int FFI\CType::TYPE_SINT32;
public const int FFI\CType::TYPE_UINT64;
public const int FFI\CType::TYPE_SINT64;
public const int FFI\CType::TYPE_ENUM;
public const int FFI\CType::TYPE_BOOL;
public const int FFI\CType::TYPE_CHAR;
public const int FFI\CType::TYPE_POINTER;
public const int FFI\CType::TYPE_FUNC;
public const int FFI\CType::TYPE_ARRAY;
public const int FFI\CType::TYPE_STRUCT;
public const int FFI\CType::ATTR_CONST;
public const int FFI\CType::ATTR_INCOMPLETE_TAG;
public const int FFI\CType::ATTR_VARIADIC;
public const int FFI\CType::ATTR_INCOMPLETE_ARRAY;
public const int FFI\CType::ATTR_VLA;
public const int FFI\CType::ATTR_UNION;
public const int FFI\CType::ATTR_PACKED;
public const int FFI\CType::ATTR_MS_STRUCT;
public const int FFI\CType::ATTR_GCC_STRUCT;
public const int FFI\CType::ABI_DEFAULT;
public const int FFI\CType::ABI_CDECL;
public const int FFI\CType::ABI_FASTCALL;
public const int FFI\CType::ABI_THISCALL;
public const int FFI\CType::ABI_STDCALL;
public const int FFI\CType::ABI_PASCAL;
public const int FFI\CType::ABI_REGISTER;
public const int FFI\CType::ABI_MS;
public const int FFI\CType::ABI_SYSV;
public const int FFI\CType::ABI_VECTORCALL;
/* Methods */
public FFI\CType::getAlignment(): int
public FFI\CType::getArrayElementType(): FFI\CType
public FFI\CType::getArrayLength(): int
public FFI\CType::getAttributes(): int
public FFI\CType::getEnumKind(): int
public FFI\CType::getFuncABI(): int
public FFI\CType::getFuncParameterCount(): int
public FFI\CType::getFuncParameterType(int `$index`): FFI\CType
public FFI\CType::getFuncReturnType(): FFI\CType
public FFI\CType::getKind(): int
public FFI\CType::getName(): string
public FFI\CType::getPointerType(): FFI\CType
public FFI\CType::getSize(): int
public FFI\CType::getStructFieldNames(): array
public FFI\CType::getStructFieldOffset(string `$name`): int
public FFI\CType::getStructFieldType(string `$name`): FFI\CType
}

## Predefined Constants

`FFI\CType::TYPE_VOID`
`FFI\CType::TYPE_FLOAT`
`FFI\CType::TYPE_DOUBLE`
`FFI\CType::TYPE_LONGDOUBLE`
`FFI\CType::TYPE_UINT8`
`FFI\CType::TYPE_SINT8`
`FFI\CType::TYPE_UINT16`
`FFI\CType::TYPE_SINT16`
`FFI\CType::TYPE_UINT32`
`FFI\CType::TYPE_SINT32`
`FFI\CType::TYPE_UINT64`
`FFI\CType::TYPE_SINT64`
`FFI\CType::TYPE_ENUM`
`FFI\CType::TYPE_BOOL`
`FFI\CType::TYPE_CHAR`
`FFI\CType::TYPE_POINTER`
`FFI\CType::TYPE_FUNC`
`FFI\CType::TYPE_ARRAY`
`FFI\CType::TYPE_STRUCT`
`FFI\CType::ATTR_CONST`
`FFI\CType::ATTR_INCOMPLETE_TAG`
`FFI\CType::ATTR_VARIADIC`
`FFI\CType::ATTR_INCOMPLETE_ARRAY`
`FFI\CType::ATTR_VLA`
`FFI\CType::ATTR_UNION`
`FFI\CType::ATTR_PACKED`
`FFI\CType::ATTR_MS_STRUCT`
`FFI\CType::ATTR_GCC_STRUCT`
`FFI\CType::ABI_DEFAULT`
`FFI\CType::ABI_CDECL`
`FFI\CType::ABI_FASTCALL`
`FFI\CType::ABI_THISCALL`
`FFI\CType::ABI_STDCALL`
`FFI\CType::ABI_PASCAL`
`FFI\CType::ABI_REGISTER`
`FFI\CType::ABI_MS`
`FFI\CType::ABI_SYSV`
`FFI\CType::ABI_VECTORCALL`

# FFI\CType::getAlignment

(PHP 8 >= 8.1.0)

FFI\CType::getAlignment — Description

### Description

public FFI\CType::getAlignment(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getArrayElementType

(PHP 8 >= 8.1.0)

FFI\CType::getArrayElementType — Description

### Description

public FFI\CType::getArrayElementType(): FFI\CType

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getArrayLength

(PHP 8 >= 8.1.0)

FFI\CType::getArrayLength — Description

### Description

public FFI\CType::getArrayLength(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getAttributes

(PHP 8 >= 8.1.0)

FFI\CType::getAttributes — Description

### Description

public FFI\CType::getAttributes(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getEnumKind

(PHP 8 >= 8.1.0)

FFI\CType::getEnumKind — Description

### Description

public FFI\CType::getEnumKind(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getFuncABI

(PHP 8 >= 8.1.0)

FFI\CType::getFuncABI — Description

### Description

public FFI\CType::getFuncABI(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getFuncParameterCount

(PHP 8 >= 8.1.0)

FFI\CType::getFuncParameterCount — Retrieve the count of parameters of a function type

### Description

public FFI\CType::getFuncParameterCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the number of parameters for the underlying function type. If the underlying type is not a function, an FFI\Exception is thrown.

# FFI\CType::getFuncParameterType

(PHP 8 >= 8.1.0)

FFI\CType::getFuncParameterType — Retrieve the type of a function parameter

### Description

public FFI\CType::getFuncParameterType(int `$index`): FFI\CType

Returns the type of a parameter for the underlying function type.

### Parameters

`index`
  Index of the function parameter, zero-based.

### Return Values

Returns the type of a parameter for the underlying function type. If the underlying type is not a function, or the given index is outside of the range of parameters of the function, an FFI\Exception is thrown.

# FFI\CType::getFuncReturnType

(PHP 8 >= 8.1.0)

FFI\CType::getFuncReturnType — Description

### Description

public FFI\CType::getFuncReturnType(): FFI\CType

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getKind

(PHP 8 >= 8.1.0)

FFI\CType::getKind — Description

### Description

public FFI\CType::getKind(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getName

(PHP 7 >= 7.4.0, PHP 8)

FFI\CType::getName — Description

### Description

public FFI\CType::getName(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getPointerType

(PHP 8 >= 8.1.0)

FFI\CType::getPointerType — Description

### Description

public FFI\CType::getPointerType(): FFI\CType

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getSize

(PHP 8 >= 8.1.0)

FFI\CType::getSize — Description

### Description

public FFI\CType::getSize(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getStructFieldNames

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldNames — Description

### Description

public FFI\CType::getStructFieldNames(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# FFI\CType::getStructFieldOffset

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldOffset — Description

### Description

public FFI\CType::getStructFieldOffset(string `$name`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`name`

### Return Values

# FFI\CType::getStructFieldType

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldType — Description

### Description

public FFI\CType::getStructFieldType(string `$name`): FFI\CType

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`name`

### Return Values

## Table of Contents

- FFI\CType::getAlignment — Description
- FFI\CType::getArrayElementType — Description
- FFI\CType::getArrayLength — Description
- FFI\CType::getAttributes — Description
- FFI\CType::getEnumKind — Description
- FFI\CType::getFuncABI — Description
- FFI\CType::getFuncParameterCount — Retrieve the count of parameters of a function type
- FFI\CType::getFuncParameterType — Retrieve the type of a function parameter
- FFI\CType::getFuncReturnType — Description
- FFI\CType::getKind — Description
- FFI\CType::getName — Description
- FFI\CType::getPointerType — Description
- FFI\CType::getSize — Description
- FFI\CType::getStructFieldNames — Description
- FFI\CType::getStructFieldOffset — Description
- FFI\CType::getStructFieldType — Description

# FFI Exceptions

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

## Class synopsis

namespace FFI;
class Exception extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

# FFI Parser Exceptions

(PHP 7 >= 7.4.0, PHP 8)

## Introduction

## Class synopsis

namespace FFI;
final class ParserException extends FFI\Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Examples
  - Basic FFI usage
  - PHP Callbacks
  - A Complete PHP/FFI/preloading Example
- FFI — Main interface to C code and data
  - FFI::addr — Creates an unmanaged pointer to C data
  - FFI::alignof — Gets the alignment
  - FFI::arrayType — Dynamically constructs a new C array type
  - FFI::cast — Performs a C type cast
  - FFI::cdef — Creates a new FFI object
  - FFI::free — Releases an unmanaged data structure
  - FFI::isNull — Checks whether a FFI\CData is a null pointer
  - FFI::load — Loads C declarations from a C header file
  - FFI::memcmp — Compares memory areas
  - FFI::memcpy — Copies one memory area to another
  - FFI::memset — Fills a memory area
  - FFI::new — Creates a C data structure
  - FFI::scope — Instantiates an FFI object with C declarations parsed during preloading
  - FFI::sizeof — Gets the size of C data or types
  - FFI::string — Creates a PHP string from a memory area
  - FFI::type — Creates an FFI\CType object from a C declaration
  - FFI::typeof — Gets the FFI\CType of FFI\CData
- FFI\CData — C Data Handles
- FFI\CType — C Type Handles
  - FFI\CType::getAlignment — Description
  - FFI\CType::getArrayElementType — Description
  - FFI\CType::getArrayLength — Description
  - FFI\CType::getAttributes — Description
  - FFI\CType::getEnumKind — Description
  - FFI\CType::getFuncABI — Description
  - FFI\CType::getFuncParameterCount — Retrieve the count of parameters of a function type
  - FFI\CType::getFuncParameterType — Retrieve the type of a function parameter
  - FFI\CType::getFuncReturnType — Description
  - FFI\CType::getKind — Description
  - FFI\CType::getName — Description
  - FFI\CType::getPointerType — Description
  - FFI\CType::getSize — Description
  - FFI\CType::getStructFieldNames — Description
  - FFI\CType::getStructFieldOffset — Description
  - FFI\CType::getStructFieldType — Description
- FFI\Exception — FFI Exceptions
- FFI\ParserException — FFI Parser Exceptions

# OPcache

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

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.

> Note: If you want to use OPcache with » Xdebug, you must load OPcache before Xdebug.

### Recommended php.ini settings

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 ; prior to PHP 7.2.0
    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.

On Windows, opcache.file_cache_fallback should be enabled, and opcache.file_cache should be set to an already existing and writable directory.

A full list of configuration directives supported by OPcache is also available.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OPcache configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
opcache.enable | 1 | `INI_ALL` |
opcache.enable_cli | 0 | `INI_SYSTEM` | Between PHP 7.1.2 and 7.1.6 inclusive, the default was `1`
opcache.memory_consumption | 128 | `INI_SYSTEM` |
opcache.interned_strings_buffer | 8 | `INI_SYSTEM` |
opcache.max_accelerated_files | 10000 | `INI_SYSTEM` |
opcache.max_wasted_percentage | 5 | `INI_SYSTEM` |
opcache.use_cwd | 1 | `INI_SYSTEM` |
opcache.validate_timestamps | 1 | `INI_ALL` |
opcache.revalidate_freq | 2 | `INI_ALL` |
opcache.revalidate_path | 0 | `INI_ALL` |
opcache.save_comments | 1 | `INI_SYSTEM` |
opcache.fast_shutdown | 0 | `INI_SYSTEM` | Removed in PHP 7.2.0
opcache.enable_file_override | 0 | `INI_SYSTEM` |
opcache.optimization_level | 0x7FFEBFFF | `INI_SYSTEM` | Changed from `0x7FFFBFFF` in PHP 7.3.0
opcache.inherited_hack | 1 | `INI_SYSTEM` | Removed in PHP 7.3.0
opcache.dups_fix | 0 | `INI_ALL` |
opcache.blacklist_filename | "" | `INI_SYSTEM` |
opcache.max_file_size | 0 | `INI_SYSTEM` |
opcache.consistency_checks | 0 | `INI_ALL` | Disabled as of 8.1.18 and 8.2.5. Removed as of PHP 8.3.0.
opcache.force_restart_timeout | 180 | `INI_SYSTEM` |
opcache.error_log | "" | `INI_SYSTEM` |
opcache.log_verbosity_level | 1 | `INI_SYSTEM` |
opcache.record_warnings | 0 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.preferred_memory_model | "" | `INI_SYSTEM` |
opcache.protect_memory | 0 | `INI_SYSTEM` |
opcache.mmap_base | `null` | `INI_SYSTEM` | Windows only.
opcache.restrict_api | "" | `INI_SYSTEM` |
opcache.file_update_protection | 2 | `INI_ALL` |
opcache.huge_code_pages | 0 | `INI_SYSTEM` |
opcache.lockfile_path | "/tmp" | `INI_SYSTEM` |
opcache.opt_debug_level | 0 | `INI_SYSTEM` | Available as of PHP 7.1.0
opcache.file_cache | `null` | `INI_SYSTEM` |
opcache.file_cache_only | 0 | `INI_SYSTEM` |
opcache.file_cache_consistency_checks | 1 | `INI_SYSTEM` |
opcache.file_cache_fallback | 1 | `INI_SYSTEM` | Windows only.
opcache.validate_permission | 0 | `INI_SYSTEM` | Available as of PHP 7.0.14
opcache.validate_root | 0 | `INI_SYSTEM` | Available as of PHP 7.0.14
opcache.preload | "" | `INI_SYSTEM` | Available as of PHP 7.4.0
opcache.preload_user | "" | `INI_SYSTEM` | Available as of PHP 7.4.0
opcache.cache_id | "" | `INI_SYSTEM` | Windows only. Available as of PHP 7.4.0
opcache.jit | "disable" | `INI_ALL` | Available as of PHP 8.0.0. Prior to PHP 8.4.0, the default value was "tracing".
opcache.jit_buffer_size | 64M | `INI_SYSTEM` | Available as of PHP 8.0.0. Prior to PHP 8.4.0, the default value was 0.
opcache.jit_debug | 0 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_bisect_limit | 0 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_prof_threshold | 0.005 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_max_root_traces | 1024 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_max_side_traces | 128 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_max_exit_counters | 8192 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_hot_loop | 64 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_hot_func | 127 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_hot_return | 8 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_hot_side_exit | 8 | `INI_SYSTEM` | Available as of PHP 8.0.0
opcache.jit_blacklist_root_trace | 16 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_blacklist_side_trace | 8 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_max_loop_unrolls | 8 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_max_recursive_calls | 2 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_max_recursive_returns | 2 | `INI_ALL` | Available as of PHP 8.0.0
opcache.jit_max_polymorphic_calls | 2 | `INI_ALL` | Available as of PHP 8.0.0

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`opcache.enable` bool
  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 in a script will generate a warning.
`opcache.enable_cli` bool
  Enables the opcode cache for the CLI version of PHP.
`opcache.memory_consumption` int
  The size of the shared memory storage used by OPcache, in megabytes. The minimum permissible value is `"8"`, which is enforced if a smaller value is set.
`opcache.interned_strings_buffer` int
  The amount of memory used to store interned strings, in megabytes. The maximum value is 32767 on 64bit architectures, and 4095 on 32bit architectures.

  > Note: Prior to PHP 8.4.0, the maximum value was 4095 megabytes on all architectures.

`opcache.max_accelerated_files` int
  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, 262237, 524521, 1048793 }` that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 1000000. Values outside of this range are clamped to the permissible range.
`opcache.max_wasted_percentage` int
  The maximum percentage of wasted memory that is allowed before a restart is scheduled, if there is insufficient free memory. The maximum permissible value is `"50"`, which is enforced if a larger value is set.
`opcache.use_cwd` bool
  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` bool

  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.

  > Note: OPcache may still validate the timestamp of a file at compile-time if opcache.file_update_protection or opcache.max_file_size options are set to non-zero values.

`opcache.revalidate_freq` int
  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` bool
  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` bool
  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.fast_shutdown` bool
  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. This directive has been removed in PHP 7.2.0. A variant of the fast shutdown sequence has been integrated into PHP and will be automatically used if possible.
`opcache.enable_file_override` bool
  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` int
  A bitmask that controls which optimisation passes are executed. The default value is `0x7FFEBFFF`, which enables all safe optimizations. Disabling optimizations or enabling unsafe optimizations is mostly useful for debugging/developing the optimizer. Each bit in the bitmask enables a specific optimization pass:

  Optimization Pass Bitmask
  Bit | Pass Name | Description | Default
  --- | --- | --- | ---
  0 | PASS_1 | Simple peephole optimizations | On
  1 | PASS_2 | Unused (got merged into PASS_1) | On
  2 | PASS_3 | Simple jump optimization | On
  3 | PASS_4 | Call optimization | On
  4 | PASS_5 | Control Flow Graph based optimization | On
  5 | PASS_6 | Data Flow Analysis based optimization | On
  6 | PASS_7 | Whether call graph should be used for SSA-based optimizations | On
  7 | PASS_8 | Sparse conditional constant propagation | On
  8 | PASS_9 | Temporary variable optimization | On
  9 | PASS_10 | Removal of NOP opcodes | On
  10 | PASS_11 | Literal compaction | On
  11 | PASS_12 | Pre-compute call stack size | On
  12 | PASS_13 | Unused variable removal | On
  13 | PASS_14 | Dead code elimination | On
  14 | PASS_15 | Collect and substitute constant declarations (unsafe) | Off
  15 | PASS_16 | Trivial function inlining (part of call optimization) | On
  16 | (Flag) | Ignore possibility of operator overloading (unsafe) | Off

  > Note: Safe vs Unsafe Optimizations
  > Safe optimizations (enabled by default) preserve the exact behavior of PHP code while improving performance. They include dead code elimination, constant folding, and jump optimization. Unsafe optimizations (disabled by default) may alter behavior in edge cases:

  > - Bit 14: Collecting constants. Constants are substituted at compile-time, ignoring runtime declaration order:
  >   `<?php
  >   echo getA(); // Outputs: "hello" instead of throwing an Error
  >   const A = "hello";
  >   function getA() { return A; }`
  > - Bit 16: Ignoring operator overloading. Unsafe when using classes with `do_operation` (e.g. GMP, BCMath) in arithmetic operations. With type declarations, the optimizer can apply the same optimizations safely.

`opcache.inherited_hack` bool
  This configuration directive is ignored.
`opcache.dups_fix` bool
  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` int
  The maximum file size that will be cached, in bytes. If this is `0`, all files will be cached.
`opcache.consistency_checks` int
  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.

  > Note: Disabled as of 8.1.18 and 8.2.5. Removed as of PHP 8.3.0.

`opcache.force_restart_timeout` int
  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 2 or above, a warning will be recorded in the error log when this occurs. This directive is not supported on Windows.
`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` int
  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.record_warnings` bool
  If enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.
`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` bool
  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.
`opcache.restrict_api` string
  Allows calling OPcache API functions only from PHP scripts which path is started from specified string. The default `""` means no restriction.
`opcache.file_update_protection` string
  Prevents caching files that are less than this number of seconds old. It protects from caching of incompletely updated files. In case all file updates are atomic, performance can be increased by setting this to `0`. This will allow files to be cached immediately.
`opcache.huge_code_pages` bool
  Enables or disables copying of PHP code (text segment) into HUGE PAGES. This should improve performance, but requires appropriate OS configuration. Available on Linux as of PHP 7.0.0, and on FreeBSD as of PHP 7.4.0.
`opcache.lockfile_path` string
  Absolute path used to store shared lockfiles (for *nix only)
`opcache.opt_debug_level` string
  Produces opcode dumps for debugging different stages of optimizations. 0x10000 will output opcodes as the compiler produced them before any optimization occurs while 0x20000 will output optimized codes.
`opcache.file_cache` string
  Enables and sets the second level cache directory. It should improve performance when SHM memory is full, at server restart or SHM reset. The default `""` disables file based caching.
`opcache.file_cache_only` bool
  Enables or disables opcode caching in shared memory.

  > Note: Prior to PHP 8.1.0, disabling this directive with an already populated file cache required to manually clear the file cache.

`opcache.file_cache_consistency_checks` bool
  Enables or disables checksum validation when script loaded from file cache.
`opcache.file_cache_fallback` bool
  Implies `opcache.file_cache_only=1` for a certain process that failed to reattach to shared memory (Windows only). Explicitly enabling the file cache is required.
  Caution

  Disabling this configuration option may prevent processes to start, and is therefore discouraged.

`opcache.validate_permission` bool
  Validates the cached file permissions against the current user.
`opcache.validate_root` bool
  Prevents name collisions in chroot'ed environments. This should be enabled in all chroot'ed environments to prevent access to files outside the chroot.
`opcache.preload` string
  Specifies a PHP script that is going to be compiled and executed at server start-up, and which may preload other files, either by includeing them or by using the opcache_compile_file() function. All the entities (e.g. functions and classes) defined in these files will be available to requests out of the box, until the server is shut down.

  > Note: Preloading is not supported on Windows.

`opcache.preload_user` string
  Lets the preloading to be run as the specified system user. This is useful for servers that startup as root before switching to an unprivileged system user. Preloading as root is not allowed by default for security reasons, unless this directive is explicitly set to `root`. As of PHP 8.3.0, this directive does not need to be set in order to allow preloading while running as root when using the CLI SAPI or phpdbg SAPI.
`opcache.cache_id` string

  On Windows, all processes running the same PHP SAPI under the same user account having the same cache ID share a single OPcache instance. The value of the cache ID can be freely chosen.

  Tip

  For IIS, different application pools can have their own OPcache instance by using the environment variable APP_POOL_ID as `opcache.cache_id`.

`opcache.jit` string|int
  For typical usage, this option accepts one of four string values:
  - `disable`: Completely disabled, cannot be enabled at runtime.
  - `off`: Disabled, but can be enabled at runtime.
  - `tracing`/`on`: Use tracing JIT. Enabled by default and recommended for most users.
  - `function`: Use function JIT.

  For advanced usage, this option accepts a 4-digit integer `CRTO`, where the digits mean:

  `C` (CPU-specific optimization flags)
    - `0`: Disable CPU-specific optimization.
    - `1`: Enable use of AVX, if the CPU supports it.
  `R` (register allocation)
    - `0`: Don't perform register allocation.
    - `1`: Perform block-local register allocation.
    - `2`: Perform global register allocation.
  `T` (trigger)
    - `0`: Compile all functions on script load.
    - `1`: Compile functions on first execution.
    - `2`: Profile functions on first request and compile the hottest functions afterwards.
    - `3`: Profile on the fly and compile hot functions.
    - `4`: Currently unused.
    - `5`: Use tracing JIT. Profile on the fly and compile traces for hot code segments.
  `O` (optimization level)
    - `0`: No JIT.
    - `1`: Minimal JIT (call standard VM handlers).
    - `2`: Inline VM handlers.
    - `3`: Use type inference.
    - `4`: Use call graph.
    - `5`: Optimize whole script.
  The `"tracing"` mode corresponds to `CRTO = 1254`, the `"function"` mode corresponds to `CRTO = 1205`.
`opcache.jit_buffer_size` int
  The amount of shared memory to reserve for compiled JIT code. A zero value disables the JIT. When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
`opcache.jit_debug` int
  A bit mask specifying which JIT debug output to enable. For possible values, please consult » zend_jit.h (search for macro definitions beginning with `ZEND_JIT_DEBUG`).
`opcache.jit_bisect_limit` int
  Debugging option that disables JIT compilation after compiling a certain number of functions. This may be helpful to bisect the source of a JIT miscompilation. Note: this option only works when JIT trigger is set to 0 (compile on script load) or 1 (compile on first execution), e.g. `opcache.jit=1215`. See more in opcache.jit option.
`opcache.jit_prof_threshold` float
  When using the "profile on first request" trigger mode, this threshold determines whether a function is considered hot. The number of calls to the function divided by the number of calls to all functions must be above the threshold. For example, a threshold of 0.005 means that functions that made up more than 0.5% of all calls will be JIT compiled.
`opcache.jit_max_root_traces` int
  Maximum number of root traces. The root trace is an execution flow taking one path through the code firstly, which is a unit of JIT compilation. JIT will not compile new code if it reaches this limit.
`opcache.jit_max_side_traces` int
  Maximum number of side traces a root trace may have. The side trace is another execution flow that does not follow the path of compiled root trace. Side traces belonging to the same root trace will not be compiled if it reaches this limit.
`opcache.jit_max_exit_counters` int
  Maximum number of side trace exit counters. This limits the total number of side traces there may be, across all root traces.
`opcache.jit_hot_loop` int
  After how many iterations a loop is considered hot. Valid value range is `[0,255]`; for any setting out of this range, e.g. `-1` or `256`, default value will be used instead. `0` will disable JIT to trace and compile any loops.
`opcache.jit_hot_func` int
  After how many calls a function is considered hot. Valid value range is `[0,255]`; for any setting out of this range, e.g. `-1` or `256`, default value will be used instead. `0` will disable JIT to trace and compile any functions.
`opcache.jit_hot_return` int
  After how many returns a return is considered hot. Valid value range is `[0,255]`; for any setting out of this range, e.g. `-1` or `256`, default value will be used instead. `0` will disable JIT to trace and compile any returns.
`opcache.jit_hot_side_exit` int
  After how many exits a side exit is considered hot. Valid value range is `[0,255]`; for any setting out of this range, e.g. `-1` or `256`, default value will be used instead. `0` will disable JIT to trace and compile any side exits.
`opcache.jit_blacklist_root_trace` int
  Maximum number of times the compilation of a root trace is attempted before it is blacklisted.
`opcache.jit_blacklist_side_trace` int
  Maximum number of times the compilation of a side trace is attempted before it is blacklisted.
`opcache.jit_max_loop_unrolls` int
  Maximum number of attempts to unroll a loop in a side trace, trying to reach the root trace and close the outer loop.
`opcache.jit_max_recursive_calls` int
  Maximum number of unrolled recursive call loops.
`opcache.jit_max_recursive_returns` int
  Maximum number of unrolled recursive return loops.
`opcache.jit_max_polymorphic_calls` int
  Maximum number of attempts to inline polymorphic (dynamic or method) calls. Calls above this limit are treated as megamorphic and are not inlined.

# Preloading

As of PHP 7.4.0, PHP can be configured to preload scripts into the opcache when the engine starts. Any functions, classes, interfaces, or traits (but not constants) in those files will then become globally available for all requests without needing to be explicitly included. That trades convenience and performance (because the code is always available) for baseline memory usage. It also requires restarting the PHP process to clear pre-loaded scripts, meaning this feature is only practical to use in production, not in a development environment.

Note that the optimal tradeoff between performance and memory may vary with the application. "Preload everything" may be the easiest strategy, but not necessarily the best strategy. Additionally, preloading is only useful when there is a persistent process from one request to another. That means while it can work in a CLI script if the opcache is enabled, it's generally pointless. The exception is when using preloading on FFI libraries.

> Note: Preloading is not supported on Windows.

Configuring preloading involves two steps, and requires that the opcache be enabled. First, set the opcache.preload value in php.ini:

    opcache.preload=preload.php

preload.php is an arbitrary file that will run once at server startup (PHP-FPM, mod_php, etc.) and load code into persistent memory. In servers that startup as root before switching to an unprivileged system user, or if PHP will be run as root (not recommended), the opcache.preload_user value can specify the system user to run the preloading. Running preloading as root is not allowed by default. Set `opcache.preload_user=root` to explicitly allow it.

In the preload.php script, any file referenced by include, include_once, require, require_once, or opcache_compile_file() will be parsed into persistent memory. In the following example, all .php files in the src directory will be preloaded, unless they are a `Test` file.

`<?php
$directory = new RecursiveDirectoryIterator(__DIR__ . '/src');
$fullTree = new RecursiveIteratorIterator($directory);
$phpFiles = new RegexIterator($fullTree, '/.+((?<!Test)+\.php$)/i', RecursiveRegexIterator::GET_MATCH);
foreach ($phpFiles as $key => $file) {
require_once $file[0];
}
?>`

Both include and opcache_compile_file() will work, but have different implications for how code gets handled.

- include will execute code in the file, while opcache_compile_file() will not. That means only the former supports conditional declaration (functions declared inside an if-block).
- Because include will execute code, nested included files will also be parsed and their declarations preloaded.
- opcache_compile_file() can load files in any order. That is, if a.php defines class `A` and b.php defines class `B` that extends `A`, then opcache_compile_file() can load those two files in any order. When using include, however, a.php must be included first.
- In either case, if a later script includes a file that has already been preloaded then its contents will still execute, but any symbols it defines will not be re-defined. Using include_once will not prevent the file from being included a second time. It may be necessary to load a file again in order to include global constants defined in it, as those are not handled by preloading.

Which approach is better therefore depends on the desired behavior. With code that would otherwise use an autoloader, opcache_compile_file() allows for greater flexibility. With code that would otherwise be loaded manually, include will be more robust.

# OPcache Functions

# opcache_compile_file

(PHP 5 >= 5.5.5, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_compile_file — Compiles and caches a PHP script without executing it

### Description

opcache_compile_file(string `$filename`): bool

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.

### Parameters

`filename`
  The path to the PHP script to be compiled.

### Return Values

Returns `true` if `filename` was compiled successfully or `false` on failure.

### Errors/Exceptions

If `filename` cannot be loaded or compiled, an error of level `E_WARNING` is generated. You may use @ to suppress this warning.

### See Also

- opcache_invalidate() - Invalidates a cached script

# opcache_get_configuration

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_get_configuration — Get configuration information about the cache

### Description

opcache_get_configuration(): array|false

This function returns configuration information about the cache instance

### Parameters

This function has no parameters.

### Return Values

Returns an array of information, including ini, blacklist and version

### Errors/Exceptions

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.

### See Also

- opcache_get_status() - Get status information about the cache

# opcache_get_status

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_get_status — Get status information about the cache

### Description

opcache_get_status(bool `$include_scripts` = `true`): array|false

This function returns state information about the in-memory cache instance. It will not return any information about the file cache.

### Parameters

`include_scripts`
  Include script specific state information

### Return Values

Returns an array of information, optionally containing script specific state information, or `false` on failure.

### Errors/Exceptions

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.

### Changelog

Version | Description
--- | ---
PHP 8.3.0 | `opcache_get_status()['scripts'][n]['revalidate']` now contains a Unix timestamp of when the next revalidation of the scripts timestamp is due, as dictated by the `opcache.revalidate_freq` INI directive.

### Examples

Example #1 A opcache_get_status() example

`<?php
var_dump(opcache_get_status());
?>`

The above example will output something similar to:

    array(9) {
      'opcache_enabled' =>
      bool(true)
      'cache_full' =>
      bool(false)
      'restart_pending' =>
      bool(false)
      'restart_in_progress' =>
      bool(false)
      'memory_usage' =>
      array(4) {
        'used_memory' =>
        int(9167936)
        'free_memory' =>
        int(125049792)
        'wasted_memory' =>
        int(0)
        'current_wasted_percentage' =>
        double(0)
      }
      'interned_strings_usage' =>
      array(4) {
        'buffer_size' =>
        int(8388608)
        'used_memory' =>
        int(2593616)
        'free_memory' =>
        int(5794992)
        'number_of_strings' =>
        int(10358)
      }
      'opcache_statistics' =>
      array(13) {
        'num_cached_scripts' =>
        int(0)
        'num_cached_keys' =>
        int(0)
        'max_cached_keys' =>
        int(16229)
        'hits' =>
        int(0)
        'start_time' =>
        int(1733310010)
        'last_restart_time' =>
        int(0)
        'oom_restarts' =>
        int(0)
        'hash_restarts' =>
        int(0)
        'manual_restarts' =>
        int(0)
        'misses' =>
        int(0)
        'blacklist_misses' =>
        int(0)
        'blacklist_miss_ratio' =>
        double(0)
        'opcache_hit_rate' =>
        double(0)
      }
      'scripts' =>
      array(0) {
      }
      'jit' =>
      array(7) {
        'enabled' =>
        bool(false)
        'on' =>
        bool(false)
        'kind' =>
        int(5)
        'opt_level' =>
        int(4)
        'opt_flags' =>
        int(6)
        'buffer_size' =>
        int(0)
        'buffer_free' =>
        int(0)
      }
    }

### See Also

- opcache_get_configuration() - Get configuration information about the cache

# opcache_invalidate

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.0)

opcache_invalidate — Invalidates a cached script

### Description

opcache_invalidate(string `$filename`, bool `$force` = `false`): bool

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. This function only invalidates in-memory cache and not file cache.

### Parameters

`filename`
  The path to the script being invalidated.
`force`
  If set to `true`, the script will be invalidated regardless of whether invalidation is necessary.

### Return Values

Returns `true` if the opcode cache for `filename` was invalidated or if there was nothing to invalidate, or `false` if the opcode cache is disabled.

### See Also

- opcache_compile_file() - Compiles and caches a PHP script without executing it
- opcache_reset() - Resets the contents of the opcode cache

# opcache_is_script_cached

(PHP 5 >= 5.5.11, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.4)

opcache_is_script_cached — Tells whether a script is cached in OPCache

### Description

opcache_is_script_cached(string `$filename`): bool

This function checks if a PHP script has been cached in OPCache. This can be used to more easily detect the "warming" of the cache for a particular script. This function only checks in-memory cache, not file cache. In order to check file cache, use opcache_is_script_cached_in_file_cache().

### Parameters

`filename`
  The path to the PHP script to be checked.

### Return Values

Returns `true` if `filename` is cached in OPCache in-memory cache, `false` otherwise.

### See Also

- opcache_compile_file() - Compiles and caches a PHP script without executing it
- opcache_is_script_cached_in_file_cache() - Tells whether a script is cached in OPCache file cache

# opcache_is_script_cached_in_file_cache

(PHP 8 >= 8.5.0)

opcache_is_script_cached_in_file_cache — Tells whether a script is cached in OPCache file cache

### Description

opcache_is_script_cached_in_file_cache(string `$filename`): bool

This function checks if a PHP script has been cached in OPCache. This can be used to more easily detect the "warming" of the cache for a particular script. This function only checks file cache, not in-memory cache. In order to check in-memory cache, use opcache_is_script_cached().

### Parameters

`filename`
  The path to the PHP script to be checked.

### Return Values

Returns `true` if `filename` is cached in OPCache, `false` otherwise.

### See Also

- opcache_compile_file() - Compiles and caches a PHP script without executing it
- opcache_is_script_cached() - Tells whether a script is cached in OPCache

# opcache_jit_blacklist

(PHP 8 >= 8.4.0)

opcache_jit_blacklist — Blacklists a function from being JIT compiled

### Description

opcache_jit_blacklist( Closure `$closure` ): void

This function blacklists a particular function from being JIT compiled when Tracing JIT is in use. The function is specified using a Closure.

Warning

Any parts of the function that were already JIT compiled remain unaffected and will still be JIT compiled.

### Parameters

`closure`
  The function to blacklist, represented as a first class callable. It is also possible to pass an anonymous function, in which case the anonymous function itself is blacklisted.

### Return Values

No value is returned.

### Examples

Example #1 opcache_jit_blacklist() basic example

`<?php
function foo() {
$x = 1;
$x += 0;
++$x;
var_dump($x);
}
opcache_jit_blacklist(foo(...));
foo();
?>`

### See Also

- opcache_invalidate() - Invalidates a cached script
- opcache_reset() - Resets the contents of the opcode cache

# opcache_reset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.0)

opcache_reset — Resets the contents of the opcode cache

### Description

opcache_reset(): bool

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 only resets in-memory cache, not the file cache.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the opcode cache was reset, or `false` if the opcode cache is disabled or the restart is pending or in progress (see opcache_get_status()).

### See Also

- opcache_invalidate() - Invalidates a cached script
- opcache_get_status() - Get status information about the cache

## Table of Contents

- opcache_compile_file — Compiles and caches a PHP script without executing it
- opcache_get_configuration — Get configuration information about the cache
- opcache_get_status — Get status information about the cache
- opcache_invalidate — Invalidates a cached script
- opcache_is_script_cached — Tells whether a script is cached in OPCache
- opcache_is_script_cached_in_file_cache — Tells whether a script is cached in OPCache file cache
- opcache_jit_blacklist — Blacklists a function from being JIT compiled
- opcache_reset — Resets the contents of the opcode cache

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Preloading
- OPcache Functions
  - opcache_compile_file — Compiles and caches a PHP script without executing it
  - opcache_get_configuration — Get configuration information about the cache
  - opcache_get_status — Get status information about the cache
  - opcache_invalidate — Invalidates a cached script
  - opcache_is_script_cached — Tells whether a script is cached in OPCache
  - opcache_is_script_cached_in_file_cache — Tells whether a script is cached in OPCache file cache
  - opcache_jit_blacklist — Blacklists a function from being JIT compiled
  - opcache_reset — Resets the contents of the opcode cache

# Output Buffering Control

# Introduction

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

# Installing/Configuring

## Table of Contents

- Runtime Configuration

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Output Control configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
output_buffering | `"0"` | `INI_PERDIR` |
output_handler | `null` | `INI_PERDIR` |
implicit_flush | `"0"` | `INI_ALL` |
url_rewriter.tags | `"form="` | `INI_ALL` | As of PHP 7.1.0, this INI setting only affects output_add_rewrite_var(). Prior to PHP 7.1.0, this INI setting enabled transparent session id support (see session.trans_sid_tags).
url_rewriter.hosts | `$_SERVER['HTTP_HOST']` is used as default. | `INI_ALL` | Available as of PHP 7.1.0

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`output_buffering` bool/int

  Output buffering for all files can be enabled by setting this directive to `"On"`. To limit the size of the buffer, a number/quantity corresponding to the maximum numbers of bytes allowed can be used instead of `"On"` for the value of this directive. For example `output_buffering=4096`. This directive is always Off in PHP-CLI.

`output_handler` string

  The output of scripts can be redirected to a function. For example setting `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:

  > mb_output_handler() and ob_iconv_handler() cannot be used together and ob_gzhandler() and zlib.output_compression cannot be used with any of the following: mb_output_handler(), ob_gzhandler(), zlib.output_compression, the 'URL-Rewriter' handler (see session.use_trans_sid and output_add_rewrite_var()).

  > Note:

  > Only built-in functions can be used with this directive. For user defined functions, use ob_start().

`implicit_flush` bool

  `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 any function producing output (such as 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().

`url_rewriter.tags` string
  `url_rewriter.tags` specifies HTML tags and attributes in which URLs are rewritten by output_add_rewrite_var() values. Defaults to `"form="`. Adding `"form="` or any `form` attribute will add a hidden `input` element to the `form` with a name and value attribute for each name-value pair passed to output_add_rewrite_var().
  Caution

  Adding the same tag more than once to `url_rewriter.tags` will only use the first occurrence during the URL rewriting process.

  > Note: Prior to PHP 7.1.0, url_rewriter.tags was used to specify session.trans_sid_tags.

`url_rewriter.hosts` string
  `url_rewriter.hosts` specifies which hosts are rewritten to include output_add_rewrite_var() values. Defaults to `$_SERVER['HTTP_HOST']`. Multiple hosts can be specified by a comma separated list that does not include spaces. For example `"php.net,wiki.php.net,bugs.php.net"`.

# Predefined Constants

The constants below are always available as part of the PHP core.

Status flags passed to output handler

The following flags are passed to the second (`phase`) parameter of the output handler set by ob_start() as part of a bitmask:

`PHP_OUTPUT_HANDLER_START` (int)

  Indicates that output buffering has begun.

`PHP_OUTPUT_HANDLER_WRITE` (int)

  Indicates that the output buffer is being flushed, and had data to output.

`PHP_OUTPUT_HANDLER_FLUSH` (int)

  Indicates that the buffer has been flushed.

`PHP_OUTPUT_HANDLER_CLEAN` (int)

  Indicates that the output buffer has been cleaned.

`PHP_OUTPUT_HANDLER_FINAL` (int)

  Indicates that this is the final output buffering operation.

`PHP_OUTPUT_HANDLER_CONT` (int)

  Indicates that the buffer has been flushed, but output buffering will continue.

  This is an alias for `PHP_OUTPUT_HANDLER_WRITE`.

`PHP_OUTPUT_HANDLER_END` (int)

  Indicates that output buffering has ended.

  This is an alias for `PHP_OUTPUT_HANDLER_FINAL`.

Output buffer control flags

The following flags can be passed to the third (`flags`) parameter of the output handler set by ob_start() as a bitmask:

`PHP_OUTPUT_HANDLER_CLEANABLE` (int)

  Controls whether an output buffer created by ob_start() can be cleaned by ob_clean(). This flag does not control the behaviour of ob_end_clean() or ob_get_clean().

`PHP_OUTPUT_HANDLER_FLUSHABLE` (int)

  Controls whether an output buffer created by ob_start() can be flushed by ob_flush(). This flag does not control the behaviour of ob_end_flush() or ob_get_flush().

`PHP_OUTPUT_HANDLER_REMOVABLE` (int)

  Controls whether an output buffer created by ob_start() can be removed before the end of the script or when calling ob_end_clean(), ob_end_flush(), ob_get_clean() or ob_get_flush().

`PHP_OUTPUT_HANDLER_STDFLAGS` (int)

  The default set of output buffer flags; currently equivalent to `PHP_OUTPUT_HANDLER_CLEANABLE` | `PHP_OUTPUT_HANDLER_FLUSHABLE` | `PHP_OUTPUT_HANDLER_REMOVABLE`.

Output handler status flags

The following flags are part of the `flags` bitmask returned by ob_get_status():

`PHP_OUTPUT_HANDLER_STARTED` (int)

  Indicates that the output handler was called.

`PHP_OUTPUT_HANDLER_DISABLED` (int)

  Indicates that the output handler is disabled. This flag is set when the output handler returns `false` or fails while processing the buffer. Prior to PHP 8.4.0, this flag could be set when starting an output buffer.

`PHP_OUTPUT_HANDLER_PROCESSED` (int)

  Indicates that the output handler successfully processed the buffer. Available as of PHP 8.4.0.

# Output Buffering

Output buffering is the buffering (temporary storage) of output before it is flushed (sent and discarded) to the browser (in a web context) or to the shell (on the command line). While output buffering is active no output is sent from the script, instead the output is stored in an internal buffer.

## Buffering Affecting PHP

PHP relies on the underlying software/hardware infrastructure when flushing output. Buffering implemented by consoles on the command line (e.g. line buffered) or web servers and browser in a web context (e.g. fully buffered) do affect when output is displayed to the end-user. Some of these effects can be eliminated by fine-tuning server settings and/or aligning buffer sizes of the various layers.

## Output Buffering Control In PHP

PHP provides a fully buffered user-level output buffer with functions to start, manipulate and turn off the buffer (most ob_* functions), and two functions to flush the underlying system buffers (flush() and ob_implicit_flush()). Some of this functionality can be set and/or configured using the appropriate php.ini settings as well.

## Use Cases

Output buffering is generally useful in situations when the buffered output is modified or inspected, or it is used more than once in a request; or when the controlled flushing of output is desired. Specific use cases include:

- caching the result of compute/time intensive scripts for example by generating static `HTML` pages
- re-using the generated output by displaying it, saving it to a file and/or sending it by email
- flushing the `head` of an `HTML` page separate from the `body` allows browsers to load external resources while the script executes potentially more time consuming processes (e.g. database/file access, external network connection). This is only useful if the `HTTP` status code cannot change after the headers are sent
- extracting information from functions that would otherwise produce output (e.g. phpinfo())
- controlling the output of third-party code by modifying/using parts (e.g. extracting data, replacing words/phrases, adding missing `HTML` tags), or discarding it entirely under certain conditions (e.g. errors)
- polyfilling certain unavailable web server functionality (e.g. compressing or encoding output)

# Flushing System Buffers

PHP provides two related ways to flush (send and discard the contents of) system buffers: through calling flush() and through enabling implicit flushing with ob_implicit_flush() or the implicit_flush php.ini setting.

## Output Flushing Behaviour

With implicit flushing disabled, PHP will flush output only when flush() is called or when the script ends.

With implicit flushing enabled, PHP will attempt to flush after every block of code resulting in output. Output in this context is non-zero length data that is:

- outside of the `<?php ?>` tags
- printed by language constructs and functions whose explicit purpose is to output user provided variables or strings such as echo, print, printf(), var_dump(), var_export(), vprintf()
- printed by functions whose purpose is to collect and output data/information on the running script or PHP such as debug_print_backtrace(), phpcredits(), phpinfo(), ReflectionExtension::info()
- printed by PHP on an uncaught exception or an unhandled error (subject to the settings of display_errors and error_reporting)
- anything written to `php://output`

> Note: Printing empty strings or sending headers is not considered output and will not result in a flush operation.

Warning

If implicit flushing is enabled, control characters (e.g. `"\n"`, `"\r"`, `"\0"`) will trigger flushing as well.

## Limitations

This functionality cannot flush user-level output buffers. To use these together, user-level output buffers must be flushed before flushing system buffers in order for PHP to produce any output.

Warning

Calling flush() or implicit flushing being enabled can interfere with output handlers of user-level output buffers that set and send headers in a web context (e.g. ob_gzhandler()) by sending headers before these handlers can do so.

Buffering implemented by the underlying software/hardware cannot be overridden by PHP and should be taken into account when working with PHP's buffer control functions. Checking the web servers/browsers/consoles buffering settings and working with these can alleviate possible issues. Working in a web context, either the web server's buffering settings or the script's buffering could be adjusted to work in tandem whereas working around the buffering strategies of various browsers can be achieved by adjusting buffering in the PHP script. On consoles that implement line buffering, newline characters could be inserted in the appropriate places before flushing output.

## SAPI Differences In Flushing

Although flushing is implemented by each SAPI in a slightly different way, these implementations fall in one of two categories:

- SAPIs used in a web context will flush headers first followed by the output. `Apache2Handler`, `CGI`, `FastCGI` and `FPM` are such SAPIs
- other SAPIs such as `CLI` and `embed` will flush output only

# User-Level Output Buffers

## Table of Contents

- What Output Is Buffered?
- Nesting Output Buffers
- Buffer Size
- Operations Allowed On Buffers
- Output Handlers
- Working With Output Handlers
- Flags Passed To Output Handlers
- Output Handler Return Values

User-level output buffers can be started, manipulated and terminated from PHP code. Each of these buffers includes an output buffer and an associated output handler function.

## What Output Is Buffered?

PHP's user-level output buffers buffer all output after they are started until they are turned off or the script ends. Output in the context of PHP's user-level output buffer is everything that PHP would display or send back to the browser. In practical terms, output is non-zero length data that is:

- outside of the `<?php ?>` tags
- printed by language constructs and functions whose explicit purpose is to output user provided variables or strings such as echo, print, printf(), var_dump(), var_export(), vprintf()
- printed by functions whose purpose is to collect and output data/information on the running script or PHP such as debug_print_backtrace(), phpcredits(), phpinfo(), ReflectionExtension::info()
- printed by PHP on an uncaught exception or an unhandled error (subject to the settings of display_errors and error_reporting)
- anything written to `php://output`

> Note: Data that is written directly to `stdout` or passed to an SAPI function with a similar functionality will not be captured by user-level output buffers. This includes writing data to `stdout` with fwrite() or sending headers using header() or setcookie().

## Turning Output Buffering On

Output buffering can be turned on by using the ob_start() function or by setting the output_buffering and output_handler php.ini settings. While both can create output buffers, ob_start() is more flexible as it accepts user-defined functions as output handlers and the operations allowed on the buffer (flush, clean, remove) can be set as well. Buffers started with ob_start() will be active from the line the function was called, while those started with output_buffering will be buffering output from the first line of the script.

PHP is also shipped with a built-in `"URL-Rewriter"` output handler which starts its own output buffer and only allows up to two instances of it running at any time (one for user-level URL-rewriting and one for transparent session id support). These buffers can be started by calling the output_add_rewrite_var() function and/or by enabling the session.use_trans_sid php.ini setting.

The bundled `zlib` extension has its own output buffer which can be enabled by using the zlib.output_compression php.ini setting.

> Note: While `"URL-Rewriter"` is special in that it only allows up to two instances of it running at any one time, all user-level output buffers use the same underlying buffers used by ob_start() with their functionality implemented by a custom output handler function. As such, all of their functionality can be emulated by userland code.

## Nesting Output Buffers

If there is an output buffer active when a new buffer is started, the new buffer will be nested inside the previously active buffer. The inner buffer will behave the same way regardless whether it is nested but output buffered by it will not be buffered by the outer buffer. Only output flushed by the inner buffer will be buffered by the outer buffer.

Most `ob_*` functions only work with the active output buffer (the last one started) therefore only the active buffer can be flushed, cleaned and turned off. The functions that work with other buffers are ob_list_handlers() which returns the list of all output handlers in use and ob_get_status() which can return information on the active buffer only or on all buffers in use.

Calling ob_get_level() or ob_get_status() will return the nesting level of the active output buffer.

Caution

The value for identical levels between ob_get_level() and ob_get_status() is off by one. For ob_get_level() the first level is `1`, whereas for ob_get_status() the first level is `0`.

## Buffer Size

Buffer sizes are expressed by integers and represent the number of bytes the buffer can store without flushing. When the size of output in the buffer exceeds the size of the buffer, the contents of the buffer are sent to the output handler, its return value is flushed and the buffer is cleared.

With the exception of `"URL-Rewriter"`, the size of output buffers can be set when the buffer is started. If set to `0`, the output buffer is only limited by the memory available to PHP. If set to `1`, the buffer is flushed after every block of code producing any non-zero length output.

The size of output buffers can be retrieved by calling ob_get_status().

Output buffers started with ob_start() will have their buffer sizes set to the integer value passed to the function's second `chunk_size` parameter. If omitted, it is set to `0`.

The output buffer started with output_buffering set to `"On"` will have its buffer size set to 0. If set to an integer than buffer size will correspond to that number.

`"URL-Rewriter"`'s buffer size is set to `0`, therefore it is only limited by the memory available to PHP.

The size of `zlib`'s output buffer is controlled by the zlib.output_compression php.ini setting. If set to `"On"` the buffer size will be `"16K"`/`16384`. If set to an integer then buffer size will correspond to that number in bytes.

## Operations Allowed On Buffers

The operations allowed on buffers can be controlled by passing one of the buffer control flags to ob_start()'s third `flags` parameter. If omitted, all operations are allowed by default. If `0` is used instead, the buffer cannot be flushed, cleaned or removed but it's contents can still be retrieved.

`PHP_OUTPUT_HANDLER_CLEANABLE` allows ob_clean() to clean the contents of the buffer.

Warning

The absence of the `PHP_OUTPUT_HANDLER_CLEANABLE` flag will not prevent ob_end_clean() or ob_get_clean() from clearing the contents of the buffer.

`PHP_OUTPUT_HANDLER_FLUSHABLE` allows ob_flush() to flush the contents of the buffer.

Warning

The absence of the `PHP_OUTPUT_HANDLER_FLUSHABLE` flag will not prevent ob_end_flush() or ob_get_flush() from flushing the contents of the buffer.

`PHP_OUTPUT_HANDLER_REMOVABLE` allows ob_end_clean(), ob_end_flush(), ob_get_clean() or ob_get_flush() to turn off the buffer.

`PHP_OUTPUT_HANDLER_STDFLAGS`, the combination of the three flags will allow each of the three operations to be performed on the buffer.

## Flushing, Accessing And Cleaning Buffer Contents

Flushing sends and discards the contents of the active buffer. Output buffers get flushed when the size of the output exceeds the size of the buffer; the script ends or ob_flush(), ob_end_flush() or ob_get_flush() is called.

Caution

Calling ob_end_flush() or ob_get_flush() will turn off the active buffer.

Caution

Flushing buffers will flush the return value of the output handler which can differ from the contents of the buffer. For example, using ob_gzhandler() will compress the output and flush the compressed output.

The contents of the active buffer can be retrieved by calling ob_get_contents(), ob_get_clean() or ob_get_flush().

If only the length of the buffer's contents are needed, ob_get_length() or ob_get_status() will return the length of the contents in bytes.

Caution

Calling ob_get_clean() or ob_get_flush() will turn off the active buffer after returning the its contents.

The contents of the active buffer can be cleaned by calling ob_clean(), ob_end_clean() or ob_get_clean().

Caution

Calling ob_end_clean() or ob_get_clean() will turn off the active buffer.

## Turning Buffers Off

Output buffers can be turned off by calling ob_end_clean(), ob_end_flush(), ob_get_flush() or ob_get_clean().

Warning

Output buffers started without the `PHP_OUTPUT_HANDLER_REMOVABLE` flag cannot be turned off and may generate an `E_NOTICE`.

Every output buffer that has not been closed by the end of the script or when exit() is called will be flushed and turned off by PHP's shutdown process. The buffers will be flushed and turned off in reverse order of their starting up. The last buffered started will be first, the first buffer started will be last to be flushed and turned off.

Caution

If flushing of the buffer's contents is not desired, a custom output handler should be used to prevent flushing during shutdown.

## Output Handlers

Output handlers are callables associated with output buffers that are invoked by calling ob_clean(), ob_flush(), ob_end_flush(), ob_get_flush(), ob_end_clean(), ob_get_clean() or during PHP's shutdown process.

> Note: The shutdown process will flush the return value of the handler.

If omitted or `null` when starting the output buffer the internal `"default output handler"` will be used which returns the unmodified contents of the buffer when invoked. Output handlers can be used to return a modified version of the buffer's contents and/or have side-effects (e.g. send headers).

PHP comes with two internal output handlers: `"default output handler"` and `"URL-Rewriter"` (which is integrated into its own output buffer and only up to two instances of it can be started).

The bundled extensions include four additional output handlers: mb_output_handler(), ob_gzhandler(), ob_iconv_handler(), ob_tidyhandler().

## Working With Output Handlers

When invoked, output handlers are passed the contents of the buffer and a bitmask indicating the status of output buffering.

handler ( string `$buffer` , int `$phase` = ?): string

`buffer`
  Contents of the output buffer.
`phase`
  Bitmask of `PHP_OUTPUT_HANDLER_*` constants .

Warning

Calling any of the following functions from within an output handler will result in a fatal error: ob_clean(), ob_end_clean(), ob_end_flush(), ob_flush(), ob_get_clean(), ob_get_flush(), ob_start().

> Note: If the `PHP_OUTPUT_HANDLER_DISABLED` of a handler is set, the handler will not be invoked by calling ob_end_clean(), ob_end_flush(), ob_get_clean(), ob_get_flush(), ob_clean(), ob_flush() or during PHP's shutdown process. Prior to PHP 8.4.0, this flag had no effect when calling ob_clean() or ob_flush().

> Note: The working directory of the script can change inside the shutdown function under some web servers, e.g. Apache or the built-in web server.

## Flags Passed To Output Handlers

The bitmask passed to the second `phase` parameter of the output handler provides information on the invocation of the handler.

> Note: The bitmask can include more than one flag and the bitwise `&` operator should be used to check whether a flag is set.

Warning

The value of `PHP_OUTPUT_HANDLER_WRITE` and its alias `PHP_OUTPUT_HANDLER_CONT` is `0` therefore whether it is set can only be determined by using an equality operator (`==` or `===`).

The following flags are set in a specific phase of the handler's lifecycle: `PHP_OUTPUT_HANDLER_START` is set when a handler is invoked for the first time. `PHP_OUTPUT_HANDLER_FINAL` or its alias `PHP_OUTPUT_HANDLER_END` is set when a handler is invoked for the last time, i.e. it is being turned off. This flag is also set when buffers are being turned off by PHP's shutdown process.

The following flags are set by a specific invocation of the handler: `PHP_OUTPUT_HANDLER_FLUSH` is set when the handler is invoked by calling ob_flush(). `PHP_OUTPUT_HANDLER_WRITE` or its alias `PHP_OUTPUT_HANDLER_CONT` is set when the size of its contents equals or exceeds the size of the buffer and the handler is invoked while the buffer is being automatically flushed. `PHP_OUTPUT_HANDLER_FLUSH` is set when the handler is invoked by calling ob_clean(), ob_end_clean() or ob_get_clean(). When ob_end_clean() or ob_get_clean() is called, `PHP_OUTPUT_HANDLER_FINAL` is set as well.

> Note: When ob_end_flush() or ob_get_flush() is called, `PHP_OUTPUT_HANDLER_FINAL` is set but `PHP_OUTPUT_HANDLER_FLUSH` is not.

## Output Handler Return Values

The return value of the output handler is internally coerced into a string following standard PHP type semantics, with two exceptions: arrays and booleans.

Arrays are converted into the string `"Array"` but the `Array to string conversion` warning is not triggered.

If the handler returns `false` the contents of the buffer are returned. If the handler returns `true` an empty string is returned.

> Note: If a handler returns `false` or throws an exception its `PHP_OUTPUT_HANDLER_DISABLED` status flag is set.

## Exceptions Thrown In Output Handlers

If an uncaught exception is thrown in an output handler the program terminates and the handler is invoked by the shutdown process after which the `"Uncaught Exception"` error message is flushed.

If the uncaught exception is thrown in a handler invoked by ob_flush(), ob_end_flush() or ob_get_flush(), the contents of the buffer are flushed before the error message.

If an uncaught exception is thrown in an output handler during shutdown, the handler is terminated and neither the contents of the buffer nor the error message is flushed.

> Note: If a handler throws an exception its `PHP_OUTPUT_HANDLER_DISABLED` status flag is set.

## Errors Raised In Output Handlers

If a non-fatal error is raised in an output handler the program continues execution.

If the non-fatal error is raised in a handler invoked by ob_flush(), ob_end_flush() or ob_get_flush(), the buffer flushes certain data depending on the return value of the handler. If the handler returns `false` the buffer and the error message are flushed. If the returns anything else the handler return value is flushed but not the error message.

> Note: If a handler returns `false` its `PHP_OUTPUT_HANDLER_DISABLED` status flag is set.

If a fatal error is raised in an output handler the program terminates and the handler is invoked by the shutdown process after which the error message is flushed.

If the fatal error is raised in a handler invoked by ob_flush(), ob_end_flush() or ob_get_flush(), the contents of the buffers are flushed before the error message.

If a fatal error is raised in an output handler during shutdown the program terminates without flushing the buffer or the error message.

## Output In Output Handlers

In specific circumstances, output produced in the handler is flushed along with the contents of the buffer. This output is not appended to the buffer and is not part of the string returned by ob_get_flush().

During flush operations (calling ob_flush(), ob_end_flush(), ob_get_flush() and during shutdown) if the return value of a handler is `false` the contents of the buffer are flushed followed by the output. If the handler is not invoked during shutdown the handler throwing an exception or exit() being called results in the same behavior.

> Note: If a handler returns `false` its `PHP_OUTPUT_HANDLER_DISABLED` status flag is set.

## Output Handler Status Flags

The handler status flags of the buffer's `flags` bitmask are set every time to the output handler is invoked and are part of the `flags` returned by ob_get_status(). If the handler successfully executes and does not return `false`, `PHP_OUTPUT_HANDLER_STARTED` and `PHP_OUTPUT_HANDLER_PROCESSED` is set. If the handler returns `false` or throws an exception while executing, `PHP_OUTPUT_HANDLER_STARTED` and `PHP_OUTPUT_HANDLER_DISABLED` is set.

> Note: If the `PHP_OUTPUT_HANDLER_DISABLED` of a handler is set, the handler will not be invoked by calling ob_end_clean(), ob_end_flush(), ob_get_clean(), ob_get_flush(), ob_clean(), ob_flush() or during PHP's shutdown process. Prior to PHP 8.4.0, this flag had no effect when calling ob_clean() or ob_flush().

# Examples

## Table of Contents

- Basic usage
- Output rewrite usage

## Basic usage

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. (Headers cannot normally be sent to the browser after data has already been sent.)

## Output rewrite usage

Since PHP 7.1.0, output_add_rewrite_var(), output_reset_rewrite_vars() use dedicated output buffer. i.e. It does not use trans sid output buffer.

Example #1 Output rewrite example

`<?php
// This code works with PHP 7.1.0, 7.0.10, 5.6.25 and up.
// HTTP_HOST is default target host. Set manually to make sample code works.
$_SERVER['HTTP_HOST'] = 'php.net';
// Output rewriter only rewrite form. Add a=href.
// Tags can be specified tag_name=url_attr, e.g. img=src,iframe=src
// No space allowed between settings.
// Form tag is special tag that add hidden input.
ini_set('url_rewriter.tags','a=href,form=');
var_dump(ini_get('url_rewriter.tags'));
// This is added to URL and form
output_add_rewrite_var('test', 'value');
?>
<a href="//php.net/index.php?bug=1234">bug1234</a>
<form action="https://php.net/?bug=1234&edit=1" method="post">
<input type="text" name="title" />
</form>`

The above example will output:

    <a href="//php.net/?bug=1234&test=value">bug1234</a>
    <form action="https://php.net/?bug=1234&edit=1" method="post"><input type="hidden" name="test" value="value" />
     <input type="text" name="title" />
    </form>

Since PHP 7.1.0, output rewrite functions have its own INI settings, url_rewriter.tags and url_rewriter.hosts.

# Output Control Functions

# See Also

See also header() and setcookie().

# flush

(PHP 4, PHP 5, PHP 7, PHP 8)

flush — Flush system output buffer

### Description

flush(): void

Flushes the system write buffers of PHP and the backend used by PHP (e.g.: CGI, a web server). In a command line environment flush() will attempt to flush the contents of the buffers only whereas in a web context headers and the contents of the buffers are flushed.

> Note: flush() may not be able to override the buffering scheme of the web server and it has no effect on any client-side buffering in the browser.

> Note: This function does not have any effect on user level output handlers such as those started by ob_start() or output_add_rewrite_var().

Warning

flush() can interfere with output handlers that set and send headers in a web context (e.g. ob_gzhandler()) by sending headers before these handlers can do so.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.4.0 | Flushing headers without a body will now succeed in FastCGI.

### See Also

- ob_flush() - Flush (send) the return value of the active output handler
- ob_clean() - Clean (erase) the contents of the active output buffer
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off

# ob_clean

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_clean — Clean (erase) the contents of the active output buffer

### Description

ob_clean(): bool

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_CLEAN` flag), discards it's return value and cleans (erases) the contents of the active output buffer.

This function does not turn off the active output buffer like ob_end_clean() or ob_get_clean() does.

ob_clean() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_CLEANABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off
- ob_get_clean() - Get the contents of the active output buffer and turn it off
- ob_flush() - Flush (send) the return value of the active output handler

# ob_end_clean

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_end_clean — Clean (erase) the contents of the active output buffer and turn it off

### Description

ob_end_clean(): bool

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_CLEAN` and `PHP_OUTPUT_HANDLER_FINAL` flags), discards its return value, discards the contents of the active output buffer and turns off the active output buffer.

ob_end_clean() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_REMOVABLE` flag.

ob_end_clean() will discard the contents of the active output buffer even if it was started without the `PHP_OUTPUT_HANDLER_CLEANABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### Examples

The following example shows an easy way to get rid of the contents of the active output buffer:

Example #1 ob_end_clean() example

`<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>`

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_clean() - Clean (erase) the contents of the active output buffer
- ob_get_clean() - Get the contents of the active output buffer and turn it off
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off

# ob_end_flush

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_end_flush — Flush (send) the return value of the active output handler and turn the active output buffer off

### Description

ob_end_flush(): bool

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_FINAL` flag), flushes (sends) it's return value, discards the contents of the active output buffer and turns off the active output buffer.

ob_end_flush() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_REMOVABLE` flag.

ob_end_flush() will flush (send) the return value of the output handler even if the active output buffer was started without the `PHP_OUTPUT_HANDLER_FLUSHABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### Examples

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());
?>`

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_flush() - Flush (send) the return value of the active output handler
- ob_get_flush() - Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off

# ob_flush

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_flush — Flush (send) the return value of the active output handler

### Description

ob_flush(): bool

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_FLUSH` flag), flushes (sends) its return value and discards the contents of the active output buffer.

This function does not turn off the active output buffer like ob_end_flush() or ob_get_flush() does.

ob_flush() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_FLUSHABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_get_flush() - Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
- ob_clean() - Clean (erase) the contents of the active output buffer

# ob_get_clean

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_get_clean — Get the contents of the active output buffer and turn it off

### Description

ob_get_clean(): string|false

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_CLEAN` and `PHP_OUTPUT_HANDLER_FINAL` flags), discards it's return value, returns the contents of the active output buffer and turns off the active output buffer.

ob_get_clean() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_REMOVABLE` flag.

ob_get_clean() will discard the contents of the active output buffer even if it was started without the `PHP_OUTPUT_HANDLER_CLEANABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns the contents of the active output buffer on success or `false` on failure.

Caution

ob_get_clean() will return false but will not generate an `E_NOTICE` if there is no active output buffer.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### Examples

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"

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_clean() - Clean (erase) the contents of the active output buffer
- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off
- ob_get_flush() - Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off

# ob_get_contents

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_get_contents — Return the contents of the output buffer

### Description

ob_get_contents(): string|false

Gets the contents of the output buffer without clearing it.

### Parameters

This function has no parameters.

### Return Values

This will return the contents of the output buffer or `false`, if output buffering isn't active.

### Examples

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"

### See Also

- ob_start() - Turn on output buffering
- ob_get_length() - Return the length of the output buffer

# ob_get_flush

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_get_flush — Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off

### Description

ob_get_flush(): string|false

This function calls the output handler (with the `PHP_OUTPUT_HANDLER_FINAL` flag), flushes (sends) it's return value, returns the contents of the active output buffer and turns off the active output buffer.

ob_get_flush() will fail without an active output buffer started with the `PHP_OUTPUT_HANDLER_REMOVABLE` flag.

ob_get_flush() will flush (send) the return value of the output handler even if the active output buffer was started without the `PHP_OUTPUT_HANDLER_FLUSHABLE` flag.

### Parameters

This function has no parameters.

### Return Values

Returns the contents of the active output buffer on success or `false` on failure.

### Errors/Exceptions

If the function fails it generates an `E_NOTICE`.

### Examples

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

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer
- ob_flush() - Flush (send) the return value of the active output handler
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_get_clean() - Get the contents of the active output buffer and turn it off

# ob_get_length

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

ob_get_length — Return the length of the output buffer

### Description

ob_get_length(): int|false

This will return the length of the contents in the output buffer, in bytes.

### Parameters

This function has no parameters.

### Return Values

Returns the length of the output buffer contents, in bytes, or `false` if no buffering is active.

### Examples

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

### See Also

- ob_start() - Turn on output buffering
- ob_get_contents() - Return the contents of the output buffer

# ob_get_level

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_get_level — Return the nesting level of the output buffering mechanism

### Description

ob_get_level(): int

Returns the nesting level of the output buffering mechanism.

### Parameters

This function has no parameters.

### Return Values

Returns the level of nested output buffering handlers or zero if output buffering is not active.

Caution

The value for identical levels between ob_get_level() and ob_get_status() is off by one. For ob_get_level() the first level is `1`. Whereas for ob_get_status() the first level is `0`.

### See Also

- ob_start() - Turn on output buffering
- ob_get_status() - Get status of output buffers
- ob_get_contents() - Return the contents of the output buffer

# ob_get_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_get_status — Get status of output buffers

### Description

ob_get_status(bool `$full_status` = `false`): array

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

### Parameters

`full_status`

  `true` to return all active output buffer levels. If `false` or not set, only the top level output buffer is returned.

### Return Values

If `full_status` is omitted or `false` a simple array holding status information on the active output level is returned.

If `full_status` is `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.

An empty array is returned if output buffering is not turned on.

ob_get_status() return array elements
Key | Value
--- | ---
name | Name of active output handler (see the return values of ob_list_handlers() for details)
type | `0` (internal handler) or `1` (user supplied handler)
flags | Bitmask of flags set by ob_start(), the type of output handler (see above) and the status of the buffering process ( `PHP_OUTPUT_HANDLER_*` constants). If the handler successfully processed the buffer and did not return `false`, `PHP_OUTPUT_HANDLER_STARTED` and `PHP_OUTPUT_HANDLER_PROCESSED` will be set. If the handler failed while processing the buffer or returned `false`, `PHP_OUTPUT_HANDLER_STARTED` and `PHP_OUTPUT_HANDLER_DISABLED` will be set.
level | Output nesting level (zero based). Note that the value returned for the same level by ob_get_level() is off by one. The first level is `0` for ob_get_status(), and `1` for ob_get_level().
chunk_size | Chunk size in bytes. Set by ob_start() or output_buffering is enabled and its value is set to a positive integer
buffer_size | Output buffer size in bytes
buffer_used | Size of data in output buffer in bytes (the same as the integer return value of ob_get_length())

### Examples

Example #1 Array returned when `full_status` is `false`

    Array
    (
        [name] => URL-Rewriter
        [type] => 0
        [flags] => 112
        [level] => 2
        [chunk_size] => 0
        [buffer_size] => 16384
        [buffer_used] => 1024
    )

Example #2 Array returned when `full_status` is `true`

    Array
    (
        [0] => Array
            (
                [name] => default output handler
                [type] => 0
                [flags] => 112
                [level] => 1
                [chunk_size] => 0
                [buffer_size] => 16384
                [buffer_used] => 2048
            )

        [1] => Array
            (
                [name] => URL-Rewriter
                [type] => 0
                [flags] => 112
                [level] => 2
                [chunk_size] => 0
                [buffer_size] => 16384
                [buffer_used] => 1024
            )

    )

### See Also

- ob_get_level() - Return the nesting level of the output buffering mechanism
- ob_list_handlers() - List all output handlers in use
- ob_get_length() - Return the length of the output buffer
- ob_start() - Turn on output buffering

# ob_implicit_flush

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_implicit_flush — Turn implicit flush on/off

### Description

ob_implicit_flush(bool `$enable` = `true`): void

ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every block of code resulting in output, so that explicit calls to flush() will no longer be needed.

> Note: Printing empty strings or sending headers is not considered output and will not result in a flush operation.

> Note: This function does not have any effect on user level output handlers such as those started by ob_start() or output_add_rewrite_var().

### Parameters

`enable`

  `true` to turn implicit flushing on, `false` otherwise.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | The `enable` expects a bool value now; previously, an int was expected.

### See Also

- flush() - Flush system output buffer
- ob_start() - Turn on output buffering
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off

# ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_list_handlers — List all output handlers in use

### Description

ob_list_handlers(): array

Lists all output handlers in use.

### Parameters

This function has no parameters.

### Return Values

This will return an array with the output handlers in use (if any).

If output_buffering is enabled and no output_handler is set, or no callback or `null` was passed to ob_start(), `"default output handler"` is returned. Enabling output_buffering and setting an output_handler is equivalent to passing an internal (built-in) function to ob_start().

If a callable was passed to ob_start(), the fully qualified name of the callable is returned. If the callable is an object implementing __invoke(), the fully qualified name of the object's __invoke() method is returned. If the callable is a Closure, `"Closure::__invoke"` is returned.

### Examples

Example #1 ob_list_handlers() example

`<?php
// using output_buffering=On, no output_handler set
var_dump(ob_list_handlers());
ob_end_flush();
// no callback or null
ob_start();
var_dump(ob_list_handlers());
ob_end_flush();
// anonymous function
ob_start(function($string) { return $string; });
var_dump(ob_list_handlers());
ob_end_flush();
// arrow function
ob_start(fn($string) => $string);
var_dump(ob_list_handlers());
ob_end_flush();
// first class callable
$firstClassCallable = userDefinedFunction(...);
ob_start([$firstClassCallable, '__invoke']);
var_dump(ob_list_handlers());
ob_end_flush();
// internal (built-in) function
ob_start('print_r');
var_dump(ob_list_handlers());
ob_end_flush();
// user-defined function
function userDefinedFunction($string, $flags) { return $string; };
ob_start('userDefinedFunction');
var_dump(ob_list_handlers());
ob_end_flush();
class MyClass {
public static function staticHandle($string) {
return $string;
}
public static function handle($string) {
return $string;
}
public function __invoke($string) {
return $string;
}
}
// class and static method
ob_start(['MyClass','staticHandle']);
var_dump(ob_list_handlers());
ob_end_flush();
// object and non-static method
ob_start([new MyClass,'handle']);
var_dump(ob_list_handlers());
ob_end_flush();
// invokable object
ob_start(new MyClass);
var_dump(ob_list_handlers());
ob_end_flush();
?>`

The above example will output:

    array(1) {
      [0]=>
      string(22) "default output handler"
    }
    array(1) {
      [0]=>
      string(22) "default output handler"
    }
    array(1) {
      [0]=>
      string(7) "print_r"
    }
    array(1) {
      [0]=>
      string(19) "userDefinedFunction"
    }
    array(1) {
      [0]=>
      string(17) "Closure::__invoke"
    }
    array(1) {
      [0]=>
      string(17) "Closure::__invoke"
    }
    array(1) {
      [0]=>
      string(17) "Closure::__invoke"
    }
    array(1) {
      [0]=>
      string(21) "MyClass::staticHandle"
    }
    array(1) {
      [0]=>
      string(15) "MyClass::handle"
    }
    array(1) {
      [0]=>
      string(17) "MyClass::__invoke"
    }

### See Also

- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_get_flush() - Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
- ob_start() - Turn on output buffering

# ob_start

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_start — Turn on output buffering

### Description

ob_start(?callable `$callback` = `null`, int `$chunk_size` = 0, int `$flags` = `PHP_OUTPUT_HANDLER_STDFLAGS`): bool

This function will turn output buffering on. While output buffering is active no output is sent from the script, instead the output is stored in an internal buffer. See What Output Is Buffered? on exactly what output is affected.

Output buffers are stackable, that is, ob_start() may be called while another buffer is active. If multiple output buffers are active, output is being filtered sequentially through each of them in nesting order. See Nesting Output Buffers for more details.

See User-Level Output Buffers for a detailed description of output buffers.

### Parameters

`callback`

  An optional `callback` callable may be specified. It can also be bypassed by passing `null`.

  `callback` is invoked when the output buffer is flushed (sent), cleaned, or when the output buffer is flushed at the end of the script.

  The signature of the `callback` is as follows:

  handler(string `$buffer`, int `$phase` = ?): string
  `buffer`
    Contents of the output buffer.
  `phase`
    Bitmask of `PHP_OUTPUT_HANDLER_*` constants . See Flags Passed To Output Handlers for more details.

  If `callback` returns `false` the contents of the buffer are returned. See Output Handler Return Values for more details.

  Warning

  Calling any of the following functions from within an output handler will result in a fatal error: ob_clean(), ob_end_clean(), ob_end_flush(), ob_flush(), ob_get_clean(), ob_get_flush(), ob_start().

  See Output Handlers and Working With Output Handlers for more details on `callback`s (output handlers).

`chunk_size`

  If the optional parameter `chunk_size` is passed, the buffer will be flushed after any block of code resulting in output that causes the buffer's length to equal or exceed `chunk_size`. The default value `0` means that all output is buffered until the buffer is turned off. See Buffer Size for more details.

`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 the buffer control flags . See Operations Allowed On Buffers for more details.

  Each flag controls access to a set of functions, as described below:

  Constant | Functions
  --- | ---
  `PHP_OUTPUT_HANDLER_CLEANABLE` | ob_clean()
  `PHP_OUTPUT_HANDLER_FLUSHABLE` | ob_flush()
  `PHP_OUTPUT_HANDLER_REMOVABLE` | ob_end_clean(), ob_end_flush(), ob_get_clean(), ob_get_flush()

  > Note: Prior to PHP 8.4.0, the flags parameter could set the output handler status flags as well.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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 unerasable output buffer

`<?php
ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE);
?>`

### See Also

- ob_get_contents() - Return the contents of the output buffer
- ob_end_clean() - Clean (erase) the contents of the active output buffer and turn it off
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_implicit_flush() - Turn implicit flush on/off
- ob_gzhandler() - ob_start callback function to gzip output buffer
- ob_iconv_handler() - Convert character encoding as output buffer handler
- mb_output_handler() - Callback function converts character encoding in output buffer
- ob_tidyhandler() - ob_start callback function to repair the buffer

# output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

output_add_rewrite_var — Add URL rewriter values

### Description

output_add_rewrite_var(string `$name`, string `$value`): bool

This function starts the `'URL-Rewriter'` output buffer handler if it is not active, stores the `name` and `value` parameters, and when the buffer is flushed rewrites the URLs and forms based on the applicable ini settings. Subsequent calls to this function will store all additional name/value pairs until the handler is turned off.

When the output buffer is flushed (by calling ob_flush(), ob_end_flush(), ob_get_flush() or at the end of the script) the `'URL-Rewriter'` handler adds the name/value pairs as query parameters to URLs in attributes of HTML tags and adds hidden fields to forms based on the values of the url_rewriter.tags and url_rewriter.hosts configuration directives.

Each name/value pair added to the `'URL-Rewriter'` handler is added to the URLs and/or forms even if this results in duplicate URL query parameters or elements with the same name attributes.

> Note: Once the `'URL-Rewriter'` handler has been turned off it cannot be started again.

Warning

Prior to PHP 8.4.0, the hosts to be rewritten were set in session.trans_sid_hosts instead of url_rewriter.hosts.

### Parameters

`name`

  The variable name.

`value`

  The variable value.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.0 | As of PHP 7.1.0, a dedicated output buffer is used, url_rewriter.tags is used solely for output functions and url_rewriter.hosts is available. Prior to PHP 7.1.0, rewrite variables set by output_add_rewrite_var() shared an output buffer with transparent session id support (see session.trans_sid_tags).

### Examples

Example #1 output_add_rewrite_var() example

`<?php
ini_set('url_rewriter.tags', 'a=href,form=');
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
    )

### See Also

- output_reset_rewrite_vars() - Reset URL rewriter values
- ob_flush() - Flush (send) the return value of the active output handler
- ob_list_handlers() - List all output handlers in use
- url_rewriter.tags
- url_rewriter.hosts

# output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

output_reset_rewrite_vars — Reset URL rewriter values

### Description

output_reset_rewrite_vars(): bool

This function removes all rewrite variables previously set by the output_add_rewrite_var() function.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.0 | Before PHP 7.1.0, rewrite vars set by output_add_rewrite_var() use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used and output_reset_rewrite_vars() only removes rewrite vars defined by output_add_rewrite_var().

### Examples

Example #1 output_reset_rewrite_vars() example

`<?php
ini_set('url_rewriter.tags', 'a=href');
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?var=value">link</a>
    <a href="file.php">link</a>

### See Also

- output_add_rewrite_var() - Add URL rewriter values
- ob_flush() - Flush (send) the return value of the active output handler
- ob_list_handlers() - List all output handlers in use
- url_rewriter.tags
- url_rewriter.hosts
- session.trans_sid_tags
- session.trans_sid_hosts

## Table of Contents

- flush — Flush system output buffer
- ob_clean — Clean (erase) the contents of the active output buffer
- ob_end_clean — Clean (erase) the contents of the active output buffer and turn it off
- ob_end_flush — Flush (send) the return value of the active output handler and turn the active output buffer off
- ob_flush — Flush (send) the return value of the active output handler
- ob_get_clean — Get the contents of the active output buffer and turn it off
- ob_get_contents — Return the contents of the output buffer
- ob_get_flush — Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
- ob_get_length — Return the length of the output buffer
- ob_get_level — Return the nesting level of the output buffering mechanism
- ob_get_status — Get status of output buffers
- ob_implicit_flush — Turn implicit flush on/off
- ob_list_handlers — List all output handlers in use
- ob_start — Turn on output buffering
- output_add_rewrite_var — Add URL rewriter values
- output_reset_rewrite_vars — Reset URL rewriter values

- Installing/Configuring
  - Runtime Configuration
- Predefined Constants
- Output Buffering
- Flushing System Buffers
- User-Level Output Buffers
  - What Output Is Buffered?
  - Nesting Output Buffers
  - Buffer Size
  - Operations Allowed On Buffers
  - Output Handlers
  - Working With Output Handlers
  - Flags Passed To Output Handlers
  - Output Handler Return Values
- Examples
  - Basic usage
  - Output rewrite usage
- Output Control Functions
  - flush — Flush system output buffer
  - ob_clean — Clean (erase) the contents of the active output buffer
  - ob_end_clean — Clean (erase) the contents of the active output buffer and turn it off
  - ob_end_flush — Flush (send) the return value of the active output handler and turn the active output buffer off
  - ob_flush — Flush (send) the return value of the active output handler
  - ob_get_clean — Get the contents of the active output buffer and turn it off
  - ob_get_contents — Return the contents of the output buffer
  - ob_get_flush — Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
  - ob_get_length — Return the length of the output buffer
  - ob_get_level — Return the nesting level of the output buffering mechanism
  - ob_get_status — Get status of output buffers
  - ob_implicit_flush — Turn implicit flush on/off
  - ob_list_handlers — List all output handlers in use
  - ob_start — Turn on output buffering
  - output_add_rewrite_var — Add URL rewriter values
  - output_reset_rewrite_vars — Reset URL rewriter values

# PHP Options and Information

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Runtime Configuration

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PHP Options/Info Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
assert.active | "1" | `INI_ALL` | Deprecated as of PHP 8.3.0
assert.bail | "0" | `INI_ALL` | Deprecated as of PHP 8.3.0
assert.warning | "1" | `INI_ALL` | Deprecated as of PHP 8.3.0
assert.callback | NULL | `INI_ALL` | Deprecated as of PHP 8.3.0
assert.quiet_eval | "0" | `INI_ALL` | Removed as of PHP 8.0.0
assert.exception | "1" | `INI_ALL` | Prior to PHP 8.0.0, defaults to `"0"`. Deprecated as of PHP 8.3.0
enable_dl | "1" | `INI_SYSTEM` | This deprecated feature will certainly be removed in the future.
max_execution_time | "30" | `INI_ALL` |
max_input_time | "-1" | `INI_PERDIR` |
max_input_nesting_level | "64" | `INI_PERDIR` |
max_input_vars | 1000 | `INI_PERDIR` |
zend.enable_gc | "1" | `INI_ALL` |
zend.max_allowed_stack_size | "0" | `INI_SYSTEM` | Available as of PHP 8.3.0.
zend.reserved_stack_size | "0" | `INI_SYSTEM` | Available as of PHP 8.3.0.
fiber.stack_size |  | `INI_ALL` | Available as of PHP 8.1.0.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`assert.active` bool

  Enable assert() evaluation. zend.assertions should be used instead to control the behaviour of assert().

  Warning

  This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.

`assert.bail` bool

  Terminate script execution on failed assertions.

  Warning

  This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.

`assert.warning` bool

  Issue a PHP warning for each failed assertion.

  Warning

  This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.

`assert.callback` string

  User function to call on failed assertions.

  Warning

  This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.

`assert.quiet_eval` bool
  Warning

  This feature was REMOVED as of PHP 8.0.0.

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

`assert.exception` bool

  Issue an AssertionError exception for the failed assertion.

  Warning

  This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.

`enable_dl` bool

  This directive allows to turn dynamic loading of PHP extensions with dl() on and off.

  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.

`max_execution_time` int

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

  On non Windows systems, the maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.

  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` int

  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. The default setting is `-1`, which means that max_execution_time is used instead. Set to `0` to allow unlimited time.

`max_input_nesting_level` int

  Sets the max nesting depth of input variables (i.e. $_GET, $_POST.)

`max_input_vars` int

  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.

`zend.enable_gc` bool

  Enables or disables the circular reference collector.

`zend.max_allowed_stack_size` int

  The maximum native stack space that the operating system allows the program to consume. Trying to consume more than the operating system allows typically results in a hard crash with no easily available debugging information. To make debugging easier, the engine throws an Error before it happens (when the program uses more than zend.max_allowed_stack_size-zend.reserved_stack_size bytes of stack).

  Recursion in user-defined code does not consume native stack space. However, internal functions and magic methods do. Very deep recursion involving these functions can cause the program to exhaust all available native stack space.

  Possible values for this parameter are:

  - `0`: Auto-detect the maximum native stack space that the operating system allows the program to consume. This is the default. When detection is not possible, a known system default is used.
  - `-1`: Disables stack size checking in the engine.
  - Positive integer: A fixed size, in bytes. Setting this value too high has the same effect as disabling stack size checking.

  As the stack size of fibers is determined by fiber.stack_size, the value of this parameter is used instead of zend.max_allowed_stack_size when checking stack usage during the execution of a Fiber.

  > Note:

  > This is not related to stack buffer overflows, and is not a security feature.

`zend.reserved_stack_size` int

  The reserved stack size, in bytes. This is subtracted from the max allowed stack size, as a buffer, when checking the stack size.

  Possible values for this parameter are:

  - `0`: Auto-detect a sensible size.
  - Positive integer: A fixed size, in bytes.
`fiber.stack_size` int

  The native stack size, in bytes, allocated for each Fiber.

  The default value is 1MiB on systems with a pointer size lower than 8 bytes, or 2MiB otherwise.

# Predefined Constants

The constants below are always available as part of the PHP core.

Constants | Description
--- | ---
Pre-defined phpcredits() constants
`CREDITS_GROUP` (int) | A list of the core developers
`CREDITS_GENERAL` (int) | General credits: Language design and concept, PHP authors and SAPI module.
`CREDITS_SAPI` (int) | A list of the server API modules for PHP, and their authors.
`CREDITS_MODULES` (int) | A list of the extension modules for PHP, and their authors.
`CREDITS_DOCS` (int) | The credits for the documentation team.
`CREDITS_FULLPAGE` (int) | 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` (int) | The credits for the quality assurance team.
`CREDITS_ALL` (int) | 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.

Constants | Description
--- | ---
phpinfo() constants
`INFO_GENERAL` (int) | The configuration line, php.ini location, build date, Web Server, System and more.
`INFO_CREDITS` (int) | PHP Credits. See also phpcredits().
`INFO_CONFIGURATION` (int) | Current Local and Master values for PHP directives. See also ini_get().
`INFO_MODULES` (int) | Loaded modules and their respective settings.
`INFO_ENVIRONMENT` (int) | Environment Variable information that's also available in $_ENV.
`INFO_VARIABLES` (int) | Shows all predefined variables from `EGPCS` (Environment, GET, POST, Cookie, Server).
`INFO_LICENSE` (int) | PHP License information. See also the » license faq.
`INFO_ALL` (int) | Shows all of the above. This is the default value.

Constants | Description
--- | ---
INI mode constants
`INI_USER` (int) | Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Entry can be set in .user.ini
`INI_PERDIR` (int) | Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini
`INI_SYSTEM` (int) | Entry can be set in php.ini or httpd.conf
`INI_ALL` (int) | Entry can be set anywhere

Assert constants, these values are used to set the assertion options in assert_options().

Constants | Description
--- | ---
assert() constants
`ASSERT_ACTIVE` (int) | Enable assert() evaluation. Warning This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.
`ASSERT_CALLBACK` (int) | Callback to call on failed assertions. Warning This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.
`ASSERT_BAIL` (int) | Terminate execution on failed assertions. Warning This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.
`ASSERT_EXCEPTION` (int) | Throws an AssertionError for each failed assertion Warning This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.
`ASSERT_WARNING` (int) | Issues a PHP warning for each failed assertion Warning This feature has been DEPRECATED as of PHP 8.3.0. Relying on this feature is highly discouraged.
`ASSERT_QUIET_EVAL` (int) | Disable `error_reporting` during assertion expression evaluation. Warning This feature was REMOVED as of PHP 8.0.0.

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.

Constants | Description
--- | ---
Windows specific constants
`PHP_WINDOWS_VERSION_MAJOR` (int) | The major version of Windows, this can be either `4` (NT4/Me/98/95), `5` (XP/2003 R2/2003/2000) or `6` (Vista/2008/7/8/8.1).
`PHP_WINDOWS_VERSION_MINOR` (int) | 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` (int) | The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
`PHP_WINDOWS_VERSION_PLATFORM` (int) | 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` (int) | 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` (int) | The minor version of the service pack installed, this value is `0` if no service pack is installed.
`PHP_WINDOWS_VERSION_SUITEMASK` (int) | 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` (int) | 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` (int) | This is a domain controller
`PHP_WINDOWS_NT_SERVER` (int) | 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` (int) | 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.

Windows suitemask bitfields
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 Options/Info Functions

# assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assert — Checks an assertion

### Description

assert(mixed `$assertion`, Throwable|string|null `$description` = `null`): bool

assert() allows for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production.

Assertions can be used to aid debugging. One use case for them is to act as sanity-checks for preconditions that should always be `true` and that if they aren't upheld this indicates some programming errors. Another use case is to ensure the presence of certain features like extension functions or certain system limits and features.

As assertions can be configured to be eliminated, they should not be used for normal runtime operations like input parameter checks. As a rule of thumb code should behave as expected even if assertion checking is deactivated.

assert() will check that the expectation given in `assertion` holds. If not, and thus the result is `false`, it will take the appropriate action depending on how assert() was configured.

The behaviour of assert() is dictated by the following INI settings:

Assert Configure Options
Name | Default | Description | Changelog
--- | --- | --- | ---
zend.assertions | `1` | `1`: generate and execute code (development mode) `0`: generate code but jump around it at runtime `-1`: do not generate code (production mode) |
assert.active | `true` | If `false`, assert() does not check the expectation and returns `true`, unconditionally. | Deprecated as of PHP 8.3.0.
assert.callback | `null` | A user defined function to call when an assertion fails. Its signature should be: assert_callback( string `$file`, int `$line`, null `$assertion`, string `$description` = ? ): void | Prior to PHP 8.0.0, the signature of the callback should be: assert_callback( string `$file`, int `$line`, string `$assertion`, string `$description` = ? ): void Deprecated as of PHP 8.3.0.
assert.exception | `true` | If `true` will throw an AssertionError if the expectation isn't upheld. | Deprecated as of PHP 8.3.0.
assert.bail | `false` | If `true` will abort execution of the PHP script if the expectation isn't upheld. | Deprecated as of PHP 8.3.0.
assert.warning | `true` | If `true`, will emit an `E_WARNING` if the expectation isn't upheld. This INI setting is ineffective if assert.exception is enabled. | Deprecated as of PHP 8.3.0.

### Parameters

`assertion`

  This is any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.

  Warning

  Prior to PHP 8.0.0, if `assertion` was a string it was interpreted as PHP code and executed via eval(). This string would be passed to the callback as the third argument. This behaviour was DEPRECATED in PHP 7.2.0, and REMOVED in PHP 8.0.0.

`description`

  If `description` is an instance of Throwable, it will be thrown only if the `assertion` is executed and fails.

  > Note:

  > As of PHP 8.0.0, this is done prior to calling the potentially defined assertion callback.

  > Note:

  > As of PHP 8.0.0, the object will be thrown regardless of the configuration of assert.exception.

  > Note:

  > As of PHP 8.0.0, the assert.bail setting has no effect in this case.

  If `description` is a string this message will be used if an exception or a warning is emitted. An optional description that will be included in the failure message if the `assertion` fails.

  If `description` is omitted. A default description equal to the source code for the invocation of assert() is created at compile time.

### Return Values

assert() will always return `true` if at least one of the following is true:

- `zend.assertions=0`
- `zend.assertions=-1`
- `assert.active=0`
- `assert.exception=1`
- `assert.bail=1`
- A custom exception object is passed to `description`.

If none of the conditions are true assert() will return `true` if `assertion` is truthy and `false` otherwise.

### Changelog

Version | Description
--- | ---
8.3.0 | All `assert.` INI settings have been deprecated.
8.0.0 | assert() will no longer evaluate string arguments, instead they will be treated like any other argument. `assert($a == $b)` should be used instead of `assert('$a == $b')`. The `assert.quiet_eval` php.ini directive and the `ASSERT_QUIET_EVAL` constant have also been removed, as they would no longer have any effect.
8.0.0 | If `description` is an instance of Throwable, the object is thrown if the assertion fails, regardless of the value of assert.exception.
8.0.0 | If `description` is an instance of Throwable, no user callback is called even if it set.
8.0.0 | Declaring a function called `assert()` inside a namespace is no longer allowed, and issues `E_COMPILE_ERROR`.
7.3.0 | Declaring a function called `assert()` inside a namespace became deprecated. Such declaration now emits an `E_DEPRECATED`.
7.2.0 | Usage of a string as the `assertion` became deprecated. It now emits an `E_DEPRECATED` notice when both assert.active and zend.assertions are set to `1`.

### Examples

Example #1 assert() example

`<?php
assert(1 > 2);
echo 'Hi!';`

If assertions are enabled (`zend.assertions=1`) the above example will output:

    Fatal error: Uncaught AssertionError: assert(1 > 2) in example.php:2
    Stack trace:
    #0 example.php(2): assert(false, 'assert(1 > 2)')
    #1 {main}
      thrown in example.php on line 2

If assertions are disabled (`zend.assertions=0` or `zend.assertions=-1`) the above example will output:

    Hi!

Example #2 Using a custom message

`<?php
assert(1 > 2, "Expected one to be greater than two");
echo 'Hi!';`

If assertions are enabled the above example will output:

    Fatal error: Uncaught AssertionError: Expected one to be greater than two in example.php:2
    Stack trace:
    #0 example.php(2): assert(false, 'Expected one to...')
    #1 {main}
      thrown in example.php on line 2

If assertions are disabled the above example will output:

    Hi!

Example #3 Using a custom exception class

`<?php
class ArithmeticAssertionError extends AssertionError {}
assert(1 > 2, new ArithmeticAssertionError("Expected one to be greater than two"));
echo 'Hi!';`

If assertions are enabled the above example will output:

    Fatal error: Uncaught ArithmeticAssertionError: Expected one to be greater than two in example.php:4
    Stack trace:
    #0 {main}
      thrown in example.php on line 4

If assertions are disabled the above example will output:

    Hi!

### See Also

- assert_options() - Set/get the various assert flags

# assert_options

(PHP 4, PHP 5, PHP 7, PHP 8)

assert_options — Set/get the various assert flags

Warning

This function has been DEPRECATED as of PHP 8.3.0. Relying on this function is highly discouraged.

### Description

assert_options(int `$option`, mixed `$value` = ?): mixed

Set the various assert() control options or just query their current settings.

> Note: The use of assert_options() is discouraged in favor of setting and getting the php.ini directives zend.assertions and assert.exception with ini_set() and ini_get(), respectively.

### Parameters

`option`

  Assert Options
  Option | INI Setting | Default value | Description
  --- | --- | --- | ---
  ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation
  ASSERT_EXCEPTION | assert.exception | 1 | throws an AssertionError for each failed assertions
  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. Removed as of PHP 8.0.0.
  ASSERT_CALLBACK | assert.callback | (`null`) | Callback to call on failed assertions

`value`

  An optional new value for the option.

  The callback function set via `ASSERT_CALLBACK` or assert.callback should have the following signature:

  assert_callback(
  string `$file`,
  int `$line`,
  ?string `$assertion`,
  string `$description` = ?
  ): void
  `file`
    The file where assert() has been called.
  `line`
    The line where assert() has been called.
  `assertion`
    Prior to PHP 8.0.0, the assertion which has been passed to assert(), but only when the assertion is given as a string. (If the assertion is a boolean condition, this parameter will be an empty string.) As of PHP 8.0.0, this parameter is always `null`.
  `description`
    The description that has been passed to assert().

Passing an empty string as `value` resets the assert callback.

### Return Values

Returns the original setting of any option.

### Errors/Exceptions

If `option` is not a valid option a ValueError is thrown.

### Changelog

Version | Description
--- | ---
8.3.0 | assert_option() is now deprecated.
8.0.0 | If `option` is not a valid option, a ValueError is now thrown. Previously `false` was returned.

### Examples

Example #1 assert_options() example

`<?php
// This is our function to handle
// assert failures
function assert_failure($file, $line, $assertion, $message)
{
echo "The assertion $assertion in $file on line $line has failed: $message";
}
// 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';
?>`

### See Also

- assert() - Checks an assertion

# cli_get_process_title

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

cli_get_process_title — Returns the current process title

### Description

cli_get_process_title(): ?string

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.

### Parameters

This function has no parameters.

### Return Values

Return a string with the current process title or `null` on error.

### Errors/Exceptions

An `E_WARNING` will be generated if the operating system is unsupported.

### Examples

Example #1 cli_get_process_title() example

`<?php
echo "Process title: " . cli_get_process_title() . "\n";
?>`

### See Also

- cli_set_process_title() - Sets the process title

# cli_set_process_title

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

cli_set_process_title — Sets the process title

### Description

cli_set_process_title(string `$title`): bool

Sets the process title visible in tools such as top and ps. This function is available only in CLI mode.

### Parameters

`title`

  The new title.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

An `E_WARNING` will be generated if the operating system is unsupported.

### Examples

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

### See Also

- cli_get_process_title() - Returns the current process title

# dl

(PHP 4, PHP 5, PHP 7, PHP 8)

dl — Loads a PHP extension at runtime

### Description

dl(string `$extension_filename`): bool

Loads the PHP extension given by the parameter `extension_filename`.

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

Warning

This function is only available for the CLI and embed SAPIs, and the CGI SAPI when run from the command line.

### Parameters

`extension_filename`

  This 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:\php5\ by default.

  Unix - If not explicitly set in the php.ini, the default extension directory depends on

  - whether PHP has been built with `--enable-debug` or not
  - whether PHP has been built with ZTS (Zend Thread Safety) support or not
  - the current internal `ZEND_MODULE_API_NO` (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. `20010901`)
  Taking into account the above, the directory then defaults to `<install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO`, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

### Return Values

Returns `true` on success or `false` on failure. If the functionality of loading modules is not available or has been disabled (by setting enable_dl off 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.

### Examples

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 using PHP_SHLIB_SUFFIX constant
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>`

### Notes

> Note:

> dl() is case sensitive on Unix platforms.

### See Also

- Extension Loading Directives
- extension_loaded() - Find out whether an extension is loaded

# extension_loaded

(PHP 4, PHP 5, PHP 7, PHP 8)

extension_loaded — Find out whether an extension is loaded

### Description

extension_loaded(string `$extension`): bool

Finds out whether the extension is loaded.

### Parameters

`extension`

  The extension name. This parameter is case-insensitive.

  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]

### Return Values

Returns `true` if the extension identified by `extension` is loaded, `false` otherwise.

### Examples

Example #1 extension_loaded() example

`<?php
if (!extension_loaded('gd')) {
if (!dl('gd.so')) {
exit;
}
}
?>`

### See Also

- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- get_extension_funcs() - Returns an array with the names of the functions of a module
- phpinfo() - Outputs information about PHP's configuration
- dl() - Loads a PHP extension at runtime
- function_exists() - Return true if the given function has been defined

# gc_collect_cycles

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_collect_cycles — Forces collection of any existing garbage cycles

### Description

gc_collect_cycles(): int

Forces collection of any existing garbage cycles.

### Parameters

This function has no parameters.

### Return Values

Returns number of collected cycles.

### See Also

- Garbage Collection

# gc_disable

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_disable — Deactivates the circular reference collector

### Description

gc_disable(): void

Deactivates the circular reference collector, setting zend.enable_gc to `0`.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Garbage Collection

# gc_enable

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_enable — Activates the circular reference collector

### Description

gc_enable(): void

Activates the circular reference collector, setting zend.enable_gc to `1`.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Garbage Collection

# gc_enabled

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_enabled — Returns status of the circular reference collector

### Description

gc_enabled(): bool

Returns status of the circular reference collector.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the garbage collector is enabled, `false` otherwise.

### Examples

Example #1 A gc_enabled() example

`<?php
if(gc_enabled()) gc_collect_cycles();
?>`

### See Also

- Garbage Collection

# gc_mem_caches

(PHP 7, PHP 8)

gc_mem_caches — Reclaims memory used by the Zend Engine memory manager

### Description

gc_mem_caches(): int

Reclaims memory used by the Zend Engine memory manager.

### Parameters

This function has no parameters.

### Return Values

Returns the number of bytes freed.

### See Also

- Garbage Collection

# gc_status

(PHP 7 >= 7.3.0, PHP 8)

gc_status — Gets information about the garbage collector

### Description

gc_status(): array

Gets information about the current state of the garbage collector.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the following elements:

- `"runs"`
- `"collected"`
- `"threshold"`
- `"roots"`
- `"running"`
- `"protected"`
- `"full"`
- `"buffer_size"`
- `"application_time"`
- `"collector_time"`
- `"destructor_time"`
- `"free_time"`

### Changelog

Version | Description
--- | ---
8.3.0 | gc_status() now returns the following additional fields: `"running"`, `"protected"`, `"full"`, `"buffer_size"`, `"application_time"`, `"collector_time"`, `"destructor_time"`, and `"free_time"`.

### Examples

Example #1 gc_status() Usage

`<?php
// create object tree that needs gc collection
$a = new stdClass();
$a->b = [];
for ($i = 0; $i < 100000; $i++) {
$b = new stdClass();
$b->a = $a;
$a->b[] = $b;
}
unset($a);
unset($b);
gc_collect_cycles();
var_dump(gc_status());`

The above example will output something similar to:

    array(4) {
      ["runs"]=>
      int(5)
      ["collected"]=>
      int(100002)
      ["threshold"]=>
      int(50001)
      ["roots"]=>
      int(0)
    }

Output of the above example in PHP 8.3 is similar to:

    array(12) {
      ["running"]=>
      bool(false)
      ["protected"]=>
      bool(false)
      ["full"]=>
      bool(false)
      ["runs"]=>
      int(5)
      ["collected"]=>
      int(100002)
      ["threshold"]=>
      int(50001)
      ["buffer_size"]=>
      int(131072)
      ["roots"]=>
      int(0)
      ["application_time"]=>
      float(0.031182458)
      ["collector_time"]=>
      float(0.020106291)
      ["destructor_time"]=>
      float(0)
      ["free_time"]=>
      float(0.003707167)
    }

### See Also

- Garbage Collection

# get_cfg_var

(PHP 4, PHP 5, PHP 7, PHP 8)

get_cfg_var — Gets the value of a PHP configuration option

### Description

get_cfg_var(string `$option`): string|array|false

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.

### Parameters

`option`

  The configuration option name.

### Return Values

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

### See Also

- ini_get() - Gets the value of a configuration option
- ini_get_all() - Gets all configuration options

# get_current_user

(PHP 4, PHP 5, PHP 7, PHP 8)

get_current_user — Gets the name of the owner of the current PHP script

### Description

get_current_user(): string

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

### Parameters

This function has no parameters.

### Return Values

Returns the username as a string.

### Examples

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

### See Also

- getmyuid() - Gets PHP script owner's UID
- getmygid() - Get PHP script owner's GID
- getmypid() - Gets PHP's process ID
- getmyinode() - Gets the inode of the current script
- getlastmod() - Gets time of last page modification

# get_defined_constants

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

get_defined_constants — Returns an associative array with the names of all the constants and their values

### Description

get_defined_constants(bool `$categorize` = `false`): array

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.

### Parameters

`categorize`

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

      )

### Return Values

Returns an array of constant name => constant value array, optionally groupped by extension name registering the constant.

### Examples

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
    )

### See Also

- defined() - Checks whether a constant with the given name exists
- constant() - Returns the value of a constant
- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- get_defined_functions() - Returns an array of all defined functions
- get_defined_vars() - Returns an array of all defined variables

# get_extension_funcs

(PHP 4, PHP 5, PHP 7, PHP 8)

get_extension_funcs — Returns an array with the names of the functions of a module

### Description

get_extension_funcs(string `$extension`): array|false

This function returns the names of all the functions defined in the module indicated by `extension`.

### Parameters

`extension`

  The module name.

  > Note:

  > This parameter must be in lowercase.

### Return Values

Returns an array with all the functions, or `false` if `extension` is not a valid extension.

### Examples

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
    )

### See Also

- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- ReflectionExtension::getFunctions() - Gets extension functions

# get_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

get_include_path — Gets the current include_path configuration option

### Description

get_include_path(): string|false

Gets the current include_path configuration option value.

### Parameters

This function has no parameters.

### Return Values

Returns the path, as a string, or `false` on failure.

### Examples

Example #1 get_include_path() example

`<?php
echo get_include_path();
// Or using ini_get()
echo ini_get('include_path');
?>`

### See Also

- ini_get() - Gets the value of a configuration option
- restore_include_path() - Restores the value of the include_path configuration option
- set_include_path() - Sets the include_path configuration option
- include - include

# get_included_files

(PHP 4, PHP 5, PHP 7, PHP 8)

get_included_files — Returns an array with the names of included or required files

### Description

get_included_files(): array

Gets the names of all files that have been included using include, include_once, require or require_once.

### Parameters

This function has no parameters.

### Return Values

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.

### Examples

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:

    /path/to/abc.php
    /path/to/test1.php
    /path/to/test2.php
    /path/to/test3.php
    /path/to/test4.php

### See Also

- include - include
- include_once - include_once
- require - require
- require_once - require_once
- get_required_files() - Alias of get_included_files

# get_loaded_extensions

(PHP 4, PHP 5, PHP 7, PHP 8)

get_loaded_extensions — Returns an array with the names of all modules compiled and loaded

### Description

get_loaded_extensions(bool `$zend_extensions` = `false`): array

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

### Parameters

`zend_extensions`

  Only return Zend extensions, if not then regular extensions, like mysqli are listed. Defaults to `false` (return regular extensions).

### Return Values

Returns an indexed array of all the modules names.

### Examples

Example #1 get_loaded_extensions() Example

`<?php
print_r(get_loaded_extensions());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Core
        [1] => date
        [2] => libxml
        [3] => pcre
        [4] => sqlite3
        [5] => zlib
        [6] => ctype
        [7] => dom
        [8] => fileinfo
        [9] => filter
        [10] => hash
        [11] => json
        [12] => mbstring
        [13] => SPL
        [14] => PDO
        [15] => session
        [16] => posix
        [17] => Reflection
        [18] => standard
        [19] => SimpleXML
        [20] => pdo_sqlite
        [21] => Phar
        [22] => tokenizer
        [23] => xml
        [24] => xmlreader
        [25] => xmlwriter
        [26] => gmp
        [27] => iconv
        [28] => intl
        [29] => bcmath
        [30] => sodium
        [31] => Zend OPcache
    )

### See Also

- get_extension_funcs() - Returns an array with the names of the functions of a module
- extension_loaded() - Find out whether an extension is loaded
- dl() - Loads a PHP extension at runtime
- phpinfo() - Outputs information about PHP's configuration

# get_magic_quotes_gpc

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

get_magic_quotes_gpc(): false

Always returns `false`.

### Parameters

This function has no parameters.

### Return Values

Always returns `false`.

### Changelog

Version | Description
--- | ---
8.0.0 | Removed this function.
7.4.0 | Deprecated this function.

### See Also

- addslashes() - Quote string with slashes
- stripslashes() - Un-quotes a quoted string
- get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime
- ini_get() - Gets the value of a configuration option

# get_magic_quotes_runtime

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

get_magic_quotes_runtime(): false

Always returns `false`.

### Parameters

This function has no parameters.

### Return Values

Always returns `false`.

### Changelog

Version | Description
--- | ---
8.0.0 | Removed this function.
7.4.0 | Deprecated this function.

### See Also

- get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

# get_required_files

(PHP 4, PHP 5, PHP 7, PHP 8)

get_required_files — Alias of get_included_files()

### Description

This function is an alias of: get_included_files().

# get_resources

(PHP 7, PHP 8)

get_resources — Returns active resources

### Description

get_resources(?string `$type` = `null`): array

Returns an array of all currently active resources, optionally filtered by resource type.

> Note: This function is meant for debugging and testing purposes. It is not supposed to be used in production environments, especially not to access or even manipulate resources which are normally not accessible (e.g. the underlying stream resource of SplFileObject instances).

### Parameters

`type`

  If defined, this will cause get_resources() to only return resources of the given type. A list of resource types is available.

  If the string `Unknown` is provided as the type, then only resources that are of an unknown type will be returned.

  If omitted, all resources will be returned.

### Return Values

Returns an array of currently active resources, indexed by resource number.

### Changelog

Version | Description
--- | ---
8.0.0 | `type` is nullable now.

### Examples

Example #1 Unfiltered get_resources()

`<?php
$fp = tmpfile();
var_dump(get_resources());
?>`

The above example will output something similar to:

    array(1) {
      [1]=>
      resource(1) of type (stream)
    }

Example #2 Filtered get_resources()

`<?php
$fp = tmpfile();
var_dump(get_resources('stream'));
var_dump(get_resources('curl'));
?>`

The above example will output something similar to:

    array(1) {
      [1]=>
      resource(1) of type (stream)
    }
    array(0) {
    }

### See Also

- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- get_defined_constants() - Returns an associative array with the names of all the constants and their values
- get_defined_functions() - Returns an array of all defined functions
- get_defined_vars() - Returns an array of all defined variables

# getenv

(PHP 4, PHP 5, PHP 7, PHP 8)

getenv — Gets the value of a single or all environment variables

### Description

getenv(?string `$name` = `null`, bool `$local_only` = `false`): string|array|false

Gets the value of a single or all environment variables.

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

### Parameters

`name`

  The variable name as a string or `null`.

`local_only`

  When set to `true`, only local environment variables are returned, set by the operating system or putenv. It only has an effect when `name` is a string.

### Return Values

Returns the value of the environment variable `name`, or `false` if the environment variable `name` does not exist. If `name` is `null`, all environment variables are returned as an associative array.

### Changelog

Version | Description
--- | ---
8.0.0 | The `name` is now nullable.
7.1.0 | The `name` can now be omitted to retrieve an associative array of all environment variables.
7.0.9 | The `local_only` parameter has been added.

### Examples

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'];
// Safely get the value of an environment variable, ignoring whether
// or not it was set by a SAPI or has been changed with putenv
$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')
?>`

### Notes

Warning

If PHP is running in a SAPI such as Fast CGI, this function will always return the value of an environment variable set by the SAPI, even if putenv() has been used to set a local environment variable of the same name. Use the `local_only` parameter to return the value of locally-set environment variables.

### See Also

- putenv() - Sets the value of an environment variable
- apache_getenv() - Get an Apache subprocess_env variable
- Superglobals

# getlastmod

(PHP 4, PHP 5, PHP 7, PHP 8)

getlastmod — Gets time of last page modification

### Description

getlastmod(): int|false

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

### Parameters

This function has no parameters.

### Return Values

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.

### Examples

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());
?>`

### See Also

- date() - Format a Unix timestamp
- getmyuid() - Gets PHP script owner's UID
- getmygid() - Get PHP script owner's GID
- get_current_user() - Gets the name of the owner of the current PHP script
- getmyinode() - Gets the inode of the current script
- getmypid() - Gets PHP's process ID
- filemtime() - Gets file modification time

# getmygid

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

getmygid — Get PHP script owner's GID

### Description

getmygid(): int|false

Gets the group ID of the current script.

### Parameters

This function has no parameters.

### Return Values

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

### See Also

- getmyuid() - Gets PHP script owner's UID
- getmypid() - Gets PHP's process ID
- get_current_user() - Gets the name of the owner of the current PHP script
- getmyinode() - Gets the inode of the current script
- getlastmod() - Gets time of last page modification

# getmyinode

(PHP 4, PHP 5, PHP 7, PHP 8)

getmyinode — Gets the inode of the current script

### Description

getmyinode(): int|false

Gets the inode of the current script.

### Parameters

This function has no parameters.

### Return Values

Returns the current script's inode as an integer, or `false` on error.

### See Also

- getmygid() - Get PHP script owner's GID
- getmyuid() - Gets PHP script owner's UID
- getmypid() - Gets PHP's process ID
- get_current_user() - Gets the name of the owner of the current PHP script
- getlastmod() - Gets time of last page modification

# getmypid

(PHP 4, PHP 5, PHP 7, PHP 8)

getmypid — Gets PHP's process ID

### Description

getmypid(): int|false

Gets the current PHP process ID.

### Parameters

This function has no parameters.

### Return Values

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

### Notes

Warning

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

### See Also

- getmygid() - Get PHP script owner's GID
- getmyuid() - Gets PHP script owner's UID
- get_current_user() - Gets the name of the owner of the current PHP script
- getmyinode() - Gets the inode of the current script
- getlastmod() - Gets time of last page modification

# getmyuid

(PHP 4, PHP 5, PHP 7, PHP 8)

getmyuid — Gets PHP script owner's UID

### Description

getmyuid(): int|false

Gets the user ID of the current script.

### Parameters

This function has no parameters.

### Return Values

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

### See Also

- getmygid() - Get PHP script owner's GID
- getmypid() - Gets PHP's process ID
- get_current_user() - Gets the name of the owner of the current PHP script
- getmyinode() - Gets the inode of the current script
- getlastmod() - Gets time of last page modification

# getopt

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

getopt — Gets options from the command line argument list

### Description

getopt(string `$short_options`, array `$long_options` = [], int `&$rest_index` = `null`): array|false

Parses options passed to the script.

### Parameters

`short_options`
  Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (`-`). For example, an option string `"x"` recognizes an option `-x`. Only a-z, A-Z and 0-9 are allowed.
`long_options`
  An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (`--`). For example, an longopts element `"opt"` recognizes an option `--opt`.
`rest_index`
  If the `rest_index` parameter is present, then the index where argument parsing stopped will be written to this variable.

The `short_options` parameter may contain the following elements:

- Individual characters (do not accept values)
- Characters followed by a colon (parameter requires value)
- Characters followed by two colons (optional value)

Option values are the first argument after the string. If a value is required, it does not matter whether the value has leading white space or not. See note.

> Note: Optional values do not accept `" "` (space) as a separator.

The `long_options` array values may contain:

- String (parameter does not accept any value)
- String followed by a colon (parameter requires value)
- String followed by two colons (optional value)

> Note:

> The format for the `short_options` and `long_options` is almost the same, the only difference is that `long_options` takes an array of options (where each element is the option) whereas `short_options` takes a string (where each character is the option).

### Return Values

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.

### Changelog

Version | Description
--- | ---
7.1.0 | Added the `rest_index` parameter.

### Examples

Example #1 getopt() example: The basics

`<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>`

    shell> php example.php -fvalue -h

The above example will output:

    array(2) {
      ["f"]=>
      string(5) "value"
      ["h"]=>
      bool(false)
    }

Example #2 getopt() example: Introducing long options

`<?php
// Script example.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);
?>`

    shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option

The above example 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: Passing multiple options as one

`<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>`

    shell> php example.php -aaac

The above example will output:

    array(2) {
      ["a"]=>
      array(3) {
        [0]=>
        bool(false)
        [1]=>
        bool(false)
        [2]=>
        bool(false)
      }
      ["c"]=>
      bool(false)
    }

Example #4 getopt() example: Using `rest_index`

`<?php
// Script example.php
$rest_index = null;
$opts = getopt('a:b:', [], $rest_index);
$pos_args = array_slice($argv, $rest_index);
var_dump($pos_args);`

    shell> php example.php -a 1 -b 2 -- test

The above example will output:

    array(1) {
      [0]=>
      string(4) "test"
    }

### See Also

- $argv

# getrusage

(PHP 4, PHP 5, PHP 7, PHP 8)

getrusage — Gets the current resource usages

### Description

getrusage(int `$mode` = 0): array|false

This is an interface to getrusage(2). It gets data returned from the system call.

### Parameters

`mode`

  If `mode` is 1, getrusage will be called with `RUSAGE_CHILDREN`.

### Return Values

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names. Returns `false` on failure.

### Examples

Example #1 getrusage() example

`<?php
$dat = getrusage();
echo $dat["ru_oublock"]; // number of block output operations
echo $dat["ru_inblock"]; // number of block input operations
echo $dat["ru_msgsnd"]; // number of IPC messages sent
echo $dat["ru_msgrcv"]; // number of IPC messages received
echo $dat["ru_maxrss"]; // maximum resident set size
echo $dat["ru_ixrss"]; // integral shared memory size
echo $dat["ru_idrss"]; // integral unshared data size
echo $dat["ru_minflt"]; // number of page reclaims (soft page faults)
echo $dat["ru_majflt"]; // number of page faults (hard page faults)
echo $dat["ru_nsignals"]; // number of signals received
echo $dat["ru_nvcsw"]; // number of voluntary context switches
echo $dat["ru_nivcsw"]; // number of involuntary context switches
echo $dat["ru_nswap"]; // number of swaps
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
echo $dat["ru_utime.tv_sec"]; // user time used (seconds)
echo $dat["ru_stime.tv_usec"]; // system time used (microseconds)
echo $dat["ru_stime.tv_sec"]; // system time used (seconds)
?>`

### Notes

> Note:

> On Windows getrusage() will only return the following members:

> - `"ru_stime.tv_sec"`
> - `"ru_stime.tv_usec"`
> - `"ru_utime.tv_sec"`
> - `"ru_utime.tv_usec"`
> - `"ru_majflt"` (only if `mode` is `RUSAGE_SELF`)
> - `"ru_maxrss"` (only if `mode` is `RUSAGE_SELF`)

> If getrusage() is called with `mode` set to `1` (`RUSAGE_CHILDREN`), then resource usage for threads are collected (meaning that internally the function is called with `RUSAGE_THREAD`).

> Note:

> on BeOS 2000, only the following members are returned:

> - `"ru_stime.tv_sec"`
> - `"ru_stime.tv_usec"`
> - `"ru_utime.tv_sec"`
> - `"ru_utime.tv_usec"`

### See Also

- Your system's man page on getrusage(2)

# ini_alter

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_alter — Alias of ini_set()

### Description

This function is an alias of: ini_set().

# ini_get

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_get — Gets the value of a configuration option

### Description

ini_get(string `$option`): string|false

Returns the value of the configuration option on success.

### Parameters

`option`

  The configuration option name.

### Return Values

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.

### Examples

Example #1 A few ini_get() examples

`<?php
/*
Our php.ini contains the following settings:
display_errors = On
opcache.enable_cli = Off
post_max_size = 8M
*/
echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'opcache.enable_cli = ' . (int) ini_get('opcache.enable_cli') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size + 1 = ' . (rtrim(ini_get('post_max_size'), 'KMG') + 1) . "\n";
echo 'post_max_size in bytes = ' . ini_parse_quantity(ini_get('post_max_size'));
?>`

The above example will output something similar to:

    display_errors = 1
    opcache.enable_cli = 0
    post_max_size = 8M
    post_max_size+1 = 9
    post_max_size in bytes = 8388608

### Notes

> 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 int equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The ini_parse_quantity() function can be used to convert the shorthand notation into bytes.

> Note:

> ini_get() can't read "array" ini options such as `pdo.dsn.*`, and returns `false` in this case.

### See Also

- get_cfg_var() - Gets the value of a PHP configuration option
- ini_get_all() - Gets all configuration options
- ini_parse_quantity() - Get interpreted size from ini shorthand syntax
- ini_restore() - Restores the value of a configuration option
- ini_set() - Sets the value of a configuration option

# ini_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ini_get_all — Gets all configuration options

### Description

ini_get_all(?string `$extension` = `null`, bool `$details` = `true`): array|false

Returns all the registered configuration options.

### Parameters

`extension`

  An optional extension name. If not `null` or the string `core`, the function returns only options specific for that extension.

`details`

  Retrieve details settings or only the current value for each setting. Default is `true` (retrieve details).

### Return Values

Returns an associative array with directive name as the array key. Returns `false` and raises an `E_WARNING` level error if the `extension` doesn't exist.

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.

### Examples

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

### Notes

> Note:

> ini_get_all() ignores "array" ini options such as `pdo.dsn.*`.

### See Also

- How to change configuration settings
- ini_get() - Gets the value of a configuration option
- ini_restore() - Restores the value of a configuration option
- ini_set() - Sets the value of a configuration option
- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- phpinfo() - Outputs information about PHP's configuration
- ReflectionExtension::getINIEntries() - Gets extension ini entries

# ini_parse_quantity

(PHP 8 >= 8.2.0)

ini_parse_quantity — Get interpreted size from ini shorthand syntax

### Description

ini_parse_quantity(string `$shorthand`): int

Returns the interpreted size in bytes on success from an ini shorthand.

### Parameters

`shorthand`

  Ini shorthand to parse, must be a number followed by an optional multiplier. The following multipliers are supported: `k`/`K` (`1024`), `m`/`M` (`1048576`), `g`/`G` (`1073741824`). The number can be a decimal, hex (prefixed with `0x` or `0X`), octal (prefixed with `0o`, `0O` or `0`) or binary (prefixed with `0b` or `0B`)

### Return Values

Returns the interpreted size in bytes as an int.

### Errors/Exceptions

If the value cannot be parsed, or an invalid multiplier is used, an `E_WARNING` is raised.

### Examples

Example #1 A few ini_parse_quantity() examples

`<?php
var_dump(ini_parse_quantity('1024'));
var_dump(ini_parse_quantity('1024M'));
var_dump(ini_parse_quantity('512K'));
var_dump(ini_parse_quantity('0xFFk'));
var_dump(ini_parse_quantity('0b1010k'));
var_dump(ini_parse_quantity('0o1024'));
var_dump(ini_parse_quantity('01024'));
var_dump(ini_parse_quantity('Foobar'));
var_dump(ini_parse_quantity('10F'));
?>`

The above example will output:

    int(1024)
    int(1073741824)
    int(524288)
    int(261120)
    int(10240)
    int(532)
    int(532)

    Warning: Invalid quantity "Foobar": no valid leading digits, interpreting as "0" for backwards compatibility
    int(0)

    Warning: Invalid quantity "10F": unknown multiplier "F", interpreting as "10" for backwards compatibility
    int(10)

### See Also

- ini_get() - Gets the value of a configuration option

# ini_restore

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_restore — Restores the value of a configuration option

### Description

ini_restore(string `$option`): void

Restores a given configuration option to its original value.

### Parameters

`option`

  The configuration option name.

### Return Values

No value is returned.

### Examples

Example #1 ini_restore() example

`<?php
$setting = 'html_errors';
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 'html_errors': 1
    New value for 'html_errors': 0
    Original value for 'html_errors': 1

### See Also

- ini_get() - Gets the value of a configuration option
- ini_get_all() - Gets all configuration options
- ini_set() - Sets the value of a configuration option

# ini_set

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_set — Sets the value of a configuration option

### Description

ini_set(string `$option`, string|int|float|bool|null `$value`): string|false

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.

### Parameters

`option`

  Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

`value`

  The new value for the option.

### Return Values

Returns the old value on success, `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | `value` now accepts any scalar type (including `null`). Previously, only string values were accepted.

### Examples

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');
?>`

### See Also

- get_cfg_var() - Gets the value of a PHP configuration option
- ini_get() - Gets the value of a configuration option
- ini_get_all() - Gets all configuration options
- ini_restore() - Restores the value of a configuration option
- How to change configuration settings

# memory_get_peak_usage

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

memory_get_peak_usage — Returns the peak of memory allocated by PHP

### Description

memory_get_peak_usage(bool `$real_usage` = `false`): int

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

### Parameters

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

### Return Values

Returns the memory peak in bytes.

### See Also

- memory_get_usage() - Returns the amount of memory allocated to PHP
- memory_reset_peak_usage() - Reset the peak memory usage
- memory_limit

# memory_get_usage

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

memory_get_usage — Returns the amount of memory allocated to PHP

### Description

memory_get_usage(bool `$real_usage` = `false`): int

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

### Parameters

`real_usage`

  Set this to `true` to get total memory allocated from system, including unused pages. If not set or `false` only the used memory is reported.

> Note:

> PHP does not track memory that is not allocated by `emalloc()`

### Return Values

Returns the memory amount in bytes.

### Examples

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
?>`

### See Also

- memory_get_peak_usage() - Returns the peak of memory allocated by PHP
- memory_limit

# memory_reset_peak_usage

(PHP 8 >= 8.2.0)

memory_reset_peak_usage — Reset the peak memory usage

### Description

memory_reset_peak_usage(): void

Resets the peak memory usage returned by the memory_get_peak_usage() function.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Examples

Example #1 memory_reset_peak_usage() example

`<?php
var_dump(memory_get_peak_usage());
$a = str_repeat("Hello", 424242);
var_dump(memory_get_peak_usage());
unset($a);
memory_reset_peak_usage();
$a = str_repeat("Hello", 2424);
var_dump(memory_get_peak_usage());
?>`

The above example will output something similar to:

    int(422440)
    int(2508672)
    int(399208)

### See Also

- memory_get_peak_usage() - Returns the peak of memory allocated by PHP

# php_ini_loaded_file

(PHP 5 >= 5.2.4, PHP 7, PHP 8)

php_ini_loaded_file — Retrieve a path to the loaded php.ini file

### Description

php_ini_loaded_file(): string|false

Check if a php.ini file is loaded, and retrieve its path.

### Parameters

This function has no parameters.

### Return Values

The loaded php.ini path, or `false` if one is not loaded.

### Examples

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

### See Also

- php_ini_scanned_files() - Return a list of .ini files parsed from the additional ini dir
- phpinfo() - Outputs information about PHP's configuration
- The configuration file

# php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir

### Description

php_ini_scanned_files(): string|false

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. The directories searched are set by a compile time option and, optionally, by an environment variable at run time: more information can be found in the installation guide.

The returned configuration files include the full path.

### Parameters

This function has no parameters.

### Return Values

Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the configure directive --with-config-file-scan-dir wasn't set and the PHP_INI_SCAN_DIR environment variable isn'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().

### Examples

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

### See Also

- ini_set() - Sets the value of a configuration option
- phpinfo() - Outputs information about PHP's configuration
- php_ini_loaded_file() - Retrieve a path to the loaded php.ini file

# php_sapi_name

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

php_sapi_name — Returns the type of interface between web server and PHP

### Description

php_sapi_name(): string|false

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.

### Parameters

This function has no parameters.

### Return Values

Returns the interface type, as a lowercase string, or `false` on failure.

Although not exhaustive, the possible return values include `apache`, `apache2handler`, `cgi` (until PHP 5.3), `cgi-fcgi`, `cli`, `cli-server`, `embed`, `fpm-fcgi`, `litespeed`, `phpdbg`.

### Examples

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

### Notes

> Note: An alternative approach

> The PHP constant `PHP_SAPI` has the same value as php_sapi_name().

Tip

# A potential gotcha

The defined SAPI may not be obvious, because for example instead of `apache` it may be defined as `apache2handler`.

### See Also

- PHP_SAPI

# php_uname

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

php_uname — Returns information about the operating system PHP is running on

### Description

php_uname(string `$mode` = "a"): string

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.

### Parameters

`mode`

  `mode` is a single character that defines what information is returned:

  - `'a'`: This is the default. Returns the same information as the individual modes `'s'`, `'n'`, `'r'`, `'v'`, `'m'` separated by spaces.

  - `'s'`: Operating system name. eg. `FreeBSD`.
  - `'n'`: Host name. eg. `localhost.example.com`.
  - `'r'`: Release name. eg. `5.1.2-RELEASE`.
  - `'v'`: Version information. Varies a lot between operating systems.
  - `'m'`: Machine type. eg. `i386`.

### Return Values

Returns the description, as a string.

### Changelog

Version | Description
--- | ---
8.4.0 | Throws a ValueError when an invalid `mode` is specified.

### Examples

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; // ;
?>`

### See Also

- phpversion() - Gets the current PHP version
- php_sapi_name() - Returns the type of interface between web server and PHP
- phpinfo() - Outputs information about PHP's configuration

# phpcredits

(PHP 4, PHP 5, PHP 7, PHP 8)

phpcredits — Prints out the credits for PHP

### Description

phpcredits(int `$flags` = `CREDITS_ALL`): true

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.

### Parameters

`flags`

  To generate a custom credits page, you may want to use the `flags` parameter.

  Pre-defined phpcredits() flags
  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

### Return Values

Always returns `true`.

### Examples

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

### Notes

> Note:

> phpcredits() outputs plain text instead of HTML when using the CLI mode.

### See Also

- phpversion() - Gets the current PHP version
- phpinfo() - Outputs information about PHP's configuration

# phpinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

phpinfo — Outputs information about PHP's configuration

### Description

phpinfo(int `$flags` = `INFO_ALL`): true

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.

### Parameters

`flags`

  The output may be customized by passing one or more of the following constants bitwise values summed together in the optional `flags` parameter. One can also combine the respective constants or bitwise values together with the bitwise or operator.

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

### Return Values

Always returns `true`.

### Examples

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

### Notes

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

### See Also

- phpversion() - Gets the current PHP version
- phpcredits() - Prints out the credits for PHP
- ini_get() - Gets the value of a configuration option
- ini_set() - Sets the value of a configuration option
- get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
- Predefined Variables

# phpversion

(PHP 4, PHP 5, PHP 7, PHP 8)

phpversion — Gets the current PHP version

### Description

phpversion(?string `$extension` = `null`): string|false

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

### Parameters

`extension`

  An optional extension name.

### Return Values

Returns the current PHP version as a string. If a string argument is provided for `extension` parameter, phpversion() returns the version of that extension, or `false` if there is no version information associated or the extension isn't enabled.

### Changelog

Version | Description
--- | ---
8.0.0 | `extension` is nullable now.

### Examples

Example #1 phpversion() example

`<?php
// Prints e.g. 'Current PHP version: 8.3.12'
echo 'Current PHP version: ' . phpversion();
// Prints e.g. '1.22.3' or nothing if the extension isn't enabled
echo phpversion('zip');
?>`

Example #2 `PHP_VERSION_ID` example and usage

`<?php
/**
* 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, ...
}
?>`

### Notes

> Note:

> This information is also available in the predefined constant `PHP_VERSION`. More versioning information is available using the `PHP_*_VERSION` constants.

> Note:

> Some extensions may define their own version number. However, most bundled extension will use the PHP version as their version number.

### See Also

- PHP_VERSION constants
- version_compare() - Compares two "PHP-standardized" version number strings
- phpinfo() - Outputs information about PHP's configuration
- phpcredits() - Prints out the credits for PHP
- zend_version() - Gets the version of the current Zend engine

# putenv

(PHP 4, PHP 5, PHP 7, PHP 8)

putenv — Sets the value of an environment variable

### Description

putenv(string `$assignment`): bool

Adds `assignment` 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.

### Parameters

`assignment`

  The setting, like `"FOO=BAR"`

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting an environment variable

`<?php
putenv("UNIQID=$uniqid");
?>`

### See Also

- getenv() - Gets the value of a single or all environment variables
- apache_setenv() - Set an Apache subprocess_env variable

# restore_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

restore_include_path — Restores the value of the include_path configuration option

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

restore_include_path(): void

Restores the include_path configuration option back to its original master value as set in php.ini

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | Removed this function.
7.4.0 | Deprecated this function.

### Examples

Example #1 restore_include_path() example

`<?php
echo get_include_path(); // .:/usr/local/lib/php
set_include_path('/inc');
echo get_include_path(); // /inc
restore_include_path();
// Or using ini_restore()
ini_restore('include_path');
echo get_include_path(); // .:/usr/local/lib/php
?>`

### See Also

- ini_restore() - Restores the value of a configuration option
- get_include_path() - Gets the current include_path configuration option
- set_include_path() - Sets the include_path configuration option
- include - include

# set_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

set_include_path — Sets the include_path configuration option

### Description

set_include_path(string `$include_path`): string|false

Sets the include_path configuration option for the duration of the script.

### Parameters

`include_path`

  The new value for the include_path

### Return Values

Returns the old include_path on success or `false` on failure.

### Examples

Example #1 set_include_path() example

`<?php
set_include_path('/usr/lib/pear');
// Or using ini_set()
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);
?>`

### See Also

- ini_set() - Sets the value of a configuration option
- get_include_path() - Gets the current include_path configuration option
- restore_include_path() - Restores the value of the include_path configuration option
- include - include

# set_time_limit

(PHP 4, PHP 5, PHP 7, PHP 8)

set_time_limit — Limits the maximum execution time

### Description

set_time_limit(int `$seconds`): bool

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.

### Parameters

`seconds`

  The maximum execution time, in seconds. If set to zero, no time limit is imposed.

### Return Values

Returns `true` on success, or `false` on failure.

### Notes

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

### See Also

- max_execution_time
- max_input_time

# sys_get_temp_dir

(PHP 5 >= 5.2.1, PHP 7, PHP 8)

sys_get_temp_dir — Returns directory path used for temporary files

### Description

sys_get_temp_dir(): string

Returns the path of the directory PHP stores temporary files in by default.

### Parameters

This function has no parameters.

### Return Values

Returns the path of the temporary directory.

### Examples

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

### See Also

- tmpfile() - Creates a temporary file
- tempnam() - Create file with unique file name

# version_compare

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

version_compare — Compares two "PHP-standardized" version number strings

### Description

version_compare(string `$version1`, string `$version2`, ?string `$operator` = `null`): int|bool

version_compare() compares two "PHP-standardized" version number strings.

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

### Parameters

`version1`

  First version number.

`version2`

  Second version number.

`operator`

  An optional operator. The possible operators are: `<`, `lt`, `<=`, `le`, `>`, `gt`, `>=`, `ge`, `==`, `=`, `eq`, `!=`, `<>`, `ne` respectively.

  This parameter is case-sensitive, values should be lowercase.

### Return Values

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.

### Examples

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, '7.0.0') >= 0) {
echo 'I am at least PHP version 7.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 at least PHP version 5.0.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am still PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>`

### Notes

> Note:

> The `PHP_VERSION` constant 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().

### See Also

- phpversion() - Gets the current PHP version
- php_uname() - Returns information about the operating system PHP is running on
- function_exists() - Return true if the given function has been defined

# zend_thread_id

(PHP 5, PHP 7, PHP 8)

zend_thread_id — Returns a unique identifier for the current thread

### Description

zend_thread_id(): int

This function returns a unique identifier for the current thread.

### Parameters

This function has no parameters.

### Return Values

Returns the thread id as an integer.

### Examples

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

### Notes

> Note:

> This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (`--enable-debug`).

# zend_version

(PHP 4, PHP 5, PHP 7, PHP 8)

zend_version — Gets the version of the current Zend engine

### Description

zend_version(): string

Returns a string containing the version of the currently running Zend Engine.

### Parameters

This function has no parameters.

### Return Values

Returns the Zend Engine version number, as a string.

### Examples

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

### See Also

- phpinfo() - Outputs information about PHP's configuration
- phpcredits() - Prints out the credits for PHP
- phpversion() - Gets the current PHP version

## Table of Contents

- assert — Checks an assertion
- assert_options — Set/get the various assert flags
- cli_get_process_title — Returns the current process title
- cli_set_process_title — Sets the process title
- dl — Loads a PHP extension at runtime
- extension_loaded — Find out whether an extension is loaded
- gc_collect_cycles — Forces collection of any existing garbage cycles
- gc_disable — Deactivates the circular reference collector
- gc_enable — Activates the circular reference collector
- gc_enabled — Returns status of the circular reference collector
- gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
- gc_status — Gets information about the garbage collector
- get_cfg_var — Gets the value of a PHP configuration option
- get_current_user — Gets the name of the owner of the current PHP script
- get_defined_constants — Returns an associative array with the names of all the constants and their values
- get_extension_funcs — Returns an array with the names of the functions of a module
- get_include_path — Gets the current include_path configuration option
- get_included_files — Returns an array with the names of included or required files
- get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
- get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
- get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
- get_required_files — Alias of get_included_files
- get_resources — Returns active resources
- getenv — Gets the value of a single or all environment variables
- getlastmod — Gets time of last page modification
- getmygid — Get PHP script owner's GID
- getmyinode — Gets the inode of the current script
- getmypid — Gets PHP's process ID
- getmyuid — Gets PHP script owner's UID
- getopt — Gets options from the command line argument list
- getrusage — Gets the current resource usages
- ini_alter — Alias of ini_set
- ini_get — Gets the value of a configuration option
- ini_get_all — Gets all configuration options
- ini_parse_quantity — Get interpreted size from ini shorthand syntax
- ini_restore — Restores the value of a configuration option
- ini_set — Sets the value of a configuration option
- memory_get_peak_usage — Returns the peak of memory allocated by PHP
- memory_get_usage — Returns the amount of memory allocated to PHP
- memory_reset_peak_usage — Reset the peak memory usage
- php_ini_loaded_file — Retrieve a path to the loaded php.ini file
- php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
- php_sapi_name — Returns the type of interface between web server and PHP
- php_uname — Returns information about the operating system PHP is running on
- phpcredits — Prints out the credits for PHP
- phpinfo — Outputs information about PHP's configuration
- phpversion — Gets the current PHP version
- putenv — Sets the value of an environment variable
- restore_include_path — Restores the value of the include_path configuration option
- set_include_path — Sets the include_path configuration option
- set_time_limit — Limits the maximum execution time
- sys_get_temp_dir — Returns directory path used for temporary files
- version_compare — Compares two "PHP-standardized" version number strings
- zend_thread_id — Returns a unique identifier for the current thread
- zend_version — Gets the version of the current Zend engine

- Installing/Configuring
  - Runtime Configuration
- Predefined Constants
- PHP Options/Info Functions
  - assert — Checks an assertion
  - assert_options — Set/get the various assert flags
  - cli_get_process_title — Returns the current process title
  - cli_set_process_title — Sets the process title
  - dl — Loads a PHP extension at runtime
  - extension_loaded — Find out whether an extension is loaded
  - gc_collect_cycles — Forces collection of any existing garbage cycles
  - gc_disable — Deactivates the circular reference collector
  - gc_enable — Activates the circular reference collector
  - gc_enabled — Returns status of the circular reference collector
  - gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
  - gc_status — Gets information about the garbage collector
  - get_cfg_var — Gets the value of a PHP configuration option
  - get_current_user — Gets the name of the owner of the current PHP script
  - get_defined_constants — Returns an associative array with the names of all the constants and their values
  - get_extension_funcs — Returns an array with the names of the functions of a module
  - get_include_path — Gets the current include_path configuration option
  - get_included_files — Returns an array with the names of included or required files
  - get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
  - get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
  - get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
  - get_required_files — Alias of get_included_files
  - get_resources — Returns active resources
  - getenv — Gets the value of a single or all environment variables
  - getlastmod — Gets time of last page modification
  - getmygid — Get PHP script owner's GID
  - getmyinode — Gets the inode of the current script
  - getmypid — Gets PHP's process ID
  - getmyuid — Gets PHP script owner's UID
  - getopt — Gets options from the command line argument list
  - getrusage — Gets the current resource usages
  - ini_alter — Alias of ini_set
  - ini_get — Gets the value of a configuration option
  - ini_get_all — Gets all configuration options
  - ini_parse_quantity — Get interpreted size from ini shorthand syntax
  - ini_restore — Restores the value of a configuration option
  - ini_set — Sets the value of a configuration option
  - memory_get_peak_usage — Returns the peak of memory allocated by PHP
  - memory_get_usage — Returns the amount of memory allocated to PHP
  - memory_reset_peak_usage — Reset the peak memory usage
  - php_ini_loaded_file — Retrieve a path to the loaded php.ini file
  - php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
  - php_sapi_name — Returns the type of interface between web server and PHP
  - php_uname — Returns information about the operating system PHP is running on
  - phpcredits — Prints out the credits for PHP
  - phpinfo — Outputs information about PHP's configuration
  - phpversion — Gets the current PHP version
  - putenv — Sets the value of an environment variable
  - restore_include_path — Restores the value of the include_path configuration option
  - set_include_path — Sets the include_path configuration option
  - set_time_limit — Limits the maximum execution time
  - sys_get_temp_dir — Returns directory path used for temporary files
  - version_compare — Compares two "PHP-standardized" version number strings
  - zend_thread_id — Returns a unique identifier for the current thread
  - zend_version — Gets the version of the current Zend engine

# Interactive PHP Debugger

# Introduction

Implemented as a SAPI module, phpdbg can exert complete control over the environment without impacting the functionality or performance of your code.

phpdbg aims to be a lightweight, powerful, easy to use debugging platform for PHP. It offers the following features:

- Step-Through Debugging
- Flexible Breakpoints (Class Method, Function, File:Line, Address, Opcode)
- Easy Access to PHP with built-in eval()
- Userland API
- SAPI Agnostic - Easily Integrated
- PHP Configuration File Support
- JIT Super Globals - Set Your Own !!
- Optional readline Support - Comfortable Terminal Operation
- Easy Operation - See Help :)

Command line options
Option | Example Argument | Description
--- | --- | ---
-c | -c/my/php.ini | Set php.ini file to load
-d | -dmemory_limit=4G | Set a php.ini directive
-n |  | Disable default php.ini
-q |  | Suppress welcome banner
-v |  | Enable oplog output
-b |  | Disable color
-i | -imy.init | Set .phpdbginit file
-I |  | Ignore default .phpdbginit
-O | -Omy.oplog | Set oplog output file
-r |  | Run execution context
-rr |  | Run execution context and quit after execution (not respecting breakpoints)
-e |  | Generate extended information for debugger/profiler
-E |  | Enable step through eval, careful!
-s | -s=, -s=foo | Read code to execute from stdin with an optional delimiter
-S | -Scli | Override SAPI name, careful!
-l | -l4000 | Setup remote console ports
-a | -a192.168.0.3 | Setup remote console bind address
-x |  | Enable xml output (instead of normal text output)
-p | -p, -p=func, -p* | Output opcodes and quit
-h |  | Print the help overview
-V |  | Print version number
-- | -- arg1 arg2 | Use to delimit phpdbg arguments and php $argv; append any $argv argument after it

# Installing/Configuring

## Table of Contents

- Runtime Configuration

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

phpdbg Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
phpdbg.eol | 2 | `INI_ALL` | Removed as of PHP 8.1.0
phpdbg.path |  | 6 | Removed as of PHP 8.1.0

Here's a short explanation of the configuration directives.

`phpdbg.eol` mixed

  The kind of line ending to use for output. For setting the value, one of the string aliases must be used.

  int Value | string Alias
  --- | ---
  `0` | `CRLF`, `crlf`, `DOS`, `dos`
  `1` | `LF`, `lf`, `UNIX`, `unix`
  `2` | `CR`, `cr`, `MAC`, `mac`

`phpdbg.path` string

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

`PHPDBG_VERSION` (string)
`PHPDBG_FILE` (int)
  Removed as of PHP 7.3.0.
`PHPDBG_METHOD` (int)
  Removed as of PHP 7.3.0.
`PHPDBG_LINENO` (int)
  Removed as of PHP 7.3.0.
`PHPDBG_FUNC` (int)
  Removed as of PHP 7.3.0.
`PHPDBG_COLOR_PROMPT` (int)
`PHPDBG_COLOR_NOTICE` (int)
`PHPDBG_COLOR_ERROR` (int)

# phpdbg Functions

# phpdbg_break_file

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_file — Inserts a breakpoint at a line in a file

### Description

phpdbg_break_file(string `$file`, int `$line`): void

Insert a breakpoint at the given `line` in the given `file`.

### Parameters

`file`
  The name of the file.
`line`
  The line number.

### Return Values

No value is returned.

### See Also

- phpdbg_break_function() - Inserts a breakpoint at entry to a function
- phpdbg_break_method() - Inserts a breakpoint at entry to a method
- phpdbg_break_next() - Inserts a breakpoint at the next opcode
- phpdbg_clear() - Clears all breakpoints

# phpdbg_break_function

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_function — Inserts a breakpoint at entry to a function

### Description

phpdbg_break_function(string `$function`): void

Insert a breakpoint at the entry to the given `function`.

### Parameters

`function`
  The name of the function.

### Return Values

No value is returned.

### See Also

- phpdbg_break_file() - Inserts a breakpoint at a line in a file
- phpdbg_break_method() - Inserts a breakpoint at entry to a method
- phpdbg_break_next() - Inserts a breakpoint at the next opcode
- phpdbg_clear() - Clears all breakpoints

# phpdbg_break_method

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_method — Inserts a breakpoint at entry to a method

### Description

phpdbg_break_method(string `$class`, string `$method`): void

Insert a breakpoint at the entry to the given `method` of the given `class`.

### Parameters

`class`
  The name of the class.
`method`
  The name of the method.

### Return Values

No value is returned.

### See Also

- phpdbg_break_file() - Inserts a breakpoint at a line in a file
- phpdbg_break_function() - Inserts a breakpoint at entry to a function
- phpdbg_break_next() - Inserts a breakpoint at the next opcode
- phpdbg_clear() - Clears all breakpoints

# phpdbg_break_next

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_next — Inserts a breakpoint at the next opcode

### Description

phpdbg_break_next(): void

Insert a breakpoint at the next opcode.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- phpdbg_break_file() - Inserts a breakpoint at a line in a file
- phpdbg_break_function() - Inserts a breakpoint at entry to a function
- phpdbg_break_method() - Inserts a breakpoint at entry to a method
- phpdbg_clear() - Clears all breakpoints

# phpdbg_clear

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_clear — Clears all breakpoints

### Description

phpdbg_clear(): void

Clear all breakpoints that have been set, either via one of the phpdbg_break_*() functions or interactively in the console.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- phpdbg_break_file() - Inserts a breakpoint at a line in a file
- phpdbg_break_function() - Inserts a breakpoint at entry to a function
- phpdbg_break_method() - Inserts a breakpoint at entry to a method
- phpdbg_break_next() - Inserts a breakpoint at the next opcode

# phpdbg_color

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_color — Sets the color of certain elements

### Description

phpdbg_color(int `$element`, string `$color`): void

Set the `color` of the given `element`.

### Parameters

`element`
  One of the `PHPDBG_COLOR_*` constants.
`color`
  The name of the color. One of `white`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan` or `black`, optionally with either a trailing `-bold` or `-underline`, for instance, `white-bold` or `green-underline`.

### Return Values

No value is returned.

### See Also

- phpdbg_prompt() - Sets the command prompt

# phpdbg_end_oplog

(PHP 7, PHP 8)

phpdbg_end_oplog — Ends an oplog

### Description

phpdbg_end_oplog(array `$options` = []): ?array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`options`

### Return Values

# phpdbg_exec

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_exec — Attempts to set the execution context

### Description

phpdbg_exec(string `$context`): string|bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`context`

### Return Values

If the execution context was set previously it is returned. If the execution context was not set previously `true` is returned. If the request to set the context fails, `false` is returned, and an `E_WARNING` raised.

# phpdbg_get_executable

(PHP 7, PHP 8)

phpdbg_get_executable — Gets executable

### Description

phpdbg_get_executable(array `$options` = []): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`options`

### Return Values

# phpdbg_prompt

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_prompt — Sets the command prompt

### Description

phpdbg_prompt(string `$string`): void

Set the command prompt to the given `string`.

### Parameters

`string`
  The string to use as command prompt.

### Return Values

No value is returned.

### See Also

- phpdbg_color() - Sets the color of certain elements

# phpdbg_start_oplog

(PHP 7, PHP 8)

phpdbg_start_oplog — Starts an oplog

### Description

phpdbg_start_oplog(): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

## Table of Contents

- phpdbg_break_file — Inserts a breakpoint at a line in a file
- phpdbg_break_function — Inserts a breakpoint at entry to a function
- phpdbg_break_method — Inserts a breakpoint at entry to a method
- phpdbg_break_next — Inserts a breakpoint at the next opcode
- phpdbg_clear — Clears all breakpoints
- phpdbg_color — Sets the color of certain elements
- phpdbg_end_oplog — Ends an oplog
- phpdbg_exec — Attempts to set the execution context
- phpdbg_get_executable — Gets executable
- phpdbg_prompt — Sets the command prompt
- phpdbg_start_oplog — Starts an oplog

- Installing/Configuring
  - Runtime Configuration
- Predefined Constants
- phpdbg Functions
  - phpdbg_break_file — Inserts a breakpoint at a line in a file
  - phpdbg_break_function — Inserts a breakpoint at entry to a function
  - phpdbg_break_method — Inserts a breakpoint at entry to a method
  - phpdbg_break_next — Inserts a breakpoint at the next opcode
  - phpdbg_clear — Clears all breakpoints
  - phpdbg_color — Sets the color of certain elements
  - phpdbg_end_oplog — Ends an oplog
  - phpdbg_exec — Attempts to set the execution context
  - phpdbg_get_executable — Gets executable
  - phpdbg_prompt — Sets the command prompt
  - phpdbg_start_oplog — Starts an oplog

# runkit7

# Introduction

The runkit7 extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables.

This package is a fork of the » runkit package providing PHP 7 support.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

Modifying Constants, Functions, Classes, and Methods as well as Custom Superglobals works with all releases of PHP 7. No special requirements are necessary.

## Installation

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: » https://pecl.php.net/package/runkit7.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Runkit Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
runkit.superglobal | "" | `INI_PERDIR` |
runkit.internal_override | "0" | `INI_SYSTEM` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`runkit.superglobal` string
  Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

  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` bool
  Enables ability to modify/rename/remove internal functions.

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

`RUNKIT7_IMPORT_FUNCTIONS` (int)
  runkit7_import() flag indicating that normal functions should be imported from the specified file.
`RUNKIT7_IMPORT_CLASS_METHODS` (int)
  runkit7_import() flag indicating that class methods should be imported from the specified file.
`RUNKIT7_IMPORT_CLASS_CONSTS` (int)
  runkit7_import() flag indicating that class constants should be imported from the specified file.
`RUNKIT7_IMPORT_CLASS_PROPS` (int)
  runkit7_import() flag indicating that class standard properties should be imported from the specified file.
`RUNKIT7_IMPORT_CLASS_STATIC_PROPS` (int)
  runkit7_import() flag indicating that class static properties should be imported from the specified file. Available since Runkit 1.0.1.
`RUNKIT7_IMPORT_CLASSES` (int)
  runkit7_import() flag representing a bitwise OR of the `RUNKIT7_IMPORT_CLASS_*` constants.
`RUNKIT7_IMPORT_OVERRIDE` (int)
  runkit7_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
`RUNKIT7_ACC_RETURN_REFERENCE` (int)
  Include this flag to make the function or method being created or redeclared return a reference.
`RUNKIT7_ACC_PUBLIC` (int)
  Flag for runkit7_method_add() and runkit7_method_redefine() to make the method public.
`RUNKIT7_ACC_PROTECTED` (int)
  Flag for runkit7_method_add() and runkit7_method_redefine() to make the method protected.
`RUNKIT7_ACC_PRIVATE` (int)
  Flag for runkit7_method_add() and runkit7_method_redefine() to make the method private.
`RUNKIT7_ACC_STATIC` (int)
  Flag for runkit7_method_add() and runkit7_method_redefine() to make the method static.
`RUNKIT7_FEATURE_MANIPULATION` (int)
  Equal to 1 if runtime manipulation is enabled, and 0 otherwise.
`RUNKIT7_FEATURE_SUPERGLOBALS` (int)
  Equal to 1 if custom superglobals are enabled, and 0 otherwise.
`RUNKIT7_FEATURE_SANDBOX` (int)
  Always 0, it's impractical to implement the sandbox feature in php 7.

# runkit7 Functions

# runkit7_constant_add

(PECL runkit7 >= Unknown)

runkit7_constant_add — Similar to define(), but allows defining in class definitions as well

### Description

runkit7_constant_add(string `$constant_name`, mixed `$value`, int `$newVisibility` = ?): bool

### Parameters

`constant_name`
  Name of constant to declare. Either a string to indicate a global constant, or `classname::constname` to indicate a class constant.
`value`
  NULL, Bool, Long, Double, String, Array, or Resource value to store in the new constant.
`newVisibility`
  Visibility of the constant, for class constants. Public by default. One of the `RUNKIT7_ACC_*` constants.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- define() - Defines a named constant
- runkit7_constant_redefine() - Redefine an already defined constant
- runkit7_constant_remove() - Remove/Delete an already defined constant

# runkit7_constant_redefine

(PECL runkit7 >= Unknown)

runkit7_constant_redefine — Redefine an already defined constant

### Description

runkit7_constant_redefine(string `$constant_name`, mixed `$value`, int `$new_visibility` = ?): bool

### Parameters

`constant_name`
  Constant to redefine. Either the name of a global constant, or `classname::constname` indicating class constant.
`value`
  Value to assign to the constant.
`new_visibility`
  The new visibility of the constant, for class constants. Unchanged by default. One of the `RUNKIT7_ACC_*` constants.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- runkit7_constant_add() - Similar to define(), but allows defining in class definitions as well
- runkit7_constant_remove() - Remove/Delete an already defined constant

# runkit7_constant_remove

(PECL runkit7 >= Unknown)

runkit7_constant_remove — Remove/Delete an already defined constant

### Description

runkit7_constant_remove(string `$constant_name`): bool

### Parameters

`constant_name`
  Name of the constant to remove. Either the name of a global constant, or `classname::constname` indicating a class constant.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- define() - Defines a named constant
- runkit7_constant_add() - Similar to define(), but allows defining in class definitions as well
- runkit7_constant_redefine() - Redefine an already defined constant

# runkit7_function_add

(PECL runkit7 >= Unknown)

runkit7_function_add — Add a new function, similar to create_function()

### Description

runkit7_function_add(
string `$function_name`,
string `$argument_list`,
string `$code`,
bool `$return_by_reference` = `null`,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool
runkit7_function_add(
string `$function_name`,
Closure `$closure`,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool

### Parameters

`function_name`
  Name of the function to be created
`argument_list`
  Comma separated argument list
`code`
  Code making up the function
`closure`
  A closure that defines the function.
`return_by_reference`
  Whether the function should return by reference.
`doc_comment`
  The doc comment of the function.
`return_type`
  The return type of the function.
`is_strict`
  Whether the function should behave as if it were declared in a file with `strict_types=1`

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 A runkit7_function_add() example

`<?php
runkit7_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

### See Also

- create_function() - Create a function dynamically by evaluating a string of code
- runkit7_function_redefine() - Replace a function definition with a new implementation
- runkit7_function_copy() - Copy a function to a new function name
- runkit7_function_rename() - Change a function's name
- runkit7_function_remove() - Remove a function definition
- runkit7_method_add() - Dynamically adds a new method to a given class

# runkit7_function_copy

(PECL runkit7 >= Unknown)

runkit7_function_copy — Copy a function to a new function name

### Description

runkit7_function_copy(string `$source_name`, string `$target_name`): bool

### Parameters

`source_name`
  Name of the existing function
`target_name`
  Name of the new function to copy the definition to

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 A runkit7_function_copy() example

`<?php
function original() {
echo "In a function\n";
}
runkit7_function_copy('original','duplicate');
original();
duplicate();
?>`

The above example will output:

    In a function
    In a function

### See Also

- runkit7_function_add() - Add a new function, similar to create_function
- runkit7_function_redefine() - Replace a function definition with a new implementation
- runkit7_function_rename() - Change a function's name
- runkit7_function_remove() - Remove a function definition

# runkit7_function_redefine

(PECL runkit7 >= Unknown)

runkit7_function_redefine — Replace a function definition with a new implementation

### Description

runkit7_function_redefine(
string `$function_name`,
string `$argument_list`,
string `$code`,
bool `$return_by_reference` = `null`,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool
runkit7_function_redefine(
string `$function_name`,
Closure `$closure`,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool

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

### Parameters

`function_name`
  Name of function to redefine
`argument_list`
  New list of arguments to be accepted by function
`code`
  New code implementation
`closure`
  A closure that defines the function.
`return_by_reference`
  Whether the function should return by reference.
`doc_comment`
  The doc comment of the function.
`return_type`
  The return type of the function.
`is_strict`
  Whether the function behaves as if it was declared in a file with `strict_types=1`

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 A runkit7_function_redefine() example

`<?php
function testme() {
echo "Original Testme Implementation\n";
}
testme();
runkit7_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>`

The above example will output:

    Original Testme Implementation
    New Testme Implementation

### See Also

- runkit7_function_add() - Add a new function, similar to create_function
- runkit7_function_copy() - Copy a function to a new function name
- runkit7_function_rename() - Change a function's name
- runkit7_function_remove() - Remove a function definition
- runkit7_method_redefine() - Dynamically changes the code of the given method

# runkit7_function_remove

(PECL runkit7 >= Unknown)

runkit7_function_remove — Remove a function definition

### Description

runkit7_function_remove(string `$function_name`): bool

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

### Parameters

`function_name`
  Name of the function to be deleted

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- runkit7_function_add() - Add a new function, similar to create_function
- runkit7_function_copy() - Copy a function to a new function name
- runkit7_function_redefine() - Replace a function definition with a new implementation
- runkit7_function_rename() - Change a function's name

# runkit7_function_rename

(PECL runkit7 >= Unknown)

runkit7_function_rename — Change a function's name

### Description

runkit7_function_rename(string `$source_name`, string `$target_name`): bool

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

### Parameters

`source_name`
  Current function name
`target_name`
  New function name

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- runkit7_function_add() - Add a new function, similar to create_function
- runkit7_function_copy() - Copy a function to a new function name
- runkit7_function_redefine() - Replace a function definition with a new implementation
- runkit7_function_remove() - Remove a function definition

# runkit7_import

(PECL runkit7 >= Unknown)

runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Warning

This feature has been removed in PECL runkit7 4.0.0.

### Description

runkit7_import(string `$filename`, int `$flags` = ?): bool

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 may be automatically overwritten by their new definitions.

### Parameters

`filename`
  Filename to import function and class definitions from
`flags`
  Bitwise OR of the `RUNKIT7_IMPORT_*` family of constants.

### Return Values

Returns `true` on success or `false` on failure.

# runkit7_method_add

(PECL runkit7 >= Unknown)

runkit7_method_add — Dynamically adds a new method to a given class

### Description

runkit7_method_add(
string `$class_name`,
string `$method_name`,
string `$argument_list`,
string `$code`,
int `$flags` = RUNKIT7_ACC_PUBLIC,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool
runkit7_method_add(
string `$class_name`,
string `$method_name`,
Closure `$closure`,
int `$flags` = RUNKIT7_ACC_PUBLIC,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool

### Parameters

`class_name`
  The class to which this method will be added
`method_name`
  The name of the method to add
`argument_list`
  Comma-delimited list of arguments for the newly-created method
`code`
  The code to be evaluated when `method_name` is called
`closure`
  A closure that defines the method.
`flags`
  The type of method to create, can be `RUNKIT7_ACC_PUBLIC`, `RUNKIT7_ACC_PROTECTED` or `RUNKIT7_ACC_PRIVATE` optionally combined via bitwise OR with `RUNKIT7_ACC_STATIC`
`doc_comment`
  The doc comment of the method.
`return_type`
  The return type of the method.
`is_strict`
  Whether the method behaves as if it were declared in a file with `strict_types=1`

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 runkit7_method_add() example

`<?php
class Example {
function foo() {
echo "foo!\n";
}
}
// create an Example object
$e = new Example();
// Add a new public method
runkit7_method_add(
'Example',
'add',
'$num1, $num2',
'return $num1 + $num2;',
RUNKIT7_ACC_PUBLIC
);
// add 12 + 4
echo $e->add(12, 4);
?>`

The above example will output:

    16

### See Also

- runkit7_method_copy() - Copies a method from class to another
- runkit7_method_redefine() - Dynamically changes the code of the given method
- runkit7_method_remove() - Dynamically removes the given method
- runkit7_method_rename() - Dynamically changes the name of the given method
- runkit7_function_add() - Add a new function, similar to create_function

# runkit7_method_copy

(PECL runkit7 >= Unknown)

runkit7_method_copy — Copies a method from class to another

### Description

runkit7_method_copy(
string `$destination_class`,
string `$destination_method_name`,
string `$source_class`,
string `$source_method_name` = ?
): bool

### Parameters

`destination_class`
  Destination class for copied method
`destination_method_name`
  Destination method name
`source_class`
  Source class of the method to copy
`source_method_name`
  Name of the method to copy from the source class. If this parameter is omitted, the value of `destination_method_name` is assumed.

### Return Values

### Examples

Example #1 runkit7_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()
runkit7_method_copy('Bar', 'baz', 'Foo', 'example');
// output copied function
echo Bar::baz();
?>`

The above example will output:

    foo!

### See Also

- runkit7_method_add() - Dynamically adds a new method to a given class
- runkit7_method_redefine() - Dynamically changes the code of the given method
- runkit7_method_remove() - Dynamically removes the given method
- runkit7_method_rename() - Dynamically changes the name of the given method
- runkit7_function_copy() - Copy a function to a new function name

# runkit7_method_redefine

(PECL runkit7 >= Unknown)

runkit7_method_redefine — Dynamically changes the code of the given method

### Description

runkit7_method_redefine(
string `$class_name`,
string `$method_name`,
string `$argument_list`,
string `$code`,
int `$flags` = RUNKIT7_ACC_PUBLIC,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool
runkit7_method_redefine(
string `$class_name`,
string `$method_name`,
Closure `$closure`,
int `$flags` = RUNKIT7_ACC_PUBLIC,
string `$doc_comment` = `null`,
string `$return_type` = ?,
bool `$is_strict` = ?
): bool

### Parameters

`class_name`
  The class in which to redefine the method
`method_name`
  The name of the method to redefine
`argument_list`
  Comma-delimited list of arguments for the redefined method
`code`
  The new code to be evaluated when `method_name` is called
`closure`
  A closure that defines the method.
`flags`
  The redefined method can be `RUNKIT7_ACC_PUBLIC`, `RUNKIT7_ACC_PROTECTED` or `RUNKIT7_ACC_PRIVATE` optionally combined via bitwise OR with `RUNKIT7_ACC_STATIC`
`doc_comment`
  The doc comment of the method.
`return_type`
  The return type of the method.
`is_strict`
  Whether the method behaves as if it was declared in a file with `strict_types=1`.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 runkit7_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
runkit7_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT7_ACC_PUBLIC
);
// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>`

The above example will output:

    Before: foo!
    After: bar!

### See Also

- runkit7_method_add() - Dynamically adds a new method to a given class
- runkit7_method_copy() - Copies a method from class to another
- runkit7_method_remove() - Dynamically removes the given method
- runkit7_method_rename() - Dynamically changes the name of the given method
- runkit7_function_redefine() - Replace a function definition with a new implementation

# runkit7_method_remove

(PECL runkit7 >= Unknown)

runkit7_method_remove — Dynamically removes the given method

### Description

runkit7_method_remove(string `$class_name`, string `$method_name`): bool

> Note: This function cannot be used to manipulate the currently running (or chained) method.

### Parameters

`class_name`
  The class in which to remove the method
`method_name`
  The name of the method to remove

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 runkit7_method_remove() example

`<?php
class Example {
function foo() {
return "foo!\n";
}
function bar() {
return "bar!\n";
}
}
// Remove the 'foo' method
runkit7_method_remove(
'Example',
'foo'
);
echo implode(' ', get_class_methods('Example'));
?>`

The above example will output:

    bar

### See Also

- runkit7_method_add() - Dynamically adds a new method to a given class
- runkit7_method_copy() - Copies a method from class to another
- runkit7_method_redefine() - Dynamically changes the code of the given method
- runkit7_method_rename() - Dynamically changes the name of the given method
- runkit7_function_remove() - Remove a function definition

# runkit7_method_rename

(PECL runkit7 >= Unknown)

runkit7_method_rename — Dynamically changes the name of the given method

### Description

runkit7_method_rename(string `$class_name`, string `$source_method_name`, string `$target_method_name`): bool

> Note: This function cannot be used to manipulate the currently running (or chained) method.

### Parameters

`class_name`
  The class in which to rename the method
`source_method_name`
  The name of the method to rename
`target_method_name`
  The new name to give to the renamed method

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 runkit7_method_rename() example

`<?php
class Example {
function foo() {
return "foo!\n";
}
}
// Rename the 'foo' method to 'bar'
runkit7_method_rename(
'Example',
'foo',
'bar'
);
// output renamed function
echo (new Example)->bar();
?>`

The above example will output:

    foo!

### See Also

- runkit7_method_add() - Dynamically adds a new method to a given class
- runkit7_method_copy() - Copies a method from class to another
- runkit7_method_redefine() - Dynamically changes the code of the given method
- runkit7_method_remove() - Dynamically removes the given method
- runkit7_function_rename() - Change a function's name

# runkit7_object_id

(PECL runkit7 >= Unknown)

runkit7_object_id — Return the integer object handle for given object

### Description

runkit7_object_id(object `$obj`): int

This function is equivalent to spl_object_id().

This function returns a unique identifier for the object. The object id is unique for the lifetime of the object. Once the object is destroyed, its id may be reused for other objects. This behavior is similar to spl_object_hash().

### Parameters

`obj`
  Any object.

### Return Values

An integer identifier that is unique for each currently existing object and is always the same for each object.

### Notes

> Note: When an object is destroyed, its id may be reused for other objects.

### See Also

- spl_object_id() - Return the integer object handle for given object

# runkit7_superglobals

(PECL runkit7 >= Unknown)

runkit7_superglobals — Return numerically indexed array of registered superglobals

### Description

runkit7_superglobals(): array

### Parameters

This function has no parameters.

### Return Values

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

### See Also

- Variable Scope

# runkit7_zval_inspect

(PECL runkit7 >= Unknown)

runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

### Description

runkit7_zval_inspect(string `$value`): array

### Parameters

`value`
  The value to return the representation of

### Return Values

The array returned by this function contains the following elements:

- `address`
- `refcount` (optional)
- `is_ref` (optional)
- `type`

### Examples

Example #1 runkit7_zval_inspect() example

`<?php
$var = new DateTime();
var_dump(runkit7_zval_inspect($var));
$var = 1;
var_dump(runkit7_zval_inspect($var));
?>`

The above example will output:

    array(4) {
      ["address"]=>
      string(14) "0x7f45ab21b1e0"
      ["refcount"]=>
      int(2)
      ["is_ref"]=>
      bool(false)
      ["type"]=>
      int(8)
    }

    array(2) {
      ["address"]=>
      string(14) "0x7f45ab21b1e0"
      ["type"]=>
      int(4)
    }

### See Also

- References Explained
- » References Explained (by Derick Rethans)

## Table of Contents

- runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
- runkit7_constant_redefine — Redefine an already defined constant
- runkit7_constant_remove — Remove/Delete an already defined constant
- runkit7_function_add — Add a new function, similar to create_function
- runkit7_function_copy — Copy a function to a new function name
- runkit7_function_redefine — Replace a function definition with a new implementation
- runkit7_function_remove — Remove a function definition
- runkit7_function_rename — Change a function's name
- runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate
- runkit7_method_add — Dynamically adds a new method to a given class
- runkit7_method_copy — Copies a method from class to another
- runkit7_method_redefine — Dynamically changes the code of the given method
- runkit7_method_remove — Dynamically removes the given method
- runkit7_method_rename — Dynamically changes the name of the given method
- runkit7_object_id — Return the integer object handle for given object
- runkit7_superglobals — Return numerically indexed array of registered superglobals
- runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- runkit7 Functions
  - runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
  - runkit7_constant_redefine — Redefine an already defined constant
  - runkit7_constant_remove — Remove/Delete an already defined constant
  - runkit7_function_add — Add a new function, similar to create_function
  - runkit7_function_copy — Copy a function to a new function name
  - runkit7_function_redefine — Replace a function definition with a new implementation
  - runkit7_function_remove — Remove a function definition
  - runkit7_function_rename — Change a function's name
  - runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate
  - runkit7_method_add — Dynamically adds a new method to a given class
  - runkit7_method_copy — Copies a method from class to another
  - runkit7_method_redefine — Dynamically changes the code of the given method
  - runkit7_method_remove — Dynamically removes the given method
  - runkit7_method_rename — Dynamically changes the name of the given method
  - runkit7_object_id — Return the integer object handle for given object
  - runkit7_superglobals — Return numerically indexed array of registered superglobals
  - runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

# User Operations for Zend

# Introduction

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:

- Overloading some opcodes including ZEND_EXIT and ZEND_NEW
- Backup and restore functions and methods
- Renaming functions and methods
- Copying of functions and methods
- Deletion of functions and methods
- Redefinition of global and class constants
- Deletion of global and class constants
- Runtime composition and modification of classes

> Note:

> All of the activities supported are compatible with opcache

Caution

PECL uopz 6.1.1 is not compatible with Xdebug >= 2.9.4. Later uopz versions are not compatible with Xdebug < 2.9.4.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

As of uopz 5.0 PHP 7.0 is required. As of uopz 5.1, PHP 7.1+ is required.

## Installation

uopz releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » https://pecl.php.net/package/uopz.

Windows users can download prebuilt release binaries from the » PECL website.

As of uopz 5.0.0 the extension must be loaded as extension. Before this version it must be loaded as zend_extension.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

uopz Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
uopz.disable | "0" | `INI_SYSTEM` | Available as of uopz 5.0.2
uopz.exit | "0" | `INI_SYSTEM` | Available as of uopz 6.0.1
uopz.overloads | "1" | `INI_SYSTEM` | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`uopz.disable` bool

  If enabled, uopz should stop having any effect on the engine.

`uopz.exit` bool

  Whether to allow the execution of exit opcodes or not. This setting can be overridden during runtime by calling uopz_allow_exit().

`uopz.overloads` bool

  Enables the ability to use uopz_overload().

> Note: When running with OPcache enabled, it may be necessary to disable all OPcache optimizations (`opcache.optimization_level=0`).

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

The following opcodes are defined as constants by uopz before 5.0.0:

`ZEND_EXIT` (int)
  Invoked by exit() and die(), receives no arguments. Return boolean `true` to exit, `false` to continue
`ZEND_NEW` (int)
  Invoked by object construction, receives the class of object being created as the only argument
`ZEND_THROW` (int)
  Invoked by the throw construct, receives the class of exception being thrown as the only argument
`ZEND_FETCH_CLASS` (int)
  Invoked upon composure, receives the class the name of the class being fetched as the only argument
`ZEND_ADD_TRAIT` (int)
  Invoked upon composure, receives the class the trait is being added to as the first argument, and the name of the trait as the second argument
`ZEND_ADD_INTERFACE` (int)
  Invoked upon composure, receives the class the interface is being added to as the first argument, and the name of the interface as the second argument
`ZEND_INSTANCEOF` (int)
  Invoked by instanceof operator, receives the object being verified as the first argument, and the name of the class which that object should be as the second argument

The following constants control the VM's behaviour after a user handler is invoked, be extremely careful! These constants are removed as of uopz 5.0.0.

`ZEND_USER_OPCODE_CONTINUE` (int)
  Advance 1 opcode and continuue
`ZEND_USER_OPCODE_ENTER` (int)
  Enter into new op_array without recursion
`ZEND_USER_OPCODE_LEAVE` (int)
  Return to calling op_array within the same executor
`ZEND_USER_OPCODE_DISPATCH` (int)
  Dispatch to original opcode handler
`ZEND_USER_OPCODE_DISPATCH_TO` (int)
  Dispatch to a specific handler (OR'd with ZEND opcode constant)
`ZEND_USER_OPCODE_RETURN` (int)
  Exit from executor (return from function)

The following modifiers are registered as constants by uopz

`ZEND_ACC_PUBLIC` (int)
  Mark function as public, the default
`ZEND_ACC_PROTECTED` (int)
  Mark function as protected
`ZEND_ACC_PRIVATE` (int)
  Mark function as private
`ZEND_ACC_STATIC` (int)
  Mark function as static
`ZEND_ACC_FINAL` (int)
  Mark function as final
`ZEND_ACC_ABSTRACT` (int)
  Mark function as abstract
`ZEND_ACC_CLASS` (int)
  Dummy registered for consistency, the default kind of class entry. Removed as of uopz 5.0.0.
`ZEND_ACC_INTERFACE` (int)
  Mark class as interface. Removed as of uopz 5.0.0.
`ZEND_ACC_TRAIT` (int)
  Mark class as trait. Removed as of uopz 5.0.0.
`ZEND_ACC_FETCH` (int)
  Used for getting flags only. Removed as of uopz 5.0.0.

# Uopz Functions

# uopz_add_function

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_add_function — Adds non-existent function or method

### Description

uopz_add_function(string `$function`, Closure `$handler`, int `&$flags` = ZEND_ACC_PUBLIC): bool
uopz_add_function(
string `$class`,
string `$function`,
Closure `$handler`,
int `&$flags` = ZEND_ACC_PUBLIC,
int `&$all` = `true`
): bool

Adds a non-existent function or method.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

`handler`

  The Closure that defines the new function or method.

`flags`

  Flags to set for the new function or method.

`all`

  Whether all classes that descend from `class` will also be affected.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

uopz_add_function() throws a RuntimeException if the function or method to add already exists.

### Examples

Example #1 Basic uopz_add_function() Usage

`<?php
uopz_add_function('foo', function () {echo 'bar';});
foo();
?>`

The above example will output:

    bar

### See Also

- uopz_del_function() - Deletes previously added function or method
- uopz_set_return() - Provide a return value for an existing function

# uopz_allow_exit

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_allow_exit — Allows control over disabled exit opcode

### Description

uopz_allow_exit(bool `$allow`): void

By default uopz disables the exit opcode, so exit() calls are practically ignored. uopz_allow_exit() allows to control this behavior.

### Parameters

`allow`

  Whether to allow the execution of exit opcodes or not.

### Return Values

No value is returned.

### Examples

Example #1 uopz_allow_exit() example

`<?php
exit(1);
echo 1;
uopz_allow_exit(true);
exit(2);
echo 2;
?>`

The above example will output:

    1

### Notes

Caution

OPcache optimizes away dead code after unconditional exit.

### See Also

- uopz_get_exit_status() - Retrieve the last set exit status

# uopz_backup

(PECL uopz 1 >= 1.0.3, PECL uopz 2)

uopz_backup — Backup a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_backup(string `$function`): void
uopz_backup(string `$class`, string `$function`): void

Backup a function at runtime, to be restored on shutdown

### Parameters

`class`

  The name of the class containing the function to backup

`function`

  The name of the function

### Return Values

### Examples

Example #1 uopz_backup() example

`<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
return true;
});
var_dump(fgets());
?>`

The above example will output:

    bool(true)

# uopz_compose

(PECL uopz 1, PECL uopz 2)

uopz_compose — Compose a class

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_compose(
string `$name`,
array `$classes`,
array `$methods` = ?,
array `$properties` = ?,
int `$flags` = ?
): void

Creates a new class of the given name that implements, extends, or uses all of the provided classes

### Parameters

`name`

  A legal class name

`classes`

  An array of class, interface and trait names

`methods`

  An associative array of methods, values are either closures or [modifiers => closure]

`properties`

  An associative array of properties, keys are names, values are modifiers

`flags`

  Entry type, by default ZEND_ACC_CLASS

### Return Values

### Examples

Example #1 uopz_compose() example

`<?php
class myClass {}
trait myTrait {}
interface myInterface {}
uopz_compose(
Composed::class, [
myClass::class,
myTrait::class,
myInterface::class
], [
"__construct" => function() {
/* ... */
}
]);
var_dump(
class_uses(Composed::class),
class_parents(Composed::class),
class_implements(Composed::class));
?>`

The above example will output:

    array(1) {
      ["myTrait"]=>
      string(7) "myTrait"
    }
    array(1) {
      ["myClass"]=>
      string(7) "myClass"
    }
    array(1) {
      ["myInterface"]=>
      string(11) "myInterface"
    }

# uopz_copy

(PECL uopz 1 >= 1.0.4, PECL uopz 2)

uopz_copy — Copy a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_copy(string `$function`): Closure
uopz_copy(string `$class`, string `$function`): Closure

Copy a function by name

### Parameters

`class`

  The name of the class containing the function to copy

`function`

  The name of the function

### Return Values

A Closure for the specified function

### Examples

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:

    string(5) "dummy"

# uopz_del_function

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_del_function — Deletes previously added function or method

### Description

uopz_del_function(string `$function`): bool
uopz_del_function(string `$class`, string `$function`, int `&$all` = `true`): bool

Deletes a previously added function or method.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

`all`

  Whether all classes that descend from `class` will also be affected.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

uopz_del_function() throws a RuntimeException if the function or method to delete has not been added by uopz_add_function().

### Examples

Example #1 Basic uopz_del_function() Usage

`<?php
uopz_add_function('foo', function () {echo 'bar';});
var_dump(function_exists('foo'));
uopz_del_function('foo');
var_dump(function_exists('foo'));
?>`

The above example will output:

    bool(true)
    bool(false)

### See Also

- uopz_add_function() - Adds non-existent function or method
- uopz_unset_return() - Unsets a previously set return value for a function

# uopz_delete

(PECL uopz 1, PECL uopz 2)

uopz_delete — Delete a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_delete(string `$function`): void
uopz_delete(string `$class`, string `$function`): void

Deletes a function or method

### Parameters

`class`

`function`

### Return Values

### Examples

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

# uopz_extend

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7 < 7.1.0)

uopz_extend — Extend a class at runtime

### Description

uopz_extend(string `$class`, string `$parent`): bool

Makes `class` extend `parent`

### Parameters

`class`

  The name of the class to extend

`parent`

  The name of the class to inherit

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

As of PHP 7.4.0, uopz_extends() throws a RuntimeException, if OPcache is enabled, and the class entry of either `class` or `parent` (if it is a trait) is immutable.

### Examples

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:

    array(1) {
      ["B"]=>
      string(1) "B"
    }

# uopz_flags

(PECL uopz 2 >= 2.0.2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_flags — Get or set flags on function or class

### Description

uopz_flags(string `$function`, int `$flags` = PHP_INT_MAX): int
uopz_flags(string `$class`, string `$function`, int `$flags` = PHP_INT_MAX): int

Get or set the flags on a class or function entry at runtime

### Parameters

`class`

  The name of a class

`function`

  The name of the function. If `class` is given and an empty string is passed as `function`, uopz_flags() gets or sets the flags of the class entry.

`flags`

  A valid set of ZEND_ACC_ flags. If omitted, uopz_flags() acts as getter.

### Return Values

If setting, returns old flags, else returns flags

### Errors/Exceptions

As of PHP 7.4.0, if the parameter `flags` is passed, uopz_flags() throws a RuntimeException, if OPcache is enabled, and the class entry of `class` or the function entry of `function` is immutable.

### Changelog

Version | Description
--- | ---
PECL uopz 5.0.0 | The `flags` parameter is now optional. Formerly, `ZEND_ACC_FETCH` had to be passed to use uopz_flags() as getter.

### Examples

Example #1 uopz_flags() example

`<?php
class Test {
public function method() {
return __CLASS__;
}
}
$flags = uopz_flags("Test", "method");
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC));
var_dump(uopz_flags("Test", "method", $flags|ZEND_ACC_STATIC|ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC));
?>`

The above example will output:

    bool(false)
    bool(false)
    int(1234567890)
    bool(true)
    bool(true)

Example #2 "Unfinalize" a Class

`<?php
final class MyClass
{
}
$flags = uopz_flags(MyClass::class, '');
uopz_flags(MyClass::class, '', $flags & ~ZEND_ACC_FINAL);
var_dump((new ReflectionClass(MyClass::class))->isFinal());
?>`

The above example will output:

    bool(false)

# uopz_function

(PECL uopz 1, PECL uopz 2)

uopz_function — Creates a function at runtime

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_function(string `$function`, Closure `$handler`, int `$modifiers` = ?): void
uopz_function(
string `$class`,
string `$function`,
Closure `$handler`,
int `$modifiers` = ?
): void

Creates a function at runtime

### Parameters

`class`

  The name of the class to receive the new function

`function`

  The name of the function

`handler`

  The Closure for the function

`modifiers`

  The modifiers for the function, by default copied or ZEND_ACC_PUBLIC

### Return Values

### Examples

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:

    11

Example #2 uopz_function() class example

`<?php
class My {}
uopz_function(My::class, "strlen", function($arg) {
return strlen($arg);
}, ZEND_ACC_STATIC);
echo My::strlen("Hello World");
?>`

The above example will output:

    11

# uopz_get_exit_status

(PECL uopz 5, PECL uopz , PECL uopz 7)

uopz_get_exit_status — Retrieve the last set exit status

### Description

uopz_get_exit_status(): mixed

Retrieves the last set exit status, i.e. the value passed to exit().

### Parameters

This function has no parameters.

### Return Values

This function returns the last exit status, or `null` if exit() has not been called.

### Examples

Example #1 uopz_get_exit_status() example

`<?php
exit(123);
echo uopz_get_exit_status();?>`

The above example will output:

    123

### Notes

Caution

OPcache optimizes away dead code after unconditional exit.

### See Also

- uopz_allow_exit() - Allows control over disabled exit opcode

# uopz_get_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_hook — Gets previously set hook on function or method

### Description

uopz_get_hook(string `$function`): Closure
uopz_get_hook(string `$class`, string `$function`): Closure

Gets the previously set hook on a function or method.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

### Return Values

Returns the previously set hook on a function or method, or `null` if no hook has been set.

### Examples

Example #1 Basic uopz_get_hook() Usage

`<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
var_dump(uopz_get_hook('foo'));
?>`

The above example will output something similar to:

    object(Closure)#2 (0) {
    }

### See Also

- uopz_set_hook() - Sets hook to execute when entering a function or method
- uopz_unset_hook() - Removes previously set hook on function or method

# uopz_get_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_mock — Get the current mock for a class

### Description

uopz_get_mock(string `$class`): mixed

Returns the current mock for `class`.

### Parameters

`class`

  The name of the mocked class.

### Return Values

Either a string containing the name of the mock, or an object, or `null` if no mock has been set.

### Examples

Example #1 uopz_get_mock() example

`<?php
class A {
public static function who() {
echo "A";
}
}
class mockA {
public static function who() {
echo "mockA";
}
}
uopz_set_mock(A::class, mockA::class);
echo uopz_get_mock(A::class);
?>`

The above example will output:

    mockA

### See Also

- uopz_set_mock() - Use mock instead of class for new objects
- uopz_unset_mock() - Unset previously set mock

# uopz_get_property

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_property — Gets value of class or instance property

### Description

uopz_get_property(string `$class`, string `$property`): mixed
uopz_get_property(object `$instance`, string `$property`): mixed

Gets the value of a static class property, if `class` is given, or the value of an instance property, if `instance` is given.

### Parameters

`class`

  The name of the class.

`instance`

  The object instance.

`property`

  The name of the property.

### Return Values

Returns the value of the class or instance property, or `null` if the property is not defined.

### Examples

Example #1 Basic uopz_get_property() Usage

`<?php
class Foo {
private static $staticBar = 10;
private $bar = 100;
}
$foo = new Foo;
var_dump(uopz_get_property('Foo', 'staticBar'));
var_dump(uopz_get_property($foo, 'bar'));
?>`

The above example will output something similar to:

    int(10)
    int(100)

### See Also

- uopz_set_property() - Sets value of existing class or instance property

# uopz_get_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_return — Gets a previous set return value for a function

### Description

uopz_get_return(string `$function`): mixed
uopz_get_return(string `$class`, string `$function`): mixed

Gets the return value of the `function` previously set by uopz_set_return().

### Parameters

`class`

  The name of the class containing the function

`function`

  The name of the function

### Return Values

The return value or Closure previously set.

### Examples

Example #1 uopz_get_return() example

`<?php
uopz_set_return("strlen", 42);
echo uopz_get_return("strlen");
?>`

The above example will output:

    42

# uopz_get_static

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_static — Gets the static variables from function or method scope

### Description

uopz_get_static(string `$class`, string `$function`): array
uopz_get_static(string `$function`): array

Gets the static variables from function or method scope.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

### Return Values

Returns an associative array of variable names mapped to their current values on success, or `null` if the function or method does not exist.

As of PHP 8.3.0, static initialzers are either computed during compile time, or if that is not possible, only when the function or method is run the first time, in which case the value of the static variable is reported as `null` prior to the first invocation.

### Examples

Example #1 Basic uopz_get_static() Usage

`<?php
function foo() {
static $bar = 'baz';
}
var_dump(uopz_get_static('foo'));
?>`

The above example will output:

    array(1) {
      ["bar"]=>
      string(3) "baz"
    }

### See Also

- ReflectionFunctionAbstract::getStaticVariables() - Gets static variables
- uopz_set_static() - Sets the static variables in function or method scope

# uopz_implement

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7 < 7.1.0)

uopz_implement — Implements an interface at runtime

### Description

uopz_implement(string `$class`, string `$interface`): bool

Makes `class` implement `interface`

### Parameters

`class`

`interface`

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

As of PHP 7.4.0, uopz_implements() throws a RuntimeException, if OPcache is enabled, and the class entry of `class` is immutable.

### Examples

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:

    array(1) {
      ["myInterface"]=>
      string(11) "myInterface"
    }

# uopz_overload

(PECL uopz 1, PECL uopz 2)

uopz_overload — Overload a VM opcode

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_overload(int `$opcode`, Callable `$callable`): void

Overloads the specified `opcode` with the user defined function

### Parameters

`opcode`

  A valid opcode, see constants for details of supported codes

`callable`

### Return Values

### Examples

Example #1 uopz_overload() example

`<?php
uopz_overload(ZEND_EXIT, function(){});
exit();
echo "Hello World";
?>`

The above example will output:

    Hello World

# uopz_redefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_redefine — Redefine a constant

### Description

uopz_redefine(string `$constant`, mixed `$value`): bool
uopz_redefine(string `$class`, string `$constant`, mixed `$value`): bool

Redefines the given `constant` as `value`

### Parameters

`class`

  The name of the class containing the constant

`constant`

  The name of the constant

`value`

  The new value for the constant, must be a valid type for a constant variable

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 uopz_redefine() example

`<?php
define("MY", 100);
uopz_redefine("MY", 1000);
echo MY;
?>`

The above example will output:

    1000

# uopz_rename

(PECL uopz 1, PECL uopz 2)

uopz_rename — Rename a function at runtime

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_rename(string `$function`, string `$rename`): void
uopz_rename(string `$class`, string `$function`, string `$rename`): void

Renames `function` to `rename`

> Note:

> If both functions exist, this effectively swaps their names

### Parameters

`class`

  The name of the class containing the function

`function`

  The name of an existing function

`rename`

  The new name for the function

### Return Values

### Examples

Example #1 uopz_rename() example

`<?php
uopz_rename("strlen", "original_strlen");
echo original_strlen("Hello World");
?>`

The above example will output:

    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:

    11

# uopz_restore

(PECL uopz 1 >= 1.0.3, PECL uopz 2)

uopz_restore — Restore a previously backed up function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

### Description

uopz_restore(string `$function`): void
uopz_restore(string `$class`, string `$function`): void

Restore a previously backed up function

### Parameters

`class`

  The name of the class containing the function to restore

`function`

  The name of the function

### Return Values

### Examples

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

# uopz_set_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_hook — Sets hook to execute when entering a function or method

### Description

uopz_set_hook(string `$function`, Closure `$hook`): bool
uopz_set_hook(string `$class`, string `$function`, Closure `$hook`): bool

Sets a hook to execute when entering a function or method.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

`hook`

  A closure to execute when entering the function or method.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Basic uopz_set_hook() Usage

`<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
foo();
?>`

The above example will output:

    barfoo

### See Also

- uopz_get_hook() - Gets previously set hook on function or method
- uopz_unset_hook() - Removes previously set hook on function or method

# uopz_set_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_mock — Use mock instead of class for new objects

### Description

uopz_set_mock(string `$class`, mixed `$mock`): void

If `mock` is a string containing the name of a class then it will be instantiated instead of `class`. `mock` can also be an object.

> Note:

> Only dynamic access to properties and methods will use the `mock` object. Static access still uses the original `class`. See example below.

### Parameters

`class`

  The name of the class to be mocked.

`mock`

  The mock to use in the form of a string containing the name of the class to use or an object. If a string is passed, it has to be the fully qualified class name. It is recommended to use the `::class` magic constant in this case.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
PECL uopz 6.0.0 | Mocking static members is no longer supported by this function. uopz_redefine() and uopz_set_return(), or Componere can be used instead.

### Examples

Example #1 uopz_set_mock() example

`<?php
class A {
public function who() {
echo "A";
}
}
class mockA {
public function who() {
echo "mockA";
}
}
uopz_set_mock(A::class, mockA::class);
(new A)->who();
?>`

The above example will output:

    mockA

Example #2 uopz_set_mock() example

`<?php
class A {
public function who() {
echo "A";
}
}
uopz_set_mock(A::class, new class {
public function who() {
echo "mockA";
}
});
(new A)->who();
?>`

The above example will output:

    mockA

Example #3 uopz_set_mock() and static members

As of uopz 6.0.0 mocking static members is no longer supported.

`<?php
class A {
const CON = 'A';
public static function who() {
echo "A";
}
}
uopz_set_mock(A::class, new class {
const CON = 'mockA';
public static function who() {
echo "mockA";
}
});
echo A::CON, PHP_EOL;
A::who();
?>`

The above example will output:

    A
    A

Output of the above example in uopz 5:

    mockA
    mockA

### See Also

- uopz_get_mock() - Get the current mock for a class
- uopz_unset_mock() - Unset previously set mock

# uopz_set_property

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_property — Sets value of existing class or instance property

### Description

uopz_set_property(string `$class`, string `$property`, mixed `$value`): void
uopz_set_property(object `$instance`, string `$property`, mixed `$value`): void

Sets the value of an existing static class property, if `class` is given, or the value of an instance property (regardless whether the instance property already exists), if `instance` is given.

### Parameters

`class`

  The name of the class.

`instance`

  The object instance.

`property`

  The name of the property.

`value`

  The value to assign to the property.

### Return Values

No value is returned.

### Examples

Example #1 Basic uopz_set_property() Usage

`<?php
class Foo {
private static $staticBar;
private $bar;
public static function testStaticBar() {
return self::$staticBar;
}
public function testBar() {
return $this->bar;
}
}
$foo = new Foo;
uopz_set_property('Foo', 'staticBar', 10);
uopz_set_property($foo, 'bar', 100);
var_dump(Foo::testStaticBar());
var_dump($foo->testBar());
?>`

The above example will output:

    int(10)

### See Also

- uopz_get_property() - Gets value of class or instance property

# uopz_set_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_return — Provide a return value for an existing function

### Description

uopz_set_return(string `$function`, mixed `$value`, bool `$execute` = `false`): bool
uopz_set_return(
string `$class`,
string `$function`,
mixed `$value`,
bool `$execute` = `false`
): bool

Sets the return value of the `function` to `value`. If `value` is a Closure and `execute` is set, the Closure will be executed in place of the original function. It is possible to call the original function from the Closure.

> Note:

> This function replaces uopz_rename().

### Parameters

`class`

  The name of the class containing the function

`function`

  The name of an existing function

`value`

  The value the function should return. If a Closure is provided and the execute flag is set, the Closure will be executed in place of the original function.

`execute`

  If true, and a Closure was provided as the value, the Closure will be executed in place of the original function.

### Return Values

True if succeeded, false otherwise.

### Examples

Example #1 uopz_set_return() example

`<?php
uopz_set_return("strlen", 42);
echo strlen("Banana");
?>`

The above example will output:

    42

Example #2 uopz_set_return() example

`<?php
uopz_set_return("strlen", function($str) { return strlen($str) * 2; }, true );
echo strlen("Banana");
?>`

The above example will output:

    12

Example #3 uopz_set_return() class example

`<?php
class My {
public static function strlen($arg) {
return strlen($arg);
}
}
uopz_set_return(My::class, "strlen", function($str) { return strlen($str) * 2; }, true );
echo My::strlen("Banana");
?>`

The above example will output:

    12

# uopz_set_static

(PECL uopz 5, PECL uopz , PECL uopz 7)

uopz_set_static — Sets the static variables in function or method scope

### Description

uopz_set_static(string `$function`, array `$static`): void
uopz_set_static(string `$class`, string `$function`, array `$static`): void

Sets the static variables in function or method scope.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

`static`

  The associative array of variable names mapped to their values.

### Return Values

No value is returned.

### Examples

Example #1 Basic uopz_set_static() Usage

`<?php
function foo() {
static $bar = 'baz';
var_dump($bar);
}
uopz_set_static('foo', ['bar' => 'qux']);
foo();
?>`

The above example will output:

    string(3) "qux"

### See Also

- uopz_get_static() - Gets the static variables from function or method scope

# uopz_undefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_undefine — Undefine a constant

### Description

uopz_undefine(string `$constant`): bool
uopz_undefine(string `$class`, string `$constant`): bool

Removes the constant at runtime

### Parameters

`class`

  The name of the class containing `constant`

`constant`

  The name of an existing constant

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 uopz_undefine() example

`<?php
define("MY", true);
uopz_undefine("MY");
var_dump(defined("MY"));
?>`

The above example will output:

    bool(false)

# uopz_unset_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_hook — Removes previously set hook on function or method

### Description

uopz_unset_hook(string `$function`): bool
uopz_unset_hook(string `$class`, string `$function`): bool

Removes the previously set hook on a function or method.

### Parameters

`class`

  The name of the class.

`function`

  The name of the function or method.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Basic uopz_unset_hook() Usage

`<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
foo();
echo PHP_EOL;
uopz_unset_hook('foo');
foo();
?>`

The above example will output:

    barfoo
    foo

### See Also

- uopz_set_hook() - Sets hook to execute when entering a function or method
- uopz_get_hook() - Gets previously set hook on function or method

# uopz_unset_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_mock — Unset previously set mock

### Description

uopz_unset_mock(string `$class`): void

Unsets the previously set mock for `class`.

### Parameters

`class`

  The name of the mocked class.

### Return Values

No value is returned.

### Errors/Exceptions

A RuntimeException is thrown, if no mock was previously set for `class`.

### Examples

Example #1 uopz_unset_mock() example

`<?php
class A {
public static function who() {
echo "A";
}
}
class mockA {
public static function who() {
echo "mockA";
}
}
uopz_set_mock(A::class, mockA::class);
uopz_unset_mock(A::class);
A::who();
?>`

The above example will output:

    A

### See Also

- uopz_set_mock() - Use mock instead of class for new objects
- uopz_get_mock() - Get the current mock for a class

# uopz_unset_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_return — Unsets a previously set return value for a function

### Description

uopz_unset_return(string `$function`): bool
uopz_unset_return(string `$class`, string `$function`): bool

Unsets the return value of the `function` previously set by uopz_set_return().

### Parameters

`class`

  The name of the class containing the function

`function`

  The name of the function

### Return Values

True on success

### Examples

Example #1 uopz_unset_return() example

`<?php
uopz_set_return("strlen", 42);
$len = strlen("Banana");
uopz_unset_return("strlen");
echo $len + strlen("Banana");
?>`

The above example will output:

    48

## Table of Contents

- uopz_add_function — Adds non-existent function or method
- uopz_allow_exit — Allows control over disabled exit opcode
- uopz_backup — Backup a function
- uopz_compose — Compose a class
- uopz_copy — Copy a function
- uopz_del_function — Deletes previously added function or method
- uopz_delete — Delete a function
- uopz_extend — Extend a class at runtime
- uopz_flags — Get or set flags on function or class
- uopz_function — Creates a function at runtime
- uopz_get_exit_status — Retrieve the last set exit status
- uopz_get_hook — Gets previously set hook on function or method
- uopz_get_mock — Get the current mock for a class
- uopz_get_property — Gets value of class or instance property
- uopz_get_return — Gets a previous set return value for a function
- uopz_get_static — Gets the static variables from function or method scope
- uopz_implement — Implements an interface at runtime
- uopz_overload — Overload a VM opcode
- uopz_redefine — Redefine a constant
- uopz_rename — Rename a function at runtime
- uopz_restore — Restore a previously backed up function
- uopz_set_hook — Sets hook to execute when entering a function or method
- uopz_set_mock — Use mock instead of class for new objects
- uopz_set_property — Sets value of existing class or instance property
- uopz_set_return — Provide a return value for an existing function
- uopz_set_static — Sets the static variables in function or method scope
- uopz_undefine — Undefine a constant
- uopz_unset_hook — Removes previously set hook on function or method
- uopz_unset_mock — Unset previously set mock
- uopz_unset_return — Unsets a previously set return value for a function

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Uopz Functions
  - uopz_add_function — Adds non-existent function or method
  - uopz_allow_exit — Allows control over disabled exit opcode
  - uopz_backup — Backup a function
  - uopz_compose — Compose a class
  - uopz_copy — Copy a function
  - uopz_del_function — Deletes previously added function or method
  - uopz_delete — Delete a function
  - uopz_extend — Extend a class at runtime
  - uopz_flags — Get or set flags on function or class
  - uopz_function — Creates a function at runtime
  - uopz_get_exit_status — Retrieve the last set exit status
  - uopz_get_hook — Gets previously set hook on function or method
  - uopz_get_mock — Get the current mock for a class
  - uopz_get_property — Gets value of class or instance property
  - uopz_get_return — Gets a previous set return value for a function
  - uopz_get_static — Gets the static variables from function or method scope
  - uopz_implement — Implements an interface at runtime
  - uopz_overload — Overload a VM opcode
  - uopz_redefine — Redefine a constant
  - uopz_rename — Rename a function at runtime
  - uopz_restore — Restore a previously backed up function
  - uopz_set_hook — Sets hook to execute when entering a function or method
  - uopz_set_mock — Use mock instead of class for new objects
  - uopz_set_property — Sets value of existing class or instance property
  - uopz_set_return — Provide a return value for an existing function
  - uopz_set_static — Sets the static variables in function or method scope
  - uopz_undefine — Undefine a constant
  - uopz_unset_hook — Removes previously set hook on function or method
  - uopz_unset_mock — Unset previously set mock
  - uopz_unset_return — Unsets a previously set return value for a function

# Windows Cache for PHP

# Introduction

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.

  Support for opcode caching was removed in `Wincache 2.0.0`, all users who wish to have an opcache should use the OPcache extension that is included with PHP.

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

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- WinCache Statistics Script
- WinCache Session Handler
- WinCache Functions Reroutes

## Requirements

The extension is currently supported only on the following configurations:

Windows OS:

- Windows XP SP3 with IIS 5.1 and » FastCGI Extension
- Windows Server 2003 with IIS 6.0 and » FastCGI Extension
- Windows Vista SP1 with IIS 7.0 and FastCGI Module
- Windows Server 2008 with IIS 7.0 and FastCGI Module
- Windows 7 with IIS 7.5 and FastCGI Module
- Windows Server 2008 R2 with IIS 7.5 and FastCGI Module

PHP:

- PHP 5.2.X, Non-thread-safe build
- PHP 5.3 X86, Non-thread-safe VC9 build

> Note: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.

## Installation

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: » https://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:

1. Unpack the package into some temporary location.

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

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

4. Add the following line at the end of the php.ini file: `extension = php_wincache.dll`.

5. Save and close the php.ini file.

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

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

## Runtime Configuration

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:

WinCache configuration options
Name | Default | Minimum | Maximum | Changeable | Changelog
--- | --- | --- | --- | --- | ---
wincache.fcenabled | "1" | "0" | "1" | `INI_ALL` | Available as of WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "255" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.fcndetect | "1" | "0" | "1" | `INI_SYSTEM` | Available as of WinCache 1.1.0
wincache.maxfilesize | "256" | "10" | "2048" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | `INI_ALL` | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | `INI_SYSTEM` | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocachesize | "96" | "15" | "255" | `INI_SYSTEM` | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.filecount | "4096" | "1024" | "16384" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | `INI_ALL` | Available as of WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | `INI_SYSTEM` | Available as of WinCache 1.0.0
wincache.ucenabled | 1 | 0 | 1 | `INI_SYSTEM` | Available as of WinCache 1.1.0
wincache.ucachesize | 8 | 5 | 85 | `INI_SYSTEM` | Available as of WinCache 1.1.0
wincache.scachesize | 8 | 5 | 85 | `INI_SYSTEM` | Available as of WinCache 1.1.0
wincache.rerouteini | NULL | NULL | NULL | `INI_SYSTEM` | Available as of WinCache 1.2.0. Removed as of 1.3.7
wincache.reroute_enabled | 1 | 0 | 1 | `INI_SYSTEM`|`INI_PERDIR` | Available as of WinCache 1.3.7
wincache.srwlocks | 1 | 0 | 1 | `INI_SYSTEM` | Available as of WinCache 1.3.6.3. Removed as of 2.0.0.0
wincache.filemapdir | NULL | NULL | NULL | `INI_SYSTEM` | Available as of WinCache 1.3.7.4

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`wincache.fcenabled` bool
  Enables or disables the file cache functionality.
`wincache.fcenabledfilter` string
  Defines a comma-separated list of IIS web site identifiers where file cache should be enabled or disabled. This setting works in conjunction with `wincache.fcenabled`: if `wincache.fcenabled` is set to 1, then the sites listed in the `wincache.fcenabledfilter` will have the file cache turned off; if `wincache.fcenabled` is set to 0, then the sites listed in the `wincache.fcenabledfilter` will have the file cache turned on.
`wincache.fcachesize` int
  Defines the maximum memory size (in megabytes) that is allocated for the file cache. If the total size of all the cached files exceeds the value specified in this setting, then most stale files will be removed from the file cache.
`wincache.fcndetect` bool
  Enables or disables the file change notification detection functionality. If file change notification is supported then it will be used to refresh the opcode and file cache entries as soon as the corresponding files are modified on a file system. If file change notification is not supported, for example when using network file shares, then wincache will poll for file changes at regular time intervals specified by `wincache.chkinterval`.
`wincache.maxfilesize` int
  Defines the maximum allowed size (in kilobytes) for a single file to be cached. If a file size exceeds the specified value, the file will not be cached. This setting applies to the file cache only.
`wincache.ocenabled` bool
  Warning

  This option has been REMOVED as of 2.0.0.0

  Enables or disables the opcode cache functionality
`wincache.ocenabledfilter` string
  Warning

  This option has been REMOVED as of 2.0.0.0

  Defines a comma-separated list of IIS web site identifiers where opcode cache should be enabled or disabled. This setting works in conjunction with `wincache.ocenabled`: if `wincache.ocenabled` is set to 1, then the sites listed in the `wincache.ocenabledfilter` will have the opcode cache turned off; if `wincache.ocenabled` is set to 0, then the sites listed in the `wincache.ocenabledfilter` will have the opcode cache turned on.
`wincache.ocachesize` int
  Warning

  This option has been REMOVED as of 2.0.0.0

  Defines the maximum memory size (in megabytes) that is allocated for the opcode cache. If the cached opcode size exceeds the specified value, then most stale opcode will be removed from the cache. Note that the opcode cache size must be at least 3 times bigger than file cache size. If that is not the case the opcode cache size will be automatically increased.
`wincache.filecount` int
  Defines how many files are expected to be cached by the extension, so that appropriate memory size is allocated at the startup time. If the number of files exceeds the specified value, the WinCache will re-allocate more memory as needed.
`wincache.chkinterval` int
  Defines how often (in seconds) the extension checks for file changes in order to refresh the cache. Setting it to 0 will disable the refreshing of the cache. The file changes will not be reflected in the cache unless the cache entry for that file is removed by scavenger or IIS application pool is recycled or wincache_refresh_if_changed function is called.
`wincache.ttlmax` int
  Defines the maximum time to live (in seconds) for a cached entry without being used. Setting it to 0 will disable the cache scavenger, so the cached entries will never be removed from the cache during the lifetime of the IIS worker process.
`wincache.enablecli` bool
  Defines if caching is enabled when PHP is running in command line (CLI) mode.
`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
  Defines a string that will be used when naming the extension specific objects that are stored in shared memory. This is used to avoid conflicts that may be caused if other applications within an IIS worker process tries to access shared memory. The length of the namesalt string cannot exceed 8 characters.
`wincache.ucenabled` bool
  Enables or disables the user cache functionality.
`wincache.ucachesize` int
  Defines the maximum memory size in megabytes that is allocated for the user cache. If the total size of variables stored in the user cache exceeds the specified value, then the most stale variables will be removed from the cache.
`wincache.scachesize` int
  Defines the maximum memory size in megabytes that is allocated for the session cache. If the total size of data stored in the session cache exceeds the specified value, then the most stale data will be removed from the cache.
`wincache.rerouteini` string
  Warning

  This option has been REMOVED as of 1.3.7. See `wincache.reroute_enabled` for similar functionality as of 1.3.7.

  Specifies an absolute or a relateve path to the reroute.ini file that contains the list of PHP functions whose implementation should be replaced with the WinCache function equivalents. If a relative path is specified then it is assumed to be relative to the location of php-cgi.exe file.
`wincache.reroute_enabled` bool
  Enables or disables the rerouting of certain file I/O functions through the file cache.
`wincache.srwlocks` bool
  Warning

  This option has been REMOVED as of 2.0.0.0

  Enables or disables the use of shared reader/writer locks. Disabling is useful when troubleshooting deadlock conditions in WinCache.
`wincache.filemapdir` string
  Specifies an absolute path to a directory where WinCache will store the temporary files used for shared memory segments. This directory must be on the local machine and not on a networked file system. If the directory is not specified, WinCache will use the Windows System Page File for all shared memory segments.

## WinCache Statistics Script

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.

## WinCache Session Handler

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\

## WinCache Functions Reroutes

NOTE: wincache.rerouteini was removed as of WinCache 1.3.7.0. It has been replaced with automatic function reroutes. See: wincache.reroute_enabled.

The WinCache functions reroutes (available since WinCache 1.2.0, removed since WinCache 1.3.7.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:

- file_exists
- file_get_contents
- readfile
- is_readable
- is_writable
- is_dir
- realpath
- filesize

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

# WinCache Functions

# wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo — Retrieves information about files cached in the file cache

### Description

wincache_fcache_fileinfo(bool `$summaryonly` = `false`): array|false

Retrieves information about file cache content and its usage.

### Parameters

`summaryonly`

  Controls whether the returned array will contain information about individual cache entries along with the file cache summary.

### Return Values

Array of meta data about file cache or `false` on failure

The array returned by this function contains the following elements:

- `total_cache_uptime` - total time in seconds that the file cache has been active
- `total_file_count` - total number of files that are currently in the file cache
- `total_hit_count` - number of times the files have been served from the file cache
- `total_miss_count` - number of times the files have not been found in the file cache

- `file_entries` - an array that contains the information about all the cached files:

  - `file_name` - absolute file name of the cached file
  - `add_time` - time in seconds since the file has been added to the file cache
  - `use_time` - time in seconds since the file has been accessed in the file cache
  - `last_check` - time in seconds since the file has been checked for modifications
  - `hit_count` - number of times the file has been served from the cache
  - `file_size` - size of the cached file in bytes

### Examples

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

### See Also

- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo — Retrieves information about file cache memory usage

### Description

wincache_fcache_meminfo(): array|false

Retrieves information about memory usage by file cache.

### Parameters

This function has no parameters.

### Return Values

Array of meta data about file cache memory usage or `false` on failure

The array returned by this function contains the following elements:

- `memory_total` - amount of memory in bytes allocated for the file cache
- `memory_free` - amount of free memory in bytes available for the file cache
- `num_used_blks` - number of memory blocks used by the file cache
- `num_free_blks` - number of free memory blocks available for the file cache
- `memory_overhead` - amount of memory in bytes used for the file cache internal structures

### Examples

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
    )

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_lock

(PECL wincache >= 1.1.0)

wincache_lock — Acquires an exclusive lock on a given key

### Description

wincache_lock(string `$key`, bool `$isglobal` = `false`): bool

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

Warning

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.

### Parameters

`key`

  Name of the key in the cache to get the lock on.

`isglobal`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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

### See Also

- wincache_unlock() - Releases an exclusive lock on a given key
- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache

# wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache

### Description

wincache_ocache_fileinfo(bool `$summaryonly` = `false`): array|false

Retrieves information about opcode cache content and its usage.

Warning

This function was REMOVED in PHP 7.0.0.

### Parameters

`summaryonly`

  Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary.

### Return Values

Array of meta data about opcode cache or `false` on failure

The array returned by this function contains the following elements:

- `total_cache_uptime` - total time in seconds that the opcode cache has been active
- `total_file_count` - total number of files that are currently in the opcode cache
- `total_hit_count` - number of times the compiled opcode have been served from the cache
- `total_miss_count` - number of times the compiled opcode have not been found in the cache
- `is_local_cache` - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache

- `file_entries` - an array that contains the information about all the cached files:

  - `file_name` - absolute file name of the cached file
  - `add_time` - time in seconds since the file has been added to the opcode cache
  - `use_time` - time in seconds since the file has been accessed in the opcode cache
  - `last_check` - time in seconds since the file has been checked for modifications
  - `hit_count` - number of times the file has been served from the cache
  - `function_count` - number of functions in the cached file
  - `class_count` - number of classes in the cached file

### Examples

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

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo — Retrieves information about opcode cache memory usage

### Description

wincache_ocache_meminfo(): array|false

Retrieves information about memory usage by opcode cache.

### Parameters

This function has no parameters.

### Return Values

Array of meta data about opcode cache memory usage or `false` on failure

The array returned by this function contains the following elements:

- `memory_total` - amount of memory in bytes allocated for the opcode cache
- `memory_free` - amount of free memory in bytes available for the opcode cache
- `num_used_blks` - number of memory blocks used by the opcode cache
- `num_free_blks` - number of free memory blocks available for the opcode cache
- `memory_overhead` - amount of memory in bytes used for the opcode cache internal structures

Warning

This function was REMOVED in PHP 7.0.0.

### Examples

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
    )

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed — Refreshes the cache entries for the cached files

### Description

wincache_refresh_if_changed(array `$files` = NULL): bool

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.

### Parameters

`files`

  An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache

# wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo — Retrieves information about resolve file path cache

### Description

wincache_rplist_fileinfo(bool `$summaryonly` = `false`): array|false

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

### Parameters

`summaryonly`

### Return Values

Array of meta data about the resolve file path cache or `false` on failure

The array returned by this function contains the following elements:

- `total_file_count` - total number of file path mappings stored in the cache

- `rplist_entries` - an array that contains the information about all the cached file paths:

  - `resolve_path` - path to a file
  - `subkey_data` - corresponding absolute path to a file

### Examples

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

### See Also

- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache

### Description

wincache_rplist_meminfo(): array|false

Retrieves information about memory usage by resolve file path cache.

### Parameters

This function has no parameters.

### Return Values

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:

- `memory_total` - amount of memory in bytes allocated for the resolve file path cache
- `memory_free` - amount of free memory in bytes available for the resolve file path cache
- `num_used_blks` - number of memory blocks used by the resolve file path cache
- `num_free_blks` - number of free memory blocks available for the resolve file path cache
- `memory_overhead` - amount of memory in bytes used for the internal structures of resolve file path cache

### Examples

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
    )

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_scache_info

(PECL wincache >= 1.1.0)

wincache_scache_info — Retrieves information about files cached in the session cache

### Description

wincache_scache_info(bool `$summaryonly` = `false`): array|false

Retrieves information about session cache content and its usage.

### Parameters

`summaryonly`

  Controls whether the returned array will contain information about individual cache entries along with the session cache summary.

### Return Values

Array of meta data about session cache or `false` on failure

The array returned by this function contains the following elements:

- `total_cache_uptime` - total time in seconds that the session cache has been active
- `total_item_count` - total number of elements that are currently in the session cache
- `is_local_cache` - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
- `total_hit_count` - number of times the data has been served from the cache
- `total_miss_count` - number of times the data has not been found in the cache

- `scache_entries` - an array that contains the information about all the cached items:

  - `key_name` - name of the key which is used to store the data
  - `value_type` - type of value stored by the key
  - `use_time` - time in seconds since the file has been accessed in the opcode cache
  - `last_check` - time in seconds since the file has been checked for modifications
  - `ttl_seconds` - time remaining for the data to live in the cache, 0 meaning infinite
  - `age_seconds` - time elapsed from the time data has been added in the cache
  - `hitcount` - number of times data has been served from the cache

### Examples

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

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_scache_meminfo

(PECL wincache >= 1.1.0)

wincache_scache_meminfo — Retrieves information about session cache memory usage

### Description

wincache_scache_meminfo(): array|false

Retrieves information about memory usage by session cache.

### Parameters

This function has no parameters.

### Return Values

Array of meta data about session cache memory usage or `false` on failure

The array returned by this function contains the following elements:

- `memory_total` - amount of memory in bytes allocated for the session cache
- `memory_free` - amount of free memory in bytes available for the session cache
- `num_used_blks` - number of memory blocks used by the session cache
- `num_free_blks` - number of free memory blocks available for the session cache
- `memory_overhead` - amount of memory in bytes used for the session cache internal structures

### Examples

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
    )

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache

# wincache_ucache_add

(PECL wincache >= 1.1.0)

wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache

### Description

wincache_ucache_add(string `$key`, mixed `$value`, int `$ttl` = 0): bool
wincache_ucache_add(array `$values`, mixed `$unused` = NULL, int `$ttl` = 0): bool

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.

### Parameters

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

`values`

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

### Return Values

If `key` is string, the function returns `true` on success and `false` on failure.

If `key` is an array, the function returns:

- If all the name => value pairs in the array can be set, function returns an empty array;
- If all the name => value pairs in the array cannot be set, function returns `false`;
- If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

### Examples

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"

### See Also

- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- __sleep()

# wincache_ucache_cas

(PECL wincache >= 1.1.0)

wincache_ucache_cas — Compares the variable with old value and assigns new value to it

### Description

wincache_ucache_cas(string `$key`, int `$old_value`, int `$new_value`): bool

Compares the variable associated with the `key` with `old_value` and if it matches then assigns the `new_value` to it.

### Parameters

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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)

### See Also

- wincache_ucache_inc() - Increments the value associated with the key
- wincache_ucache_dec() - Decrements the value associated with the key

# wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear — Deletes entire content of the user cache

### Description

wincache_ucache_clear(): bool

Clears/deletes all the values stored in the user cache.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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)

### See Also

- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache

# wincache_ucache_dec

(PECL wincache >= 1.1.0)

wincache_ucache_dec — Decrements the value associated with the key

### Description

wincache_ucache_dec(string `$key`, int `$dec_by` = 1, bool `&$success` = ?): mixed

Decrements the value associated with the `key` by 1 or as specified by `dec_by`.

### Parameters

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

### Return Values

Returns the decremented value on success and `false` on failure.

### Examples

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)

### See Also

- wincache_ucache_inc() - Increments the value associated with the key
- wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

# wincache_ucache_delete

(PECL wincache >= 1.1.0)

wincache_ucache_delete — Deletes variables from the user cache

### Description

wincache_ucache_delete(mixed `$key`): bool

Deletes the elements in the user cache pointed by `key`.

### Parameters

`key`

  The `key` that was used to store the variable in the cache. `key` is case sensitive. `key` can be an array of keys.

### Return Values

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.

### Examples

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

### See Also

- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache

# wincache_ucache_exists

(PECL wincache >= 1.1.0)

wincache_ucache_exists — Checks if a variable exists in the user cache

### Description

wincache_ucache_exists(string `$key`): bool

Checks if a variable with the `key` exists in the user cache or not.

### Parameters

`key`

  The `key` that was used to store the variable in the cache. `key` is case sensitive.

### Return Values

Returns `true` if variable with the `key` exitsts, otherwise returns `false`.

### Examples

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)

### See Also

- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache

# wincache_ucache_get

(PECL wincache >= 1.1.0)

wincache_ucache_get — Gets a variable stored in the user cache

### Description

wincache_ucache_get(mixed `$key`, bool `&$success` = ?): mixed

Gets a variable stored in the user cache.

### Parameters

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

### Return Values

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.

### Examples

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)

### See Also

- wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- __wakeup()

# wincache_ucache_inc

(PECL wincache >= 1.1.0)

wincache_ucache_inc — Increments the value associated with the key

### Description

wincache_ucache_inc(string `$key`, int `$inc_by` = 1, bool `&$success` = ?): mixed

Increments the value associated with the `key` by 1 or as specified by `inc_by`.

### Parameters

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

### Return Values

Returns the incremented value on success and `false` on failure.

### Examples

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)

### See Also

- wincache_ucache_dec() - Decrements the value associated with the key
- wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

# wincache_ucache_info

(PECL wincache >= 1.1.0)

wincache_ucache_info — Retrieves information about data stored in the user cache

### Description

wincache_ucache_info(bool `$summaryonly` = `false`, string `$key` = NULL): array|false

Retrieves information about data stored in the user cache.

### Parameters

`summaryonly`

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

### Return Values

Array of meta data about user cache or `false` on failure

The array returned by this function contains the following elements:

- `total_cache_uptime` - total time in seconds that the user cache has been active
- `total_item_count` - total number of elements that are currently in the user cache
- `is_local_cache` - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
- `total_hit_count` - number of times the data has been served from the cache
- `total_miss_count` - number of times the data has not been found in the cache

- `ucache_entries` - an array that contains the information about all the cached items:

  - `key_name` - name of the key which is used to store the data
  - `value_type` - type of value stored by the key
  - `use_time` - time in seconds since the file has been accessed in the opcode cache
  - `last_check` - time in seconds since the file has been checked for modifications
  - `is_session` - indicates if the data is a session variable
  - `ttl_seconds` - time remaining for the data to live in the cache, 0 meaning infinite
  - `age_seconds` - time elapsed from the time data has been added in the cache
  - `hitcount` - number of times data has been served from the cache

### Examples

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

### See Also

- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_ucache_meminfo

(PECL wincache >= 1.1.0)

wincache_ucache_meminfo — Retrieves information about user cache memory usage

### Description

wincache_ucache_meminfo(): array|false

Retrieves information about memory usage by user cache.

### Parameters

This function has no parameters.

### Return Values

Array of meta data about user cache memory usage or `false` on failure

The array returned by this function contains the following elements:

- `memory_total` - amount of memory in bytes allocated for the user cache
- `memory_free` - amount of free memory in bytes available for the user cache
- `num_used_blks` - number of memory blocks used by the user cache
- `num_free_blks` - number of free memory blocks available for the user cache
- `memory_overhead` - amount of memory in bytes used for the user cache internal structures

### Examples

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
    )

### See Also

- wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
- wincache_fcache_meminfo() - Retrieves information about file cache memory usage
- wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
- wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
- wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
- wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache
- wincache_scache_meminfo() - Retrieves information about session cache memory usage

# wincache_ucache_set

(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

### Description

wincache_ucache_set(mixed `$key`, mixed `$value`, int `$ttl` = 0): bool
wincache_ucache_set(array `$values`, mixed `$unused` = NULL, int `$ttl` = 0): bool

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.

### Parameters

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

`values`

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

### Return Values

If `key` is string, the function returns `true` on success and `false` on failure.

If `key` is an array, the function returns:

- If all the name => value pairs in the array can be set, function returns an empty array;
- If all the name => value pairs in the array cannot be set, function returns `false`;
- If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

### Examples

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"

### See Also

- wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- __sleep()

# wincache_unlock

(PECL wincache >= 1.1.0)

wincache_unlock — Releases an exclusive lock on a given key

### Description

wincache_unlock(string `$key`): bool

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.

Warning

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.

### Parameters

`key`

  Name of the key in the cache to release the lock on.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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

### See Also

- wincache_lock() - Acquires an exclusive lock on a given key
- wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_ucache_get() - Gets a variable stored in the user cache
- wincache_ucache_delete() - Deletes variables from the user cache
- wincache_ucache_clear() - Deletes entire content of the user cache
- wincache_ucache_exists() - Checks if a variable exists in the user cache
- wincache_ucache_meminfo() - Retrieves information about user cache memory usage
- wincache_ucache_info() - Retrieves information about data stored in the user cache
- wincache_scache_info() - Retrieves information about files cached in the session cache

## Table of Contents

- wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
- wincache_fcache_meminfo — Retrieves information about file cache memory usage
- wincache_lock — Acquires an exclusive lock on a given key
- wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
- wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
- wincache_refresh_if_changed — Refreshes the cache entries for the cached files
- wincache_rplist_fileinfo — Retrieves information about resolve file path cache
- wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
- wincache_scache_info — Retrieves information about files cached in the session cache
- wincache_scache_meminfo — Retrieves information about session cache memory usage
- wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
- wincache_ucache_cas — Compares the variable with old value and assigns new value to it
- wincache_ucache_clear — Deletes entire content of the user cache
- wincache_ucache_dec — Decrements the value associated with the key
- wincache_ucache_delete — Deletes variables from the user cache
- wincache_ucache_exists — Checks if a variable exists in the user cache
- wincache_ucache_get — Gets a variable stored in the user cache
- wincache_ucache_inc — Increments the value associated with the key
- wincache_ucache_info — Retrieves information about data stored in the user cache
- wincache_ucache_meminfo — Retrieves information about user cache memory usage
- wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
- wincache_unlock — Releases an exclusive lock on a given key

# Building for Windows

## Table of Contents

- Prerequisites
- Compiling and building
- Verifying the build

## Prerequisites

Building WinCache extension will require:

1. PHP source code
2. PHP build environment
3. WinCache source code

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.

## Compiling and building

The following steps describe how to compile and build WinCache on Windows OS:

1. Open a command prompt which is used to build PHP

2. Go to the root folder where PHP sources are present

3. Run the command:

       cscript.exe win32\build\buildconf.js

4. Run the command:

       configure.bat --help

   The output will contain a new flag `--enable-wincache`.

5. Run the command:

       configure.js [all options used to build PHP] --enable-wincache

   `--enable-wincache` is the only extra option which is required to ensure that WinCache extension gets built properly. This option will build WinCache and will statically link it with PHP dll. To build WinCache extension as a stand-alone DLL use the option `--enable-wincache=shared`.

6. Run the command:

       nmake

## Verifying the build

The following steps describe how to verify that WinCache has been built correctly:

1. Go to the folder where the PHP binaries are built

2. Run the command:

       php.exe -n -d extension=php_wincache.dll -re wincache

   If WinCache has been built properly, the output of this command will list the INI directives and functions supported by WinCache.

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - WinCache Statistics Script
  - WinCache Session Handler
  - WinCache Functions Reroutes
- WinCache Functions
  - wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
  - wincache_fcache_meminfo — Retrieves information about file cache memory usage
  - wincache_lock — Acquires an exclusive lock on a given key
  - wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
  - wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
  - wincache_refresh_if_changed — Refreshes the cache entries for the cached files
  - wincache_rplist_fileinfo — Retrieves information about resolve file path cache
  - wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
  - wincache_scache_info — Retrieves information about files cached in the session cache
  - wincache_scache_meminfo — Retrieves information about session cache memory usage
  - wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
  - wincache_ucache_cas — Compares the variable with old value and assigns new value to it
  - wincache_ucache_clear — Deletes entire content of the user cache
  - wincache_ucache_dec — Decrements the value associated with the key
  - wincache_ucache_delete — Deletes variables from the user cache
  - wincache_ucache_exists — Checks if a variable exists in the user cache
  - wincache_ucache_get — Gets a variable stored in the user cache
  - wincache_ucache_inc — Increments the value associated with the key
  - wincache_ucache_info — Retrieves information about data stored in the user cache
  - wincache_ucache_meminfo — Retrieves information about user cache memory usage
  - wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
  - wincache_unlock — Releases an exclusive lock on a given key
- Building for Windows
  - Prerequisites
  - Compiling and building
  - Verifying the build

# Hierarchical Profiler

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

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

## Installation

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: » https://pecl.php.net/package/xhprof

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Xhprof Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
xhprof.output_dir | "" | `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.

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

`XHPROF_FLAGS_NO_BUILTINS` (int)
  Used to skip all built-in (internal) functions.
`XHPROF_FLAGS_CPU` (int)
  Used to add CPU profiling information to the output.
`XHPROF_FLAGS_MEMORY` (int)
  Used to add memory profiling information to the output.

# Examples

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

# Xhprof Functions

# xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — Stops xhprof profiler

### Description

xhprof_disable(): ?array

Stops the profiler, and returns xhprof data from the run.

### Parameters

This function has no parameters.

### Return Values

An array of xhprof data, from the run. Returns `null` if profiling is not enabled.

### Examples

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
            )

    )

# xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enable — Start xhprof profiler

### Description

xhprof_enable(int `$flags` = 0, array `$options` = ?): void

Start xhprof profiling.

### Parameters

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

`options`

  An array of optional options, namely, the 'ignored_functions' option to pass in functions to be ignored during profiling.

### Return Values

`null`

### Changelog

Version | Description
--- | ---
PECL xhprof 0.9.2 | The optional `options` parameter was added.

### Examples

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')));
?>`

### See Also

- xhprof_disable() - Stops xhprof profiler
- xhprof_sample_enable() - Start XHProf profiling in sampling mode
- memory_get_usage() - Returns the amount of memory allocated to PHP
- getrusage() - Gets the current resource usages

# xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — Stops xhprof sample profiler

### Description

xhprof_sample_disable(): ?array

Stops the sample mode xhprof profiler, and returns the profile info.

### Parameters

This function has no parameters.

### Return Values

An array of xhprof sample data, from the run. Returns `null` if profiling is not enabled.

### Examples

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

# xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Start XHProf profiling in sampling mode

### Description

xhprof_sample_enable(): void

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.

### Parameters

This function has no parameters.

### Return Values

`null`

### See Also

- xhprof_sample_disable() - Stops xhprof sample profiler
- xhprof_enable() - Start xhprof profiler
- memory_get_usage() - Returns the amount of memory allocated to PHP
- getrusage() - Gets the current resource usages

## Table of Contents

- xhprof_disable — Stops xhprof profiler
- xhprof_enable — Start xhprof profiler
- xhprof_sample_disable — Stops xhprof sample profiler
- xhprof_sample_enable — Start XHProf profiling in sampling mode

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Examples
- Xhprof Functions
  - xhprof_disable — Stops xhprof profiler
  - xhprof_enable — Start xhprof profiler
  - xhprof_sample_disable — Stops xhprof sample profiler
  - xhprof_sample_enable — Start XHProf profiling in sampling mode

# Yac

# Introduction

Yac (Yet Another cache), is a lock-free, shared memory user data cache, could be used to replace APC, local memcache.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

## Installation

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: » https://pecl.php.net/package/yac.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yac Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
yac.compress_threshold | -1 | `INI_SYSTEM` |
yac.debug | 0 | `INI_ALL` |
yac.enable | 1 | `INI_SYSTEM` |
yac.enable_cli | 0 | `INI_SYSTEM` |
yac.keys_memory_size | 4M | `INI_SYSTEM` |
yac.serializer | php | `INI_SYSTEM` |
yac.values_memory_size | 64M | `INI_SYSTEM` |

Here's a short explanation of the configuration directives.

`yac.compress_threshold` int

`yac.debug` int

`yac.enable` int

`yac.enable_cli` int

`yac.keys_memory_size` string

`yac.serializer` string

`yac.values_memory_size` string

## Resource Types

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

`YAC_VERSION` (string)
`YAC_MAX_KEY_LEN` (int)
  Max length of a key could be, it is 48 bytes.
`YAC_MAX_VALUE_RAW_LEN` (int)
`YAC_MAX_RAW_COMPRESSED_LEN` (int)
`YAC_SERIALIZER_PHP` (int)
  Use php serialize as serializer
`YAC_SERIALIZER_JSON` (int)
  Use json as serializer(requrie --enable-json)
`YAC_SERIALIZER_IGBINARY` (int)
  Use igbinary as serializer(require --enable-igbinary)
`YAC_SERIALIZER_MSGPACK` (int)
  Use msgpack as serializer(require --enable-msgpack)
`YAC_SERIALIZER` (string)
  Which serialzier is yac used

# The Yac class

(PECL yac >= 1.0.0)

## Introduction

## Class synopsis

class Yac {
/* Properties */
protected $_prefix;
/* Methods */
public __construct(string `$prefix` = "")
public add(string `$keys`, mixed `$value`, int `$ttl` = 0): bool
public add(array `$key_vals`): bool
public delete(string|array `$keys`, int `$ttl` = ?): bool
public dump(int `$$num`): mixed
public flush(): bool
public get(string|array `$key`, int `&$cas` = `null`): mixed
public __get(string `$key`): mixed
public info(): array
public set(string `$keys`, mixed `$value`, int `$ttl` = 0): bool
public add(array `$key_vals`): bool
public __set(string `$keys`, mixed `$value`): mixed
}

## Properties

_prefix

# Yac::add

(PECL yac >= 1.0.0)

Yac::add — Store into cache

### Description

public Yac::add(string `$keys`, mixed `$value`, int `$ttl` = 0): bool
public Yac::add(array `$key_vals`): bool

Added a item into cache.

### Parameters

`keys`

  string key

`value`

  mixed value, All php value type could be stored except resource

`ttl`

  expire time

### Return Values

bool, `true` on success, `false` on failure

> Note:

> Yac::add() may fail if cas lock could not obtain, so, if you need the value to be stored properly, you may write codes like:

> Example #1 Make sure the item is stored

> `while(!$yac->set("key", "vale));`

# Yac::__construct

(PECL yac >= 1.0.0)

Yac::__construct — Constructor

### Description

public Yac::__construct(string `$prefix` = "")

prefix is used to prepended to keys, this could be used to avoiding conflicts between apps.

### Parameters

`prefix`

  string prefix

### Errors/Exceptions

Throws an Exception if Yac is not enabled. Throws Exception if `prefix` exceeds max key length of 48 (`YAC_MAX_KEY_LEN`) bytes.

# Yac::delete

(PECL yac >= 1.0.0)

Yac::delete — Remove items from cache

### Description

public Yac::delete(string|array `$keys`, int `$ttl` = ?): bool

remove items from cache

### Parameters

`keys`

  string key, or array of multiple keys to be removed

`ttl`

  if delay is set, delete will mark the items to be invalid in ttl second.

### Return Values

# Yac::dump

(PECL yac >= 1.0.0)

Yac::dump — Dump cache

### Description

public Yac::dump(int `$$num`): mixed

Dump values stored in cache

### Parameters

`num`

  Maximum number of items should be returned

### Return Values

mixed

# Yac::flush

(PECL yac >= 1.0.0)

Yac::flush — Flush the cache

### Description

public Yac::flush(): bool

Remove all cached values

### Parameters

This function has no parameters.

### Return Values

bool, always true

# Yac::get

(PECL yac >= 1.0.0)

Yac::get — Retrieve values from cache

### Description

public Yac::get(string|array `$key`, int `&$cas` = `null`): mixed

Retrieve values from cache

### Parameters

`key`

  string keys, or array of multiple keys.

`cas`

  if not `null`, it will be set to the retrieved item's cas.

### Return Values

mixed on success, false on failure

# Yac::__get

(PECL yac >= 1.0.0)

Yac::__get — Getter

### Description

public Yac::__get(string `$key`): mixed

Retrieve values from cache

### Parameters

`key`

  string key

### Return Values

mixed on success, `null` on failure

# Yac::info

(PECL yac >= 1.0.0)

Yac::info — Status of cache

### Description

public Yac::info(): array

Get status of cache system

### Parameters

This function has no parameters.

### Return Values

Return an array, consistent with: "memory_size", "slots_memory_size", "values_memory_size", "segment_size", "segment_num", "miss", "hits", "fails", "kicks", "recycles", "slots_size", "slots_used"

# Yac::set

(PECL yac >= 1.0.0)

Yac::set — Store into cache

### Description

public Yac::set(string `$keys`, mixed `$value`, int `$ttl` = 0): bool
public Yac::add(array `$key_vals`): bool

Add a item into cache, it the key is already exists, override it.

### Parameters

`keys`

  string key

`value`

  mixed value, All php value type could be stored except resource

`ttl`

  expire time

### Return Values

the value self

# Yac::__set

(PECL yac >= 1.0.0)

Yac::__set — Setter

### Description

public Yac::__set(string `$keys`, mixed `$value`): mixed

store a item into cache

### Parameters

`keys`

  string key

`value`

  mixed value, All php value type could be stored except resource

### Return Values

Always return the value self

## Table of Contents

- Yac::add — Store into cache
- Yac::__construct — Constructor
- Yac::delete — Remove items from cache
- Yac::dump — Dump cache
- Yac::flush — Flush the cache
- Yac::get — Retrieve values from cache
- Yac::__get — Getter
- Yac::info — Status of cache
- Yac::set — Store into cache
- Yac::__set — Setter

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Yac — The Yac class
  - Yac::add — Store into cache
  - Yac::__construct — Constructor
  - Yac::delete — Remove items from cache
  - Yac::dump — Dump cache
  - Yac::flush — Flush the cache
  - Yac::get — Retrieve values from cache
  - Yac::__get — Getter
  - Yac::info — Status of cache
  - Yac::set — Store into cache
  - Yac::__set — Setter

- APCu — APC User Cache
  - Installing/Configuring
  - Predefined Constants
  - APCu Functions
  - APCUIterator — The APCUIterator class
- Componere
  - Installing/Configuring
  - Componere\Abstract\Definition — The Componere\Abstract\Definition class
  - Componere\Definition — The Componere\Definition class
  - Componere\Patch — The Componere\Patch class
  - Componere\Method — The Componere\Method class
  - Componere\Value — The Componere\Value class
  - Componere Functions
- Error Handling — Error Handling and Logging
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Error Handling Functions
- FFI — Foreign Function Interface
  - Installing/Configuring
  - Examples
  - FFI — Main interface to C code and data
  - FFI\CData — C Data Handles
  - FFI\CType — C Type Handles
  - FFI\Exception — FFI Exceptions
  - FFI\ParserException — FFI Parser Exceptions
- OPcache
  - Installing/Configuring
  - Preloading
  - OPcache Functions
- Output Control — Output Buffering Control
  - Installing/Configuring
  - Predefined Constants
  - Output Buffering
  - Flushing System Buffers
  - User-Level Output Buffers
  - Examples
  - Output Control Functions
- PHP Options/Info — PHP Options and Information
  - Installing/Configuring
  - Predefined Constants
  - PHP Options/Info Functions
- phpdbg — Interactive PHP Debugger
  - Installing/Configuring
  - Predefined Constants
  - phpdbg Functions
- runkit7
  - Installing/Configuring
  - Predefined Constants
  - runkit7 Functions
- uopz — User Operations for Zend
  - Installing/Configuring
  - Predefined Constants
  - Uopz Functions
- WinCache — Windows Cache for PHP
  - Installing/Configuring
  - WinCache Functions
  - Building for Windows
- Xhprof — Hierarchical Profiler
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Xhprof Functions
- Yac
  - Installing/Configuring
  - Predefined Constants
  - Yac — The Yac class

# Audio Formats Manipulation

# OpenAL Audio Bindings

# Introduction

Platform independent audio bindings. Requires the » OpenAL library.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

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: » https://pecl.php.net/package/openal.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

## Resource Types

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

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

`ALC_FREQUENCY` (int)
  Context Attribute
`ALC_REFRESH` (int)
  Context Attribute
`ALC_SYNC` (int)
  Context Attribute
`AL_FREQUENCY` (int)
  Buffer Setting
`AL_BITS` (int)
  Buffer Setting
`AL_CHANNELS` (int)
  Buffer Setting
`AL_SIZE` (int)
  Buffer Setting
`AL_BUFFER` (int)
  Source/Listener Setting (Integer)
`AL_SOURCE_RELATIVE` (int)
  Source/Listener Setting (Integer)
`AL_SOURCE_STATE` (int)
  Source/Listener Setting (Integer)
`AL_PITCH` (int)
  Source/Listener Setting (Float)
`AL_GAIN` (int)
  Source/Listener Setting (Float)
`AL_MIN_GAIN` (int)
  Source/Listener Setting (Float)
`AL_MAX_GAIN` (int)
  Source/Listener Setting (Float)
`AL_MAX_DISTANCE` (int)
  Source/Listener Setting (Float)
`AL_ROLLOFF_FACTOR` (int)
  Source/Listener Setting (Float)
`AL_CONE_OUTER_GAIN` (int)
  Source/Listener Setting (Float)
`AL_CONE_INNER_ANGLE` (int)
  Source/Listener Setting (Float)
`AL_CONE_OUTER_ANGLE` (int)
  Source/Listener Setting (Float)
`AL_REFERENCE_DISTANCE` (int)
  Source/Listener Setting (Float)
`AL_POSITION` (int)
  Source/Listener Setting (Float Vector)
`AL_VELOCITY` (int)
  Source/Listener Setting (Float Vector)
`AL_DIRECTION` (int)
  Source/Listener Setting (Float Vector)
`AL_ORIENTATION` (int)
  Source/Listener Setting (Float Vector)
`AL_FORMAT_MONO8` (int)
  PCM Format
`AL_FORMAT_MONO16` (int)
  PCM Format
`AL_FORMAT_STEREO8` (int)
  PCM Format
`AL_FORMAT_STEREO16` (int)
  PCM Format
`AL_INITIAL` (int)
  Source State
`AL_PLAYING` (int)
  Source State
`AL_PAUSED` (int)
  Source State
`AL_STOPPED` (int)
  Source State
`AL_LOOPING` (int)
  Source State
`AL_TRUE` (int)
  Boolean value recognized by OpenAL
`AL_FALSE` (int)
  Boolean value recognized by OpenAL

# OpenAL Functions

# openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create — Generate OpenAL buffer

### Description

openal_buffer_create(): resource

### Parameters

This function has no parameters.

### Return Values

Returns an Open AL(Buffer) resource on success or `false` on failure.

### See Also

- openal_buffer_loadwav() - Load a .wav file into a buffer
- openal_buffer_data() - Load a buffer with data

# openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data — Load a buffer with data

### Description

openal_buffer_data(
resource `$buffer`,
int `$format`,
string `$data`,
int `$freq`
): bool

### Parameters

`buffer`
  An 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.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_buffer_loadwav() - Load a .wav file into a buffer
- openal_stream() - Begin streaming on a source

# openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy — Destroys an OpenAL buffer

### Description

openal_buffer_destroy(resource `$buffer`): bool

### Parameters

`buffer`
  An Open AL(Buffer) resource (previously created by openal_buffer_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_buffer_create() - Generate OpenAL buffer

# openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get — Retrieve an OpenAL buffer property

### Description

openal_buffer_get(resource `$buffer`, int `$property`): int|false

### Parameters

`buffer`
  An Open AL(Buffer) resource (previously created by openal_buffer_create()).
`property`
  Specific property, one of: `AL_FREQUENCY`, `AL_BITS`, `AL_CHANNELS` and `AL_SIZE`.

### Return Values

Returns an integer value appropriate to the `property` requested or `false` on failure.

### See Also

- openal_buffer_create() - Generate OpenAL buffer

# openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav — Load a .wav file into a buffer

### Description

openal_buffer_loadwav(resource `$buffer`, string `$wavfile`): bool

### Parameters

`buffer`
  An Open AL(Buffer) resource (previously created by openal_buffer_create()).
`wavfile`
  Path to .wav file on local file system.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_buffer_data() - Load a buffer with data
- openal_stream() - Begin streaming on a source

# openal_context_create

(PECL openal >= 0.1.0)

openal_context_create — Create an audio processing context

### Description

openal_context_create(resource `$device`): resource

### Parameters

`device`
  An Open AL(Device) resource (previously created by openal_device_open()).

### Return Values

Returns an Open AL(Context) resource on success or `false` on failure.

### See Also

- openal_device_open() - Initialize the OpenAL audio layer
- openal_context_destroy() - Destroys a context

# openal_context_current

(PECL openal >= 0.1.0)

openal_context_current — Make the specified context current

### Description

openal_context_current(resource `$context`): bool

### Parameters

`context`
  An Open AL(Context) resource (previously created by openal_context_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_context_create() - Create an audio processing context

# openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy — Destroys a context

### Description

openal_context_destroy(resource `$context`): bool

### Parameters

`context`
  An Open AL(Context) resource (previously created by openal_context_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_context_create() - Create an audio processing context

# openal_context_process

(PECL openal >= 0.1.0)

openal_context_process — Process the specified context

### Description

openal_context_process(resource `$context`): bool

### Parameters

`context`
  An Open AL(Context) resource (previously created by openal_context_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_context_create() - Create an audio processing context
- openal_context_current() - Make the specified context current
- openal_context_suspend() - Suspend the specified context

# openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend — Suspend the specified context

### Description

openal_context_suspend(resource `$context`): bool

### Parameters

`context`
  An Open AL(Context) resource (previously created by openal_context_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_context_create() - Create an audio processing context
- openal_context_current() - Make the specified context current
- openal_context_process() - Process the specified context

# openal_device_close

(PECL openal >= 0.1.0)

openal_device_close — Close an OpenAL device

### Description

openal_device_close(resource `$device`): bool

### Parameters

`device`
  An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_device_open() - Initialize the OpenAL audio layer

# openal_device_open

(PECL openal >= 0.1.0)

openal_device_open — Initialize the OpenAL audio layer

### Description

openal_device_open(string `$device_desc` = ?): resource

### Parameters

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

### Return Values

Returns an Open AL(Device) resource on success or `false` on failure.

### See Also

- openal_device_close() - Close an OpenAL device
- openal_context_create() - Create an audio processing context

# openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get — Retrieve a listener property

### Description

openal_listener_get(int `$property`): mixed

### Parameters

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

### Return Values

Returns a float or array of floats (as appropriate) or `false` on failure.

### See Also

- openal_listener_set() - Set a listener property

# openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set — Set a listener property

### Description

openal_listener_set(int `$property`, mixed `$setting`): bool

### Parameters

`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)).
`setting`
  Value to set, either float, or an array of floats as appropriate.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_listener_get() - Retrieve a listener property

# openal_source_create

(PECL openal >= 0.1.0)

openal_source_create — Generate a source resource

### Description

openal_source_create(): resource

### Parameters

This function has no parameters.

### Return Values

Returns an Open AL(Source) resource on success or `false` on failure.

### See Also

- openal_source_set() - Set source property
- openal_source_play() - Start playing the source
- openal_source_destroy() - Destroy a source resource

# openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy — Destroy a source resource

### Description

openal_source_destroy(resource `$source`): bool

### Parameters

`source`
  An Open AL(Source) resource (previously created by openal_source_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_create() - Generate a source resource

# openal_source_get

(PECL openal >= 0.1.0)

openal_source_get — Retrieve an OpenAL source property

### Description

openal_source_get(resource `$source`, int `$property`): mixed

### Parameters

`source`
  An 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)).

### Return Values

Returns the type associated with the property being retrieved or `false` on failure.

### See Also

- openal_source_create() - Generate a source resource
- openal_source_set() - Set source property
- openal_source_play() - Start playing the source

# openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause — Pause the source

### Description

openal_source_pause(resource `$source`): bool

### Parameters

`source`
  An Open AL(Source) resource (previously created by openal_source_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_stop() - Stop playing the source
- openal_source_play() - Start playing the source
- openal_source_rewind() - Rewind the source

# openal_source_play

(PECL openal >= 0.1.0)

openal_source_play — Start playing the source

### Description

openal_source_play(resource `$source`): bool

### Parameters

`source`
  An Open AL(Source) resource (previously created by openal_source_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_stop() - Stop playing the source
- openal_source_pause() - Pause the source
- openal_source_rewind() - Rewind the source

# openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind — Rewind the source

### Description

openal_source_rewind(resource `$source`): bool

### Parameters

`source`
  An Open AL(Source) resource (previously created by openal_source_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_stop() - Stop playing the source
- openal_source_pause() - Pause the source
- openal_source_play() - Start playing the source

# openal_source_set

(PECL openal >= 0.1.0)

openal_source_set — Set source property

### Description

openal_source_set(resource `$source`, int `$property`, mixed `$setting`): bool

### Parameters

`source`
  An 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.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_create() - Generate a source resource
- openal_source_get() - Retrieve an OpenAL source property
- openal_source_play() - Start playing the source

# openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop — Stop playing the source

### Description

openal_source_stop(resource `$source`): bool

### Parameters

`source`
  An Open AL(Source) resource (previously created by openal_source_create()).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- openal_source_play() - Start playing the source
- openal_source_pause() - Pause the source
- openal_source_rewind() - Rewind the source

# openal_stream

(PECL openal >= 0.1.0)

openal_stream — Begin streaming on a source

### Description

openal_stream(resource `$source`, int `$format`, int `$rate`): resource|false

### Parameters

`source`
  An 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`
`rate`
  Frequency of data to stream given in Hz.

### Return Values

Returns a stream resource on success or `false` on failure.

### See Also

- openal_source_create() - Generate a source resource
- fwrite() - Binary-safe file write

## Table of Contents

- openal_buffer_create — Generate OpenAL buffer
- openal_buffer_data — Load a buffer with data
- openal_buffer_destroy — Destroys an OpenAL buffer
- openal_buffer_get — Retrieve an OpenAL buffer property
- openal_buffer_loadwav — Load a .wav file into a buffer
- openal_context_create — Create an audio processing context
- openal_context_current — Make the specified context current
- openal_context_destroy — Destroys a context
- openal_context_process — Process the specified context
- openal_context_suspend — Suspend the specified context
- openal_device_close — Close an OpenAL device
- openal_device_open — Initialize the OpenAL audio layer
- openal_listener_get — Retrieve a listener property
- openal_listener_set — Set a listener property
- openal_source_create — Generate a source resource
- openal_source_destroy — Destroy a source resource
- openal_source_get — Retrieve an OpenAL source property
- openal_source_pause — Pause the source
- openal_source_play — Start playing the source
- openal_source_rewind — Rewind the source
- openal_source_set — Set source property
- openal_source_stop — Stop playing the source
- openal_stream — Begin streaming on a source

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- OpenAL Functions
  - openal_buffer_create — Generate OpenAL buffer
  - openal_buffer_data — Load a buffer with data
  - openal_buffer_destroy — Destroys an OpenAL buffer
  - openal_buffer_get — Retrieve an OpenAL buffer property
  - openal_buffer_loadwav — Load a .wav file into a buffer
  - openal_context_create — Create an audio processing context
  - openal_context_current — Make the specified context current
  - openal_context_destroy — Destroys a context
  - openal_context_process — Process the specified context
  - openal_context_suspend — Suspend the specified context
  - openal_device_close — Close an OpenAL device
  - openal_device_open — Initialize the OpenAL audio layer
  - openal_listener_get — Retrieve a listener property
  - openal_listener_set — Set a listener property
  - openal_source_create — Generate a source resource
  - openal_source_destroy — Destroy a source resource
  - openal_source_get — Retrieve an OpenAL source property
  - openal_source_pause — Pause the source
  - openal_source_play — Start playing the source
  - openal_source_rewind — Rewind the source
  - openal_source_set — Set source property
  - openal_source_stop — Stop playing the source
  - openal_stream — Begin streaming on a source

- OpenAL — OpenAL Audio Bindings
  - Installing/Configuring
  - Predefined Constants
  - OpenAL Functions

# Authentication Services

# Radius

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Installation

## Installation

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: » https://pecl.php.net/package/radius.

# Predefined Constants

## Table of Contents

- RADIUS Options
- RADIUS Packet Types
- RADIUS Attribute Types
- RADIUS Vendor Specific Attribute Types

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` (int)
  The maximum length of MPPE keys.

## RADIUS Options

Several RADIUS functions accept option flags as bitmasks. The constants representing those flags are listed below.

`RADIUS_OPTION_SALT` (int)
  When set, this option will result in the attribute value being salt-encrypted.
`RADIUS_OPTION_TAGGED` (int)
  When set, this option will result in the attribute value being tagged with the value of the tag parameter.

## RADIUS Packet Types

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` (int)
  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` (int)
  An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.
`RADIUS_ACCESS_REJECT` (int)
  An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.
`RADIUS_ACCESS_CHALLENGE` (int)
  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` (int)
  An Accounting-Request, used to convey accounting information for a service to the RADIUS server.
`RADIUS_ACCOUNTING_RESPONSE` (int)
  An Accounting-Response response to an Accounting-Request.
`RADIUS_COA_REQUEST` (int)
  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` (int)
  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` (int)
  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` (int)
  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` (int)
  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` (int)
  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.

## RADIUS Attribute Types

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` (int)
  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` (int)
  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` (int)
  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 = hash('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` (int)
  The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an int, which can be set using radius_put_addr().
`RADIUS_NAS_PORT` (int)
  The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an int, which can be set using radius_put_int().
`RADIUS_SERVICE_TYPE` (int)
  The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an int, 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_LOGIN`
  - `RADIUS_FRAMED`
  - `RADIUS_CALLBACK_LOGIN`
  - `RADIUS_CALLBACK_FRAMED`
  - `RADIUS_OUTBOUND`
  - `RADIUS_ADMINISTRATIVE`
  - `RADIUS_NAS_PROMPT`
  - `RADIUS_AUTHENTICATE_ONLY`
  - `RADIUS_CALLBACK_NAS_PROMPT`
`RADIUS_FRAMED_PROTOCOL` (int)

  The Framed-Protocol attribute. The attribute value is expected to be an int 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_PPP`
  - `RADIUS_SLIP`
  - `RADIUS_ARAP`
  - `RADIUS_GANDALF`
  - `RADIUS_XYLOGICS`
`RADIUS_FRAMED_IP_ADDRESS` (int)
  The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an int, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().
`RADIUS_FRAMED_IP_NETMASK` (int)
  The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an int, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().
`RADIUS_FRAMED_ROUTING` (int)
  The Framed-Routing attribute. The attribute value is expected to be an int indicating the routing method for the user, which can be set using radius_put_int().

  Possible values include:

  - `0`: No routing
  - `1`: Send routing packets
  - `2`: Listen for routing packets
  - `3`: Send and listen
`RADIUS_FILTER_ID` (int)
  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` (int)
  The Framed-MTU attribute. The attribute value is expected to be an int indicating the MTU to be configured for the user, and can be set using radius_put_int().
`RADIUS_FRAMED_COMPRESSION` (int)

  The Framed-Compression attribute. The attribute value is expected to be an int indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:

  - `RADIUS_COMP_NONE`: No compression
  - `RADIUS_COMP_VJ`: VJ TCP/IP header compression
  - `RADIUS_COMP_IPXHDR`: IPX header compression
  - `RADIUS_COMP_STAC_LZS`: Stac-LZS compression (added in PECL radius 1.3.0b2)
`RADIUS_LOGIN_IP_HOST` (int)
  The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an int, which can be set using radius_put_addr().
`RADIUS_LOGIN_SERVICE` (int)
  The Login-Service attribute. The attribute value is an int 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` (int)
  The Login-TCP-Port attribute. The attribute value is an int 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` (int)
  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` (int)
  The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.
`RADIUS_CALLBACK_ID` (int)
  The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.
`RADIUS_FRAMED_ROUTE` (int)
  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` (int)
  The Framed-IPX-Network attribute. The attribute value is an int 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` (int)
  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` (int)
  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` (int)
  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` (int)
  Session timeout
`RADIUS_IDLE_TIMEOUT` (int)
  Idle timeout
`RADIUS_TERMINATION_ACTION` (int)
  Termination action
`RADIUS_CALLED_STATION_ID` (int)
  Called Station Id
`RADIUS_CALLING_STATION_ID` (int)
  Calling Station Id
`RADIUS_NAS_IDENTIFIER` (int)
  NAS ID
`RADIUS_PROXY_STATE` (int)
  Proxy State
`RADIUS_LOGIN_LAT_SERVICE` (int)
  Login LAT Service
`RADIUS_LOGIN_LAT_NODE` (int)
  Login LAT Node
`RADIUS_LOGIN_LAT_GROUP` (int)
  Login LAT Group
`RADIUS_FRAMED_APPLETALK_LINK` (int)
  Framed Appletalk Link
`RADIUS_FRAMED_APPLETALK_NETWORK` (int)
  Framed Appletalk Network
`RADIUS_FRAMED_APPLETALK_ZONE` (int)
  Framed Appletalk Zone
`RADIUS_CHAP_CHALLENGE` (int)
  Challenge
`RADIUS_NAS_PORT_TYPE` (int)

  NAS port type, one of:

  - `RADIUS_ASYNC`
  - `RADIUS_SYNC`
  - `RADIUS_ISDN_SYNC`
  - `RADIUS_ISDN_ASYNC_V120`
  - `RADIUS_ISDN_ASYNC_V110`
  - `RADIUS_VIRTUAL`
  - `RADIUS_PIAFS`
  - `RADIUS_HDLC_CLEAR_CHANNEL`
  - `RADIUS_X_25`
  - `RADIUS_X_75`
  - `RADIUS_G_3_FAX`
  - `RADIUS_SDSL`
  - `RADIUS_ADSL_CAP`
  - `RADIUS_ADSL_DMT`
  - `RADIUS_IDSL`
  - `RADIUS_ETHERNET`
  - `RADIUS_XDSL`
  - `RADIUS_CABLE`
  - `RADIUS_WIRELESS_OTHER`
  - `RADIUS_WIRELESS_IEEE_802_11`
`RADIUS_PORT_LIMIT` (int)
  Port Limit
`RADIUS_LOGIN_LAT_PORT` (int)
  Login LAT Port
`RADIUS_CONNECT_INFO` (int)
  Connect info
`RADIUS_ACCT_STATUS_TYPE` (int)

  Accounting status type, one of:

  - `RADIUS_START`
  - `RADIUS_STOP`
  - `RADIUS_ACCOUNTING_ON`
  - `RADIUS_ACCOUNTING_OFF`
`RADIUS_ACCT_DELAY_TIME` (int)
  Accounting delay time
`RADIUS_ACCT_INPUT_OCTETS` (int)
  Accounting input bytes
`RADIUS_ACCT_OUTPUT_OCTETS` (int)
  Accounting output bytes
`RADIUS_ACCT_SESSION_ID` (int)
  Accounting session ID
`RADIUS_ACCT_AUTHENTIC` (int)

  Accounting authentic, one of:

  - `RADIUS_AUTH_RADIUS`
  - `RADIUS_AUTH_LOCAL`
  - `RADIUS_AUTH_REMOTE`
`RADIUS_ACCT_SESSION_TIME` (int)
  Accounting session time
`RADIUS_ACCT_INPUT_PACKETS` (int)
  Accounting input packets
`RADIUS_ACCT_OUTPUT_PACKETS` (int)
  Accounting output packets
`RADIUS_ACCT_TERMINATE_CAUSE` (int)

  Accounting terminate cause, one of:

  - `RADIUS_TERM_USER_REQUEST`
  - `RADIUS_TERM_LOST_CARRIER`
  - `RADIUS_TERM_LOST_SERVICE`
  - `RADIUS_TERM_IDLE_TIMEOUT`
  - `RADIUS_TERM_SESSION_TIMEOUT`
  - `RADIUS_TERM_ADMIN_RESET`
  - `RADIUS_TERM_ADMIN_REBOOT`
  - `RADIUS_TERM_PORT_ERROR`
  - `RADIUS_TERM_NAS_ERROR`
  - `RADIUS_TERM_NAS_REQUEST`
  - `RADIUS_TERM_NAS_REBOOT`
  - `RADIUS_TERM_PORT_UNNEEDED`
  - `RADIUS_TERM_PORT_PREEMPTED`
  - `RADIUS_TERM_PORT_SUSPENDED`
  - `RADIUS_TERM_SERVICE_UNAVAILABLE`
  - `RADIUS_TERM_CALLBACK`
  - `RADIUS_TERM_USER_ERROR`
  - `RADIUS_TERM_HOST_REQUEST`
`RADIUS_ACCT_MULTI_SESSION_ID` (int)
  Accounting multi session ID
`RADIUS_ACCT_LINK_COUNT` (int)
  Accounting link count

Service-Type Constants
`RADIUS_LOGIN`
`RADIUS_FRAMED`
`RADIUS_CALLBACK_LOGIN`
`RADIUS_CALLBACK_FRAMED`
`RADIUS_OUTBOUND`
`RADIUS_ADMINISTRATIVE`
`RADIUS_NAS_PROMPT`
`RADIUS_AUTHENTICATE_ONLY`
`RADIUS_CALLBACK_NAS_PROMPT`

Framed-Protocol Constants
`RADIUS_PPP`
`RADIUS_SLIP`
`RADIUS_ARAP`
`RADIUS_GANDALF`
`RADIUS_XYLOGICS`

Framed-Compression Constants
`RADIUS_COMP_NONE`
`RADIUS_COMP_VJ`
`RADIUS_COMP_IPXHDR`
`RADIUS_COMP_STAC_LZS`

NAS Port Type Constants
`RADIUS_ASYNC`
`RADIUS_SYNC`
`RADIUS_ISDN_SYNC`
`RADIUS_ISDN_ASYNC_V120`
`RADIUS_ISDN_ASYNC_V110`
`RADIUS_VIRTUAL`
`RADIUS_PIAFS`
`RADIUS_HDLC_CLEAR_CHANNEL`
`RADIUS_X_25`
`RADIUS_X_75`
`RADIUS_G_3_FAX`
`RADIUS_SDSL`
`RADIUS_ADSL_CAP`
`RADIUS_ADSL_DMT`
`RADIUS_IDSL`
`RADIUS_ETHERNET`
`RADIUS_XDSL`
`RADIUS_CABLE`
`RADIUS_WIRELESS_OTHER`
`RADIUS_WIRELESS_IEEE_802_11`

Accounting Status Type Constants
`RADIUS_START`
`RADIUS_STOP`
`RADIUS_ACCOUNTING_ON`
`RADIUS_ACCOUNTING_OFF`

Accounting Authentic Constants
`RADIUS_AUTH_RADIUS`
`RADIUS_AUTH_LOCAL`
`RADIUS_AUTH_REMOTE`

Accounting Terminate Cause Constants
`RADIUS_TERM_USER_REQUEST`
`RADIUS_TERM_LOST_CARRIER`
`RADIUS_TERM_LOST_SERVICE`
`RADIUS_TERM_IDLE_TIMEOUT`
`RADIUS_TERM_SESSION_TIMEOUT`
`RADIUS_TERM_ADMIN_RESET`
`RADIUS_TERM_ADMIN_REBOOT`
`RADIUS_TERM_PORT_ERROR`
`RADIUS_TERM_NAS_ERROR`
`RADIUS_TERM_NAS_REQUEST`
`RADIUS_TERM_NAS_REBOOT`
`RADIUS_TERM_PORT_UNNEEDED`
`RADIUS_TERM_PORT_PREEMPTED`
`RADIUS_TERM_PORT_SUSPENDED`
`RADIUS_TERM_SERVICE_UNAVAILABLE`
`RADIUS_TERM_CALLBACK`
`RADIUS_TERM_USER_ERROR`
`RADIUS_TERM_HOST_REQUEST`

## RADIUS Vendor Specific Attribute Types

`RADIUS_VENDOR_MICROSOFT` (int)

  Microsoft specific vendor attributes (» RFC 2548), one of:

  - `RADIUS_MICROSOFT_MS_CHAP_RESPONSE`
  - `RADIUS_MICROSOFT_MS_CHAP_ERROR`
  - `RADIUS_MICROSOFT_MS_CHAP_PW_1`
  - `RADIUS_MICROSOFT_MS_CHAP_PW_2`
  - `RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW`
  - `RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW`
  - `RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY`
  - `RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES`
  - `RADIUS_MICROSOFT_MS_RAS_VENDOR`
  - `RADIUS_MICROSOFT_MS_CHAP_DOMAIN`
  - `RADIUS_MICROSOFT_MS_CHAP_CHALLENGE`
  - `RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS`
  - `RADIUS_MICROSOFT_MS_BAP_USAGE`
  - `RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD`
  - `RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT`
  - `RADIUS_MICROSOFT_MS_MPPE_SEND_KEY`
  - `RADIUS_MICROSOFT_MS_MPPE_RECV_KEY`
  - `RADIUS_MICROSOFT_MS_RAS_VERSION`
  - `RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD`
  - `RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD`
  - `RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON`
  - `RADIUS_MICROSOFT_MS_FILTER`
  - `RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE`
  - `RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE`
  - `RADIUS_MICROSOFT_MS_CHAP2_RESPONSE`
  - `RADIUS_MICROSOFT_MS_CHAP2_SUCCESS`
  - `RADIUS_MICROSOFT_MS_CHAP2_PW`
  - `RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER`
  - `RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER`
  - `RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER`
  - `RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER`
  - `RADIUS_MICROSOFT_MS_ARAP_CHALLENGE`
`RADIUS_MICROSOFT_MS_CHAP_RESPONSE`
`RADIUS_MICROSOFT_MS_CHAP_ERROR`
`RADIUS_MICROSOFT_MS_CHAP_PW_1`
`RADIUS_MICROSOFT_MS_CHAP_PW_2`
`RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW`
`RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW`
`RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY`
`RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES`
`RADIUS_MICROSOFT_MS_RAS_VENDOR`
`RADIUS_MICROSOFT_MS_CHAP_DOMAIN`
`RADIUS_MICROSOFT_MS_CHAP_CHALLENGE`
`RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS`
`RADIUS_MICROSOFT_MS_BAP_USAGE`
`RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD`
`RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT`
`RADIUS_MICROSOFT_MS_MPPE_SEND_KEY`
`RADIUS_MICROSOFT_MS_MPPE_RECV_KEY`
`RADIUS_MICROSOFT_MS_RAS_VERSION`
`RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD`
`RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD`
`RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON`
`RADIUS_MICROSOFT_MS_FILTER`
`RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE`
`RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE`
`RADIUS_MICROSOFT_MS_CHAP2_RESPONSE`
`RADIUS_MICROSOFT_MS_CHAP2_SUCCESS`
`RADIUS_MICROSOFT_MS_CHAP2_PW`
`RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER`
`RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER`
`RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER`
`RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER`
`RADIUS_MICROSOFT_MS_ARAP_CHALLENGE`

# Examples

Howto start?

- get a radius resource
- configure the library
- create the request
- put attributes
- send the request
- receive attributes
- close the radius resource (optional)

Take also a look at the examples in this package.

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.

# Radius Functions

# radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates a Radius handle for accounting

### Description

radius_acct_open(): resource

### Parameters

This function has no parameters.

### Return Values

Returns a handle on success, `false` on error. This function only fails if insufficient memory is available.

### Examples

Example #1 radius_acct_open() example

`<?php
$res = radius_acct_open ()
or die ("Could not create handle");
print "Handle successfully created";
?>`

# radius_add_server

(PECL radius >= 1.1.0)

radius_add_server — Adds a server

### Description

radius_add_server(
resource `$radius_handle`,
string `$hostname`,
int `$port`,
string `$secret`,
int `$timeout`,
int `$max_tries`
): bool

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.

### Parameters

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

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

### See Also

- radius_config() - Causes the library to read the given configuration file

# radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates a Radius handle for authentication

### Description

radius_auth_open(): resource

### Parameters

This function has no parameters.

### Return Values

Returns a handle on success, `false` on error. This function only fails if insufficient memory is available.

### Examples

Example #1 radius_auth_open() example

`<?php
$radh = radius_auth_open()
or die ("Could not create handle");
echo "Handle successfully created";
?>`

# radius_close

(PECL radius >= 1.1.0)

radius_close — Frees all ressources

### Description

radius_close(resource `$radius_handle`): bool

It is not needed to call this function because php frees all resources at the end of each request.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

Returns `true` on success or `false` on failure.

# radius_config

(PECL radius >= 1.1.0)

radius_config — Causes the library to read the given configuration file

### Description

radius_config(resource `$radius_handle`, string `$file`): bool

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.

### Parameters

`radius_handle`
`file`
  The 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().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- radius_add_server() - Adds a server

# radius_create_request

(PECL radius >= 1.1.0)

radius_create_request — Create accounting or authentication request

### Description

radius_create_request(resource `$radius_handle`, int `$type`): bool

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!

### Parameters

`radius_handle`
`type`
  Type is `RADIUS_ACCESS_REQUEST` or `RADIUS_ACCOUNTING_REQUEST`.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 radius_create_request() example

`<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>`

### See Also

- radius_send_request() - Sends the request and waits for a reply

# radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

### Description

radius_cvt_addr(string `$data`): string

Converts raw data to IP-Address

### Parameters

`data`
  Input data

### Return Values

Returns the IP-Address.

### Examples

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

### See Also

- radius_cvt_int() - Converts raw data to integer
- radius_cvt_string() - Converts raw data to string

# radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

### Description

radius_cvt_int(string `$data`): int

Converts raw data to integer

### Parameters

`data`
  Input data

### Return Values

Returns the integer, retrieved from data.

### Examples

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

### See Also

- radius_cvt_addr() - Converts raw data to IP-Address
- radius_cvt_string() - Converts raw data to string

# radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts raw data to string

### Description

radius_cvt_string(string `$data`): string

Converts raw data to string

### Parameters

`data`
  Input data

### Return Values

Returns the string, retrieved from data.

### Examples

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

### See Also

- radius_cvt_addr() - Converts raw data to IP-Address
- radius_cvt_int() - Converts raw data to integer

# radius_demangle

(PECL radius >= 1.2.0)

radius_demangle — Demangles data

### Description

radius_demangle(resource `$radius_handle`, string `$mangled`): string

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

### Parameters

`radius_handle`

  The RADIUS resource.

`mangled`
  The mangled data to demangle

### Return Values

Returns the demangled string, or `false` on error.

# radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives mppe-keys from mangled data

### Description

radius_demangle_mppe_key(resource `$radius_handle`, string `$mangled`): string

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`mangled`
  The mangled data to demangle

### Return Values

Returns the demangled string, or `false` on error.

# radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attr — Extracts an attribute

### Description

radius_get_attr(resource `$radius_handle`): mixed

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.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

Returns an associative array containing the attribute-type and the data, or error number <= 0.

### Examples

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

### See Also

- radius_put_attr() - Attaches a binary attribute
- radius_get_vendor_attr() - Extracts a vendor specific attribute
- radius_put_vendor_attr() - Attaches a vendor specific binary attribute
- radius_send_request() - Sends the request and waits for a reply

# radius_get_tagged_attr_data

(PECL radius >= 1.3.0)

radius_get_tagged_attr_data — Extracts the data from a tagged attribute

### Description

radius_get_tagged_attr_data(string `$data`): string|false

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the data from the attribute.

### Parameters

`data`
  The tagged attribute to be decoded.

### Return Values

Returns the data from the tagged attribute or `false` on failure.

### Examples

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

### See Also

- radius_get_attr() - Extracts an attribute
- radius_get_tagged_attr_tag() - Extracts the tag from a tagged attribute

# radius_get_tagged_attr_tag

(PECL radius >= 1.3.0)

radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute

### Description

radius_get_tagged_attr_tag(string `$data`): int|false

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the tag from the attribute.

### Parameters

`data`
  The tagged attribute to be decoded.

### Return Values

Returns the tag from the tagged attribute or `false` on failure.

### Examples

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

### See Also

- radius_get_attr() - Extracts an attribute
- radius_get_tagged_attr_data() - Extracts the data from a tagged attribute

# radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attr — Extracts a vendor specific attribute

### Description

radius_get_vendor_attr(string `$data`): array

If radius_get_attr() returns `RADIUS_VENDOR_SPECIFIC`, radius_get_vendor_attr() may be called to determine the vendor.

### Parameters

`data`
  Input data

### Return Values

Returns an associative array containing the attribute-type, vendor and the data, or `false` on error.

### Examples

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

### See Also

- radius_get_attr() - Extracts an attribute
- radius_put_vendor_attr() - Attaches a vendor specific binary attribute

# radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches an IP address attribute

### Description

radius_put_addr(
resource `$radius_handle`,
int `$type`,
string `$addr`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`type`

  The attribute type.

`addr`
  An IPv4 address in string form, such as `10.0.0.1`.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

# radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches a binary attribute

### Description

radius_put_attr(
resource `$radius_handle`,
int `$type`,
string `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`type`

  The attribute type.

`value`
  The attribute value, which will be treated as a raw binary string.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### Examples

Example #1 radius_put_attr() example

`<?php
mt_srand(time());
$chall = mt_rand();
$chapval = hash('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;
}
?>`

### See Also

- radius_get_attr() - Extracts an attribute
- radius_get_vendor_attr() - Extracts a vendor specific attribute
- radius_put_vendor_attr() - Attaches a vendor specific binary attribute

# radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches an integer attribute

### Description

radius_put_int(
resource `$radius_handle`,
int `$type`,
int `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`type`

  The attribute type.

`value`
  The attribute value.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### Examples

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

### See Also

- radius_put_string() - Attaches a string attribute
- radius_put_vendor_int() - Attaches a vendor specific integer attribute
- radius_put_vendor_string() - Attaches a vendor specific string attribute

# radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches a string attribute

### Description

radius_put_string(
resource `$radius_handle`,
int `$type`,
string `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`type`

  The attribute type.

`value`
  The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### Examples

Example #1 radius_put_string() example

`<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>`

### See Also

- radius_put_int() - Attaches an integer attribute
- radius_put_vendor_int() - Attaches a vendor specific integer attribute
- radius_put_vendor_string() - Attaches a vendor specific string attribute

# radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches a vendor specific IP address attribute

### Description

radius_put_vendor_addr(
resource `$radius_handle`,
int `$vendor`,
int `$type`,
string `$addr`
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`vendor`

  The vendor ID.

`type`

  The attribute type.

`addr`
  An IPv4 address in string form, such as `10.0.0.1`.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

# radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches a vendor specific binary attribute

### Description

radius_put_vendor_attr(
resource `$radius_handle`,
int `$vendor`,
int `$type`,
string `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`vendor`

  The vendor ID.

`type`

  The attribute type.

`value`
  The attribute value, which will be treated as a raw binary string.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### Examples

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

### See Also

- radius_get_vendor_attr() - Extracts a vendor specific attribute

# radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches a vendor specific integer attribute

### Description

radius_put_vendor_int(
resource `$radius_handle`,
int `$vendor`,
int `$type`,
int `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`vendor`

  The vendor ID.

`type`

  The attribute type.

`value`
  The attribute value.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### See Also

- radius_put_vendor_string() - Attaches a vendor specific string attribute

# radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches a vendor specific string attribute

### Description

radius_put_vendor_string(
resource `$radius_handle`,
int `$vendor`,
int `$type`,
string `$value`,
int `$options` = 0,
int `$tag` = ?
): bool

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.

### Parameters

`radius_handle`

  The RADIUS resource.

`vendor`

  The vendor ID.

`type`

  The attribute type.

`value`
  The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.
`options`

  A bitmask of the attribute options. The available options include `RADIUS_OPTION_TAGGED` and `RADIUS_OPTION_SALT`.

`tag`

  The attribute tag. This parameter is ignored unless the `RADIUS_OPTION_TAGGED` option is set.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL radius 1.3.0 | The `options` and `tag` parameters were added.

### See Also

- radius_put_vendor_int() - Attaches a vendor specific integer attribute

# radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticator — Returns the request authenticator

### Description

radius_request_authenticator(resource `$radius_handle`): string

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

Returns the request authenticator as string, or `false` on error.

### See Also

- radius_demangle() - Demangles data

# radius_salt_encrypt_attr

(PECL radius >= 1.3.0)

radius_salt_encrypt_attr — Salt-encrypts a value

### Description

radius_salt_encrypt_attr(resource `$radius_handle`, string `$data`): string|false

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.

### Parameters

`data`
  The data to be salt-encrypted.

### Return Values

Returns the salt-encrypted data or `false` on failure.

### See Also

- radius_put_addr() - Attaches an IP address attribute
- radius_put_attr() - Attaches a binary attribute
- radius_put_int() - Attaches an integer attribute
- radius_put_string() - Attaches a string attribute

# radius_send_request

(PECL radius >= 1.1.0)

radius_send_request — Sends the request and waits for a reply

### Description

radius_send_request(resource `$radius_handle`): int

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.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

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

### See Also

- radius_create_request() - Create accounting or authentication request

# radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secret — Returns the shared secret

### Description

radius_server_secret(resource `$radius_handle`): string

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

Returns the server's shared secret as string, or `false` on error.

# radius_strerror

(PECL radius >= 1.1.0)

radius_strerror — Returns an error message

### Description

radius_strerror(resource `$radius_handle`): string

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

### Parameters

`radius_handle`

  The RADIUS resource.

### Return Values

Returns error messages as string from failed radius functions.

## Table of Contents

- radius_acct_open — Creates a Radius handle for accounting
- radius_add_server — Adds a server
- radius_auth_open — Creates a Radius handle for authentication
- radius_close — Frees all ressources
- radius_config — Causes the library to read the given configuration file
- radius_create_request — Create accounting or authentication request
- radius_cvt_addr — Converts raw data to IP-Address
- radius_cvt_int — Converts raw data to integer
- radius_cvt_string — Converts raw data to string
- radius_demangle — Demangles data
- radius_demangle_mppe_key — Derives mppe-keys from mangled data
- radius_get_attr — Extracts an attribute
- radius_get_tagged_attr_data — Extracts the data from a tagged attribute
- radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
- radius_get_vendor_attr — Extracts a vendor specific attribute
- radius_put_addr — Attaches an IP address attribute
- radius_put_attr — Attaches a binary attribute
- radius_put_int — Attaches an integer attribute
- radius_put_string — Attaches a string attribute
- radius_put_vendor_addr — Attaches a vendor specific IP address attribute
- radius_put_vendor_attr — Attaches a vendor specific binary attribute
- radius_put_vendor_int — Attaches a vendor specific integer attribute
- radius_put_vendor_string — Attaches a vendor specific string attribute
- radius_request_authenticator — Returns the request authenticator
- radius_salt_encrypt_attr — Salt-encrypts a value
- radius_send_request — Sends the request and waits for a reply
- radius_server_secret — Returns the shared secret
- radius_strerror — Returns an error message

- Installing/Configuring
  - Installation
- Predefined Constants
  - RADIUS Options
  - RADIUS Packet Types
  - RADIUS Attribute Types
  - RADIUS Vendor Specific Attribute Types
- Examples
- Radius Functions
  - radius_acct_open — Creates a Radius handle for accounting
  - radius_add_server — Adds a server
  - radius_auth_open — Creates a Radius handle for authentication
  - radius_close — Frees all ressources
  - radius_config — Causes the library to read the given configuration file
  - radius_create_request — Create accounting or authentication request
  - radius_cvt_addr — Converts raw data to IP-Address
  - radius_cvt_int — Converts raw data to integer
  - radius_cvt_string — Converts raw data to string
  - radius_demangle — Demangles data
  - radius_demangle_mppe_key — Derives mppe-keys from mangled data
  - radius_get_attr — Extracts an attribute
  - radius_get_tagged_attr_data — Extracts the data from a tagged attribute
  - radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
  - radius_get_vendor_attr — Extracts a vendor specific attribute
  - radius_put_addr — Attaches an IP address attribute
  - radius_put_attr — Attaches a binary attribute
  - radius_put_int — Attaches an integer attribute
  - radius_put_string — Attaches a string attribute
  - radius_put_vendor_addr — Attaches a vendor specific IP address attribute
  - radius_put_vendor_attr — Attaches a vendor specific binary attribute
  - radius_put_vendor_int — Attaches a vendor specific integer attribute
  - radius_put_vendor_string — Attaches a vendor specific string attribute
  - radius_request_authenticator — Returns the request authenticator
  - radius_salt_encrypt_attr — Salt-encrypts a value
  - radius_send_request — Sends the request and waits for a reply
  - radius_server_secret — Returns the shared secret
  - radius_strerror — Returns an error message

- Radius
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Radius Functions

# Command Line Specific Extensions

# GNU Readline

# Introduction

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.

As of PHP 7.1.0 this extension is supported on Windows.

Caution

The readline extension is not thread-safe! Thus, the usage of it with any true thread safe SAPI (like Apache mod_winnt) is strongly discouraged.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at » https://tiswww.case.edu/php/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/.

## Installation

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

On Windows this extension is available by default as of PHP 7.1.0.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Readline Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
cli.pager | "" | `INI_ALL` |
cli.prompt | "\\b \\> " | `INI_ALL` |

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.

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

`READLINE_LIB` (string)
  The library which is used for readline support; currently either `readline` or `libedit`.

# Readline Functions

# readline

(PHP 4, PHP 5, PHP 7, PHP 8)

readline — Reads a line

### Description

readline(?string `$prompt` = `null`): string|false

Reads a single line from the user. You must add this line to the history yourself using readline_add_history().

### Parameters

`prompt`
  You may specify a string with which to prompt the user.

### Return Values

Returns a single string from the user. The line returned has the ending newline removed. If there is no more data to read, then `false` is returned.

### Examples

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());
?>`

# readline_add_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_add_history — Adds a line to the history

### Description

readline_add_history(string `$prompt`): true

This function adds a line to the command line history.

### Parameters

`prompt`
  The line to be added in the history.

### Return Values

Always returns `true`.

# readline_callback_handler_install

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately

### Description

readline_callback_handler_install(string `$prompt`, callable `$callback`): true

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

### Parameters

`prompt`
  The prompt message.
`callback`
  The `callback` function takes one parameter; the user input returned.

### Return Values

Always returns `true`.

### Examples

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";
?>`

### See Also

- readline_callback_handler_remove() - Removes a previously installed callback handler and restores terminal settings
- readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received
- stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

# readline_callback_handler_remove

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings

### Description

readline_callback_handler_remove(): bool

Removes a previously installed callback handler and restores terminal settings.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if a previously installed callback handler was removed, or `false` if one could not be found.

### Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

### See Also

- readline_callback_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
- readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received

# readline_callback_read_char

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received

### Description

readline_callback_read_char(): void

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.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

### See Also

- readline_callback_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
- readline_callback_handler_remove() - Removes a previously installed callback handler and restores terminal settings

# readline_clear_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_clear_history — Clears the history

### Description

readline_clear_history(): true

This function clears the entire command line history.

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

# readline_completion_function

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_completion_function — Registers a completion function

### Description

readline_completion_function(callable `$callback`): bool

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.

### Parameters

`callback`
  You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.

### Return Values

Returns `true` on success or `false` on failure.

# readline_info

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_info — Gets/sets various internal readline variables

### Description

readline_info(?string `$var_name` = `null`, int|string|bool|null `$value` = `null`): mixed

Gets or sets various internal readline variables.

### Parameters

`var_name`
  A variable name.
`value`
  If provided, this will be the new value of the setting.

### Return Values

If called with no parameters, this function returns an array of values for all the settings 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`. The array will only contain those elements which are supported by the library used to built the readline extension.

If called with one or two parameters, the old value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `var_name` and `value` are nullable now.

# readline_list_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_list_history — Lists the history

### Description

readline_list_history(): array

Gets the entire command line history.

### Parameters

This function has no parameters.

### Return Values

Returns an array of the entire command line history. The elements are indexed by integers starting at zero.

# readline_on_new_line

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_on_new_line — Inform readline that the cursor has moved to a new line

### Description

readline_on_new_line(): void

Tells readline that the cursor has moved to a new line.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Notes

> Note: This function is only available if supported by the underlying readline library. It is not supported on Windows.

# readline_read_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_read_history — Reads the history

### Description

readline_read_history(?string `$filename` = `null`): bool

This function reads a command history from a file.

### Parameters

`filename`
  Path to the filename containing the command history.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `filename` is nullable now.

# readline_redisplay

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_redisplay — Redraws the display

### Description

readline_redisplay(): void

Redraws readline to redraw the display.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# readline_write_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_write_history — Writes the history

### Description

readline_write_history(?string `$filename` = `null`): bool

This function writes the command history to a file.

### Parameters

`filename`
  Path to the saved file.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `filename` is nullable now.

## Table of Contents

- readline — Reads a line
- readline_add_history — Adds a line to the history
- readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
- readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
- readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
- readline_clear_history — Clears the history
- readline_completion_function — Registers a completion function
- readline_info — Gets/sets various internal readline variables
- readline_list_history — Lists the history
- readline_on_new_line — Inform readline that the cursor has moved to a new line
- readline_read_history — Reads the history
- readline_redisplay — Redraws the display
- readline_write_history — Writes the history

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Readline Functions
  - readline — Reads a line
  - readline_add_history — Adds a line to the history
  - readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  - readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
  - readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
  - readline_clear_history — Clears the history
  - readline_completion_function — Registers a completion function
  - readline_info — Gets/sets various internal readline variables
  - readline_list_history — Lists the history
  - readline_on_new_line — Inform readline that the cursor has moved to a new line
  - readline_read_history — Reads the history
  - readline_redisplay — Redraws the display
  - readline_write_history — Writes the history

- Readline — GNU Readline
  - Installing/Configuring
  - Predefined Constants
  - Readline Functions

# Compression and Archive Extensions

# Bzip2

# Introduction

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

This module uses the functions of the » bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.

## Installation

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.

## Resource Types

This extension defines one resource type: a file pointer identifying the bz2-file to work on.

# Examples

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

# Bzip2 Functions

# bzclose

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzclose — Close a bzip2 file

### Description

bzclose(resource `$bz`): bool

Closes the given bzip2 file pointer.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- bzopen() - Opens a bzip2 compressed file

# bzcompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzcompress — Compress a string into bzip2 encoded data

### Description

bzcompress(string `$data`, int `$block_size` = 4, int `$work_factor` = 0): string|int

bzcompress() compresses the given string and returns it as bzip2 encoded data.

### Parameters

`data`
  The string to compress.
`block_size`
  Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.
`work_factor`
  Controls 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 `work_factor`, the generated output is the same.

### Return Values

The compressed string, or an error number if an error occurred.

### Examples

Example #1 Compressing data

`<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>`

### See Also

- bzdecompress() - Decompresses bzip2 encoded data

# bzdecompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzdecompress — Decompresses bzip2 encoded data

### Description

bzdecompress(string `$data`, bool `$use_less_memory` = `false`): string|int|false

bzdecompress() decompresses the given string containing bzip2 encoded data.

### Parameters

`data`
  The string to decompress.
`use_less_memory`
  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.

### Return Values

The decompressed string, or `false` or an error number if an error occurred.

### Changelog

Version | Description
--- | ---
8.0.0 | The type of `use_less_memory` has been changed from int to bool. Previously, the default value was `0`.

### Examples

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";
?>`

### See Also

- bzcompress() - Compress a string into bzip2 encoded data

# bzerrno

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerrno — Returns a bzip2 error number

### Description

bzerrno(resource `$bz`): int

Returns the error number of any bzip2 error returned by the given file pointer.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().

### Return Values

Returns the error number as an integer.

### See Also

- bzerror() - Returns the bzip2 error number and error string in an array
- bzerrstr() - Returns a bzip2 error string

# bzerror

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerror — Returns the bzip2 error number and error string in an array

### Description

bzerror(resource `$bz`): array

Returns the error number and error string of any bzip2 error returned by the given file pointer.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().

### Return Values

Returns an associative array, with the error code in the `errno` entry, and the error message in the `errstr` entry.

### Examples

Example #1 bzerror() example

`<?php
$error = bzerror($bz);
echo $error["errno"];
echo $error["errstr"];
?>`

### See Also

- bzerrno() - Returns a bzip2 error number
- bzerrstr() - Returns a bzip2 error string

# bzerrstr

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerrstr — Returns a bzip2 error string

### Description

bzerrstr(resource `$bz`): string

Gets the error string of any bzip2 error returned by the given file pointer.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().

### Return Values

Returns a string containing the error message.

### See Also

- bzerrno() - Returns a bzip2 error number
- bzerror() - Returns the bzip2 error number and error string in an array

# bzflush

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzflush — Do nothing

### Description

bzflush(resource `$bz`): bool

This function is supposed to force a write of all buffered bzip2 data for the file pointer `bz`, but is implemented as null function in libbz2, and as such does nothing.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- bzread() - Binary safe bzip2 file read
- bzwrite() - Binary safe bzip2 file write

# bzopen

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzopen — Opens a bzip2 compressed file

### Description

bzopen(string|resource `$file`, string `$mode`): resource|false

bzopen() opens a bzip2 (.bz2) file for reading or writing.

### Parameters

`file`
  The name of the file to open, or an existing stream resource.
`mode`
  The modes `'r'` (read), and `'w'` (write) are supported. Everything else will cause bzopen() to return `false`.

### Return Values

If the open fails, bzopen() returns `false`, otherwise it returns a pointer to the newly opened file.

### Examples

Example #1 bzopen() example

`<?php
$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");
bzclose($bz);
?>`

### See Also

- bzclose() - Close a bzip2 file

# bzread

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzread — Binary safe bzip2 file read

### Description

bzread(resource `$bz`, int `$length` = 1024): string|false

bzread() reads from the given bzip2 file pointer.

Reading stops when `length` (uncompressed) bytes have been read or EOF is reached, whichever comes first.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().
`length`
  If not specified, bzread() will read 1024 (uncompressed) bytes at a time. A maximum of 8192 uncompressed bytes will be read at a time.

### Return Values

Returns the uncompressed data, or `false` on error.

### Examples

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

### See Also

- bzwrite() - Binary safe bzip2 file write
- feof() - Tests for end-of-file on a file pointer
- bzopen() - Opens a bzip2 compressed file

# bzwrite

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzwrite — Binary safe bzip2 file write

### Description

bzwrite(resource `$bz`, string `$data`, ?int `$length` = `null`): int|false

bzwrite() writes a string into the given bzip2 file stream.

### Parameters

`bz`
  The file pointer. It must be valid and must point to a file successfully opened by bzopen().
`data`
  The 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.

### Return Values

Returns the number of bytes written, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` is nullable now.

### Examples

Example #1 bzwrite() example

`<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>`

### See Also

- bzread() - Binary safe bzip2 file read
- bzopen() - Opens a bzip2 compressed file

## Table of Contents

- bzclose — Close a bzip2 file
- bzcompress — Compress a string into bzip2 encoded data
- bzdecompress — Decompresses bzip2 encoded data
- bzerrno — Returns a bzip2 error number
- bzerror — Returns the bzip2 error number and error string in an array
- bzerrstr — Returns a bzip2 error string
- bzflush — Do nothing
- bzopen — Opens a bzip2 compressed file
- bzread — Binary safe bzip2 file read
- bzwrite — Binary safe bzip2 file write

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Examples
- Bzip2 Functions
  - bzclose — Close a bzip2 file
  - bzcompress — Compress a string into bzip2 encoded data
  - bzdecompress — Decompresses bzip2 encoded data
  - bzerrno — Returns a bzip2 error number
  - bzerror — Returns the bzip2 error number and error string in an array
  - bzerrstr — Returns a bzip2 error string
  - bzflush — Do nothing
  - bzopen — Opens a bzip2 compressed file
  - bzread — Binary safe bzip2 file read
  - bzwrite — Binary safe bzip2 file write

# LZF

# Introduction

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.

# Installing/Configuring

## Table of Contents

- Installation

## Installation

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: » https://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.

# LZF Functions

# lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress — LZF compression

### Description

lzf_compress(string `$data`): string

lzf_compress() compresses the given `data` string using LZF encoding.

### Parameters

`data`
  The string to compress.

### Return Values

Returns the compressed data or `false` if an error occurred.

### See Also

- lzf_decompress() - LZF decompression

# lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress — LZF decompression

### Description

lzf_decompress(string `$data`): string

lzf_compress() decompresses the given `data` string containing lzf encoded data.

### Parameters

`data`
  The compressed string.

### Return Values

Returns the decompressed data or `false` if an error occurred.

### See Also

- lzf_compress() - LZF compression

# lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

### Description

lzf_optimized_for(): int

Determines what was LZF extension optimized for during compilation.

### Parameters

This function has no parameters.

### Return Values

Returns 1 if LZF was optimized for speed, 0 for compression.

## Table of Contents

- lzf_compress — LZF compression
- lzf_decompress — LZF decompression
- lzf_optimized_for — Determines what LZF extension was optimized for

- Installing/Configuring
  - Installation
- LZF Functions
  - lzf_compress — LZF compression
  - lzf_decompress — LZF decompression
  - lzf_optimized_for — Determines what LZF extension was optimized for

# Phar

# Introduction

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

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

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.

If zend.multibyte is enabled, zend.detect_unicode must be enabled as well.

## Installation

The Phar extension is bundled with PHP, and enabled by default. To disable Phar support, use --disable-phar.

Phar may be installed via the PECL extension with previous PHP versions, and the » Phar PECL page contains further information and history.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
phar.readonly | "1" | `INI_ALL` |
phar.require_hash | "1" | `INI_ALL` |
phar.cache_list | "" | `INI_SYSTEM` |

Here's a short explanation of the configuration directives.

`phar.readonly` bool

  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` bool

  This option will force all opened Phar archives to contain some kind of signature (currently MD5, SHA1, SHA256, SHA512 and OpenSSL 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. 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.

  Caution

  `phar.require_hash` does not provide any security per se, it is merely a measure against running accidentially corrupted Phar archives, because anyone who would be able to tamper with the Phar could easily fix the signature afterwards.

`phar.cache_list` string

  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 #1 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

## Resource Types

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.

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

Phar compression constants
Constant | Value | Description
--- | --- | ---
`Phar::NONE` (int) | 0x00000000 | no compression
`Phar::COMPRESSED` (int) | 0x0000F000 | bitmask that can be used with file flags to determine if any compression is present
`Phar::GZ` (int) | 0x00001000 | zlib (gzip) compression
`Phar::BZ2` (int) | 0x00002000 | bzip2 compression

Phar file format constants
Constant | Value | Description
--- | --- | ---
`Phar::PHAR` (int) | 1 | phar file format
`Phar::TAR` (int) | 2 | tar file format
`Phar::ZIP` (int) | 3 | zip file format

Phar signature constants
Constant | Value | Description
--- | --- | ---
`Phar::MD5` (int) | 0x0001 | signature with md5 hash algorithm
`Phar::SHA1` (int) | 0x0002 | signature with sha1 hash algorithm
`Phar::SHA256` (int) | 0x0003 | signature with sha256 hash algorithm (requires hash extension)
`Phar::SHA512` (int) | 0x0004 | signature with sha512 hash algorithm (requires hash extension)
`Phar::OPENSSL` (int) | 0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
`Phar::OPENSSL_SHA256` (int) |  |
`Phar::OPENSSL_SHA512` (int) |  |

Phar webPhar mime override constants
Constant | Value | Description
--- | --- | ---
`Phar::PHP` (int) | 0 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
`Phar::PHPS` (int) | 1 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file()

# Using Phar Archives

## Table of Contents

- Using Phar Archives: Introduction
- Using Phar Archives: the phar stream wrapper
- Using Phar Archives: the Phar and PharData class

## Using Phar Archives: Introduction

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 RecursiveDirectoryIterator('/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. 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);
?>`
must be saved adjacent to the phar archive it verifies. If the phar archive is saved as `/path/to/my.phar`, the public key must be saved as `/path/to/my.phar.pubkey`, or phar will be unable to verify the OpenSSL signature.

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();
?>`

## Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and 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.

## Using Phar Archives: the Phar and PharData class

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:

- `$a = $p['file.php']` creates a PharFileInfo class that refers to the contents of `phar://myphar.phar/file.php`
- `$p['file.php'] = $v` creates a new file (`phar://myphar.phar/file.php`), or overwrites an existing file within `myphar.phar`. `$v` can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file. Note that `$p->addFromString('file.php', $v)` is functionally equivalent to the above. Also possible is to add the contents of a file with `$p->addFile('/path/to/file.php', 'file.php')`. Lastly, an empty directory can be created with `$p->addEmptyDir('empty')`.
- `isset($p['file.php'])` can be used to determine whether `phar://myphar.phar/file.php` exists within `myphar.phar`.
- `unset($p['file.php'])` erases `phar://myphar.phar/file.php` from `myphar.phar`.

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.

# Creating Phar Archives

## Table of Contents

- Creating Phar Archives: Introduction

## Creating Phar Archives: Introduction

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

# What makes a phar a phar and not a tar or a zip?

## Table of Contents

- Ingredients of all Phar archives, independent of file format
- Phar file stub
- Head-to-head comparison of Phar, Tar and Zip
- Tar-based phars
- Zip-based phars
- Phar File Format
- Global Phar bitmapped flags
- Phar manifest file entry definition
- Phar Signature format

## Ingredients of all Phar archives, independent of file format

All Phar archives contain three to four sections:

1. a stub

2. a manifest describing the contents

3. the file contents

4. [optional] a signature for verifying Phar integrity (phar file format only)

## Phar file stub

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

    ?>

may be included or omitted, but there can be no more than 1 space between the `;` and the close tag `

    ?>

` or the phar extension will be unable to process the Phar archive's manifest.

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.

## Head-to-head comparison of Phar, Tar and Zip

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 matrix: Phar vs. Tar vs. Zip
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
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

Tip

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

Tip

[2] All write access requires `phar.readonly` to be disabled in php.ini or on the command-line directly.

Tip

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

## Tar-based phars

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.

There is limited support for reading tarballs in pax interchange format, but all recognized pax headers (currently, typeflag `x` and `g`) are silently ignored. There is also limited support for GNU Tar Archives; currently, `././@LongLink` headers are resolved.

To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().

## Zip-based phars

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 DEFLATE 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/`

## Phar File Format

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:

Global Phar manifest format
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

## Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Bitmap values recognized
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 DEFLATE compression
`0x00002000` | If set, this Phar contains at least 1 file that is compressed with bzip2 compression

## Phar manifest file entry definition

Each file in the manifest contains the following information:

Phar Manifest file entry
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:

Bitmap values recognized
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 DEFLATE compression
`0x00002000` | If set, this file is compressed with bzip2 compression

## Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The signature formats supported at this time are MD5, SHA1, SHA256, SHA512, and OPENSSL.

Signature format
Length in bytes | Description
--- | ---
varying | 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. The length of an OPENSSL signature depends on the size of the private key.
4 bytes | Signature flags. `0x0001` is used to define an MD5 signature, `0x0002` is used to define an SHA1 signature, `0x0003` is used to define an SHA256 signature, and `0x0004` is used to define an SHA512 signature. The SHA256 and SHA512 signature support is available as of API version 1.1.0. `0x0010` is used to define an OPENSSL signature, what is available as of API version 1.1.1, if OpenSSL is available.
4 bytes | Magic `GBMB` used to define the presence of a signature.

# The Phar class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

## Introduction

The Phar class provides a high-level interface to accessing and creating phar archives.

## Class synopsis

class Phar extends RecursiveDirectoryIterator implements Countable, ArrayAccess {
/* Inherited constants */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* Constants */
const int BZ2;
const int GZ;
const int NONE;
const int PHAR;
const int TAR;
const int ZIP;
const int COMPRESSED;
const int PHP;
const int PHPS;
const int MD5;
const int OPENSSL;
const int OPENSSL_SHA256;
const int OPENSSL_SHA512;
const int SHA1;
const int SHA256;
const int SHA512;
/* Methods */
public __construct(string `$filename`, int `$flags` = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS, ?string `$alias` = `null`)
public addEmptyDir(string `$directory`): void
public addFile(string `$filename`, ?string `$localName` = `null`): void
public addFromString(string `$localName`, string `$contents`): void
final public static apiVersion(): string
public buildFromDirectory(string `$directory`, string `$pattern` = ""): array
public buildFromIterator(Traversable `$iterator`, ?string `$baseDirectory` = `null`): array
final public static canCompress(int `$compression` = 0): bool
final public static canWrite(): bool
public compress(int `$compression`, ?string `$extension` = `null`): ?Phar
public compressFiles(int `$compression`): void
public convertToData(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?PharData
public convertToExecutable(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?Phar
public copy(string `$from`, string `$to`): true
public count(int `$mode` = `COUNT_NORMAL`): int
final public static createDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): string
public decompress(?string `$extension` = `null`): ?Phar
public decompressFiles(): true
public delMetadata(): true
public delete(string `$localName`): true
public extractTo(string `$directory`, array|string|null `$files` = `null`, bool `$overwrite` = `false`): bool
public getAlias(): ?string
public getMetadata(array `$unserializeOptions` = []): mixed
public getModified(): bool
public getPath(): string
public getSignature(): array|false
public getStub(): string
final public static getSupportedCompression(): array
final public static getSupportedSignatures(): array
public getVersion(): string
public hasMetadata(): bool
final public static interceptFileFuncs(): void
public isBuffering(): bool
public isCompressed(): int|false
public isFileFormat(int `$format`): bool
final public static isValidPharFilename(string `$filename`, bool `$executable` = `true`): bool
public isWritable(): bool
final public static loadPhar(string `$filename`, ?string `$alias` = `null`): bool
final public static mapPhar(?string `$alias` = `null`, int `$offset` = 0): bool
final public static mount(string `$pharPath`, string `$externalPath`): void
final public static mungServer(array `$variables`): void
public offsetExists(string `$localName`): bool
public offsetGet(string `$localName`): SplFileInfo
public offsetSet(string `$localName`, resource|string `$value`): void
public offsetUnset(string `$localName`): void
final public static running(bool `$returnPhar` = `true`): string
public setAlias(string `$alias`): true
public setDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): true
public setMetadata(mixed `$metadata`): void
public setSignatureAlgorithm(int `$algo`, ?string `$privateKey` = `null`): void
public setStub(resource|string `$stub`, int `$length` = -1): bool
public startBuffering(): void
public stopBuffering(): void
final public static unlinkArchive(string `$filename`): true
final public static webPhar(
?string `$alias` = `null`,
?string `$index` = `null`,
?string `$fileNotFoundScript` = `null`,
array `$mimeTypes` = [],
?callable `$rewrite` = `null`
): void
public __destruct()
/* Inherited methods */
public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator
public RecursiveDirectoryIterator::getSubPath(): string
public RecursiveDirectoryIterator::getSubPathname(): string
public RecursiveDirectoryIterator::hasChildren(bool `$allowLinks` = `false`): bool
public RecursiveDirectoryIterator::key(): string
public RecursiveDirectoryIterator::next(): void
public RecursiveDirectoryIterator::rewind(): void
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int `$flags`): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string `$suffix` = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int `$offset`): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string `$suffix` = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string `$class` = `null`): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string `$class` = `null`): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string `$mode` = "r", bool `$useIncludePath` = `false`, ?resource `$context` = `null`): SplFileObject
public SplFileInfo::setFileClass(string `$class` = `SplFileObject::class`): void
public SplFileInfo::setInfoClass(string `$class` = `SplFileInfo::class`): void
public SplFileInfo::__toString(): string
}

## Changelog

Version | Description
--- | ---
8.4.0 | Added support for the Unix timestamp extension for Zip-based archives.
8.0.0 | Meta-data is no longer deserialized upon opening the archive, but is deferred until Phar::getMetadata() is called.

## Notes

Caution

Prior to PHP 8.0.0, the meta-data was deserialized upon opening the archive. This could lead to security vulnerabilities. Starting with PHP 8.0.0, meta-data is only deserialized when calling Phar::getMetadata(), which has options to restrict deserialization for security reasons.

# Phar::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addEmptyDir — Add an empty directory to the phar archive

### Description

public Phar::addEmptyDir(string `$directory`): void

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

### Parameters

`directory`

  The name of the empty directory to create in the phar archive

### Return Values

no return value, exception is thrown on failure.

### Examples

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

### See Also

- PharData::addEmptyDir() - Add an empty directory to the tar/zip archive
- Phar::addFile() - Add a file from the filesystem to the phar archive
- Phar::addFromString() - Add a file from a string to the phar archive

# Phar::addFile

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addFile — Add a file from the filesystem to the phar archive

### Description

public Phar::addFile(string `$filename`, ?string `$localName` = `null`): void

> 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 a string, 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().

### Parameters

`filename`

  Full or relative path to a file on disk to be added to the phar archive.

`localName`

  Path that the file will be stored in the archive.

### Return Values

no return value, exception is thrown on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `localName` is now nullable.

### Examples

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

### Notes

> Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

### See Also

- Phar::offsetSet() - Set the contents of an internal file to those of an external file
- PharData::addFile() - Add a file from the filesystem to the tar/zip archive
- Phar::addFromString() - Add a file from a string to the phar archive
- Phar::addEmptyDir() - Add an empty directory to the phar archive

# Phar::addFromString

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addFromString — Add a file from a string to the phar archive

### Description

public Phar::addFromString(string `$localName`, string `$contents`): void

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

### Parameters

`localName`

  Path that the file will be stored in the archive.

`contents`

  The file contents to store

### Return Values

no return value, exception is thrown on failure.

### Examples

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

### Notes

> Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

### See Also

- Phar::offsetSet() - Set the contents of an internal file to those of an external file
- PharData::addFromString() - Add a file from a string to the tar/zip archive
- Phar::addFile() - Add a file from the filesystem to the phar archive
- Phar::addEmptyDir() - Add an empty directory to the phar archive

# Phar::apiVersion

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

### Description

final public static Phar::apiVersion(): string

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.

### Parameters

### Return Values

The API version string as in `"1.0.0"`.

### Examples

Example #1 A Phar::apiVersion() example

`<?php
echo Phar::apiVersion();
?>`

The above example will output:

    1.1.1

# Phar::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory

### Description

public Phar::buildFromDirectory(string `$directory`, string `$pattern` = ""): array

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

### Parameters

`directory`

  The full or relative path to the directory that contains all files to add to the archive.

`pattern`

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

### Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

### Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

### Changelog

Version | Description
--- | ---
8.1.0 | Phar::buildFromDirectory() no longer returns `false`.

### Examples

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'));
?>`

### See Also

- Phar::buildFromIterator() - Construct a phar archive from an iterator

# Phar::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator

### Description

public Phar::buildFromIterator(Traversable `$iterator`, ?string `$baseDirectory` = `null`): array

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

### Parameters

`iterator`

  Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

`baseDirectory`

  For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

### Return Values

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

### Errors/Exceptions

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 `baseDirectory` parameter, or a PharException if there were errors saving the phar archive.

### Changelog

Version | Description
--- | ---
8.1.0 | Phar::buildFromIterator() no longer returns `false`.
8.0.0 | `baseDirectory` is now nullable.

### Examples

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'));
?>`

### See Also

- Phar::buildFromDirectory() - Construct a phar archive from the files within a directory

# Phar::canCompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2

### Description

final public static Phar::canCompress(int `$compression` = 0): bool

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

### Parameters

`compression`

  Either `Phar::GZ` or `Phar::BZ2` can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

### Return Values

`true` if compression/decompression is available, `false` if not.

### Examples

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

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
- Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

# Phar::canWrite

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

### Description

final public static Phar::canWrite(): bool

This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

### Parameters

### Return Values

`true` if write access is enabled, `false` if it is disabled.

### Examples

Example #1 A Phar::canWrite() example

`<?php
if (Phar::canWrite()) {
file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>`

### See Also

- phar.readonly
- Phar::isWritable() - Returns true if the phar archive can be modified

# Phar::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression

### Description

public Phar::compress(int `$compression`, ?string `$extension` = `null`): ?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.

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.

### Parameters

`compression`

  Compression must be one of `Phar::GZ`, `Phar::BZ2` to add compression, or `Phar::NONE` to remove compression.

`extension`

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

### Return Values

Returns a Phar object, or `null` on failure.

### Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

### Changelog

Version | Description
--- | ---
8.0.0 | `extension` is now nullable.

### Examples

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
?>`

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive

# Phar::compressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses all files in the current Phar archive

### Description

public Phar::compressFiles(int `$compression`): void

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

### Parameters

`compression`

  Compression must be one of `Phar::GZ`, `Phar::BZ2` to add compression, or `Phar::NONE` to remove compression.

### Return Values

No value is returned.

### Errors/Exceptions

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.

### Examples

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)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive

# Phar::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

### Description

public Phar::__construct(string `$filename`, int `$flags` = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS, ?string `$alias` = `null`)

### Parameters

`filename`

  Path to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.

`flags`

  Flags to pass to parent class RecursiveDirectoryIterator.

`alias`

  Alias with which this Phar archive should be referred to in calls to stream functionality.

### Errors/Exceptions

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

### Examples

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');
?>`

# Phar::convertToData

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::convertToData — Convert a phar archive to a non-executable tar or zip file

### Description

public Phar::convertToData(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?PharData

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.

### Parameters

`format`

  This should be one of `Phar::TAR` or `Phar::ZIP`. If set to `null`, the existing file format will be preserved.

`compression`

  This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.

`extension`

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

### Return Values

The method returns a PharData object on success, or `null` on failure.

### Errors/Exceptions

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.

### Changelog

Version | Description
--- | ---
8.0.0 | `format`, `compression`, and `extension` are now nullable.

### Examples

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

### See Also

- Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
- PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
- PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

# Phar::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format

### Description

public Phar::convertToExecutable(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?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.

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.

### Parameters

`format`

  This should be one of `Phar::PHAR`, `Phar::TAR`, or `Phar::ZIP`. If set to `null`, the existing file format will be preserved.

`compression`

  This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.

`extension`

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

### Return Values

The method returns a Phar object on success, or `null` on failure.

### Errors/Exceptions

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.

### Changelog

Version | Description
--- | ---
8.0.0 | `format`, `compression`, and `extension` are now nullable.

### Examples

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

### See Also

- Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
- PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
- PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

# Phar::copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::copy — Copy a file internal to the phar archive to another new file within the phar

### Description

public Phar::copy(string `$from`, string `$to`): true

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

### Parameters

`from`

`to`

### Return Values

Always returns `true`.

### Errors/Exceptions

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.

### Examples

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 "phar://myphar.phar/b"
} catch (Exception $e) {
// Handle error
}
// The stream wrapper equivalent of the above code.
// E_WARNING 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"
?>`

# Phar::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

### Description

public Phar::count(int `$mode` = `COUNT_NORMAL`): int

### Parameters

`mode`

  `mode` is an integer value specifying the counting mode to be used. By default, it is set to `COUNT_NORMAL`, which counts only the number of items in the archive that have not been deleted or hidden. When set to `COUNT_RECURSIVE`, it counts all items in the archive, including those that have been deleted or hidden.

### Return Values

The number of files contained within this phar, or `0` (the number zero) if none.

### Examples

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

# Phar::createDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::createDefaultStub — Create a phar-file format specific stub

### Description

final public static Phar::createDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): string

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';
?>`
or by simple execution:

    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.

### Parameters

`index`

  Relative path within the phar archive to run if accessed on the command-line

`webIndex`

  Relative path within the phar archive to run if accessed through a web browser

### Return Values

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.

### Errors/Exceptions

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

### Changelog

Version | Description
--- | ---
8.0.0 | `index` and `webIndex` are now nullable.

### Examples

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

### See Also

- Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
- Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive

# Phar::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

### Description

public Phar::decompress(?string `$extension` = `null`): ?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.

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.

### Parameters

`extension`

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

### Return Values

A Phar object is returned on success, and `null` on failure.

### Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

### Changelog

Version | Description
--- | ---
8.0.0 | `extension` is now nullable.

### Examples

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
?>`

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive

# Phar::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

### Description

public Phar::decompressFiles(): true

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

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Errors/Exceptions

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.

### Examples

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)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive

# Phar::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

### Description

public Phar::delMetadata(): true

> 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

### Parameters

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

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

### See Also

- Phar::getMetadata() - Returns phar archive meta-data
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::hasMetadata() - Returns whether phar has global meta-data

# Phar::delete

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::delete — Delete a file within a phar archive

### Description

public Phar::delete(string `$localName`): true

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

### Parameters

`localName`

  Path within an archive to the file to delete.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

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

### See Also

- PharData::delete() - Delete a file within a tar/zip archive
- Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory

# Phar::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::__destruct — Destructs a Phar archive object

### Description

public Phar::__destruct()

### Parameters

This function has no parameters.

# Phar::extractTo

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::extractTo — Extract the contents of a phar archive to a directory

### Description

public Phar::extractTo(string `$directory`, array|string|null `$files` = `null`, bool `$overwrite` = `false`): bool

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

### Parameters

`directory`

  Path to extract the given `files` to

`files`

  The name of a file or directory to extract, or an array of files/directories to extract, `null` to skip this param

`overwrite`

  Set to `true` to enable overwriting existing files

### Return Values

returns `true` on success, but it is better to check for thrown exception, and assume success if none is thrown.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

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

### Notes

> Note:

> Windows NTFS file systems do not support some characters in filenames, namely `<|>*?":`. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

### See Also

- PharData::extractTo() - Extract the contents of a tar/zip archive to a directory

# Phar::getAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1)

Phar::getAlias — Get the alias for Phar

### Description

public Phar::getAlias(): ?string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns the alias or `null` if there's no alias.

# Phar::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getMetadata — Returns phar archive meta-data

### Description

public Phar::getMetadata(array `$unserializeOptions` = []): mixed

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Caution

Accessing the meta-data will trigger deserialization, which can trigger the execution of arbitrary PHP code. Do not use this on untrusted phar archives, or configure the `unserializeOptions` in a secure manner.

### Parameters

No parameters.

### Return Values

Any PHP value that can be serialized and is stored as meta-data for the Phar archive, or `null` if no meta-data is stored.

### Changelog

Version | Description
--- | ---
8.0.0 | The parameter `unserializeOptions` has been added.

### Examples

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

### See Also

- Phar::setMetadata() - Sets phar archive meta-data
- Phar::delMetadata() - Deletes the global metadata of the phar
- Phar::hasMetadata() - Returns whether phar has global meta-data

# Phar::getModified

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

### Description

public Phar::getModified(): bool

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.

### Parameters

No parameters.

### Return Values

`true` if the phar has been modified since opened, `false` if not.

# Phar::getPath

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Phar::getPath — Get the real path to the Phar archive on disk

### Description

public Phar::getPath(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# Phar::getSignature

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

### Description

public Phar::getSignature(): array|false

Returns the verification signature of a phar archive in a hexadecimal string.

### Parameters

### Return Values

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. If there is no signature, the function returns `false`.

# Phar::getStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive

### Description

public Phar::getStub(): string

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';
?>`
or by simple execution:

    php myphar.phar

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

### Errors/Exceptions

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

### Examples

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

### See Also

- Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
- Phar::createDefaultStub() - Create a phar-file format specific stub

# Phar::getSupportedCompression

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

### Description

final public static Phar::getSupportedCompression(): array

### Parameters

No parameters.

### Return Values

Returns an array containing any of `Phar::GZ` or `Phar::BZ2`, depending on the availability of the zlib extension or the bz2 extension.

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive

# Phar::getSupportedSignatures

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

### Description

final public static Phar::getSupportedSignatures(): array

Return array of supported signature types

### Parameters

No parameters.

### Return Values

Returns an array containing any of `MD5`, `SHA-1`, `SHA-256`, `SHA-512`, or `OpenSSL`.

### See Also

- Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
- Phar::setSignatureAlgorithm() - Set the signature algorithm for a phar and apply it

# Phar::getVersion

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

### Description

public Phar::getVersion(): string

Returns the API version of an opened Phar archive.

### Parameters

### Return Values

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.

### See Also

- Phar::apiVersion() - Returns the api version

# Phar::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns whether phar has global meta-data

### Description

public Phar::hasMetadata(): bool

Returns whether phar has global meta-data set.

### Parameters

No parameters.

### Return Values

Returns `true` if meta-data has been set, and `false` if not.

### Examples

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)

### See Also

- Phar::getMetadata() - Returns phar archive meta-data
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::delMetadata() - Deletes the global metadata of the phar

# Phar::interceptFileFuncs

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

### Description

final public static Phar::interceptFileFuncs(): void

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.

### Parameters

No parameters.

### Return Values

### Examples

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.

# Phar::isBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

### Description

public Phar::isBuffering(): bool

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.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the write operations are being buffer, `false` otherwise.

### Examples

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)

### See Also

- Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
- Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk

# Phar::isCompressed

(PHP 5 >= 5.3.0, PHP 7, PHP 8, 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)

### Description

public Phar::isCompressed(): int|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.

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.

### Parameters

No parameters.

### Return Values

`Phar::GZ`, `Phar::BZ2` or `false`.

### Examples

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->compress(Phar::GZ);
var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>`

The above example will output:

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

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms

# Phar::isFileFormat

(PHP 5 >= 5.3.0, PHP 7, PHP 8, 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

### Description

public Phar::isFileFormat(int `$format`): bool

### Parameters

`format`

  Either `Phar::PHAR`, `Phar::TAR`, or `Phar::ZIP` to test for the format of the archive.

### Return Values

Returns `true` if the phar archive matches the file format requested by the parameter

### Errors/Exceptions

PharException is thrown if the parameter is an unknown file format specifier.

### See Also

- Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
- Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

# Phar::isValidPharFilename

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename

### Description

final public static Phar::isValidPharFilename(string `$filename`, bool `$executable` = `true`): bool

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.

### Parameters

`filename`

  The name or full path to a phar archive not yet created

`executable`

  This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

### Return Values

Returns `true` if the filename is valid, `false` if not.

# Phar::isWritable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::isWritable — Returns true if the phar archive can be modified

### Description

public Phar::isWritable(): bool

This method returns `true` if `phar.readonly` is `0`, and the actual phar archive on disk is not read-only.

### Parameters

No parameters.

### Return Values

Returns `true` if the phar archive can be modified

### See Also

- Phar::canWrite() - Returns whether phar extension supports writing and creating phars
- PharData::isWritable() - Returns true if the tar/zip archive can be modified

# Phar::loadPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

### Description

final public static Phar::loadPhar(string `$filename`, ?string `$alias` = `null`): bool

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.

### Parameters

`filename`

  the full or relative path to the phar archive to open

`alias`

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

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

### Examples

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

### See Also

- Phar::mapPhar() - Reads the currently executed file (a phar) and registers its manifest

# Phar::mapPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest

### Description

final public static Phar::mapPhar(?string `$alias` = `null`, int `$offset` = 0): bool

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.

### Parameters

`alias`

  The alias that can be used in `phar://` URLs to refer to this archive, rather than its full path.

`offset`

  Unused variable, here for compatibility with PEAR's PHP_Archive.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

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.

### Examples

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

### See Also

- Phar::loadPhar() - Loads any phar archive with an alias

# Phar::mount

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::mount — Mount an external path or file to a virtual location within the phar archive

### Description

final public static Phar::mount(string `$pharPath`, string `$externalPath`): void

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.

### Parameters

`pharPath`

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

`externalPath`

  A path or URL to an external file or directory to mount within the phar archive

### Return Values

No return. PharException is thrown on failure.

### Errors/Exceptions

Throws PharException if any problems occur mounting the path.

### Examples

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';
?>`

# Phar::mungServer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution

### Description

final public static Phar::mungServer(array `$variables`): void

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

### Parameters

`variables`

  An array of any of the strings `REQUEST_URI`, `PHP_SELF`, `SCRIPT_NAME` and `SCRIPT_FILENAME`. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

### Return Values

No return.

### Errors/Exceptions

Throws UnexpectedValueException if any problems are found with the passed in data.

### Examples

Example #1 A Phar::mungServer() example

`<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>`

### See Also

- Phar::webPhar() - Routes a request from a web browser to an internal file within the phar archive
- Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

# Phar::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetExists — Determines whether a file exists in the phar

### Description

public Phar::offsetExists(string `$localName`): bool

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.

### Parameters

`localName`

  The filename (relative path) to look for in a Phar.

### Return Values

Returns `true` if the file exists within the phar, or `false` if not.

### Examples

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)

### See Also

- Phar::offsetGet() - Gets a PharFileInfo object for a specific file
- Phar::offsetSet() - Set the contents of an internal file to those of an external file
- Phar::offsetUnset() - Remove a file from a phar

# Phar::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

### Description

public Phar::offsetGet(string `$localName`): SplFileInfo

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.

### Parameters

`localName`

  The filename (relative path) to look for in a Phar.

### Return Values

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

### Errors/Exceptions

This method throws BadMethodCallException if the file does not exist in the Phar archive.

### Examples

Example #1 Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet() is automatically called when using the `[]` angle bracket operator.

`<?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
// automatically calls offsetGet()
echo $p['exists.txt'];
echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
echo $e;
}
?>`

The above example will output:

    file exists
    Entry doesnotexist.txt does not exist

### See Also

- Phar::offsetExists() - Determines whether a file exists in the phar
- Phar::offsetSet() - Set the contents of an internal file to those of an external file
- Phar::offsetUnset() - Remove a file from a phar

# Phar::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetSet — Set the contents of an internal file to those of an external file

### Description

public Phar::offsetSet(string `$localName`, resource|string `$value`): void

> 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 is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

### Parameters

`localName`

  The filename (relative path) to modify in a Phar.

`value`

  Content of the file.

### Return Values

No return values.

### Errors/Exceptions

if phar.readonly is `1`, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to `0`. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

### Examples

Example #1 A Phar::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the `[]` operator.

`<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
// calls offsetSet
$p['file.txt'] = 'Hi there';
} catch (Exception $e) {
echo 'Could not modify file.txt:', $e;
}
?>`

### Notes

> Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

### See Also

- Phar::offsetExists() - Determines whether a file exists in the phar
- Phar::offsetGet() - Gets a PharFileInfo object for a specific file
- Phar::offsetUnset() - Remove a file from a phar

# Phar::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetUnset — Remove a file from a phar

### Description

public Phar::offsetUnset(string `$localName`): void

> 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 is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

### Parameters

`localName`

  The filename (relative path) to modify in a Phar.

### Return Values

No value is returned.

### Errors/Exceptions

if phar.readonly is `1`, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to `0`. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

### Examples

Example #1 A Phar::offsetUnset() example

`<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
// deletes file.txt from my.phar by calling offsetUnset
unset($p['file.txt']);
} catch (Exception $e) {
echo 'Could not delete file.txt: ', $e;
}
?>`

### See Also

- Phar::offsetExists() - Determines whether a file exists in the phar
- Phar::offsetGet() - Gets a PharFileInfo object for a specific file
- Phar::offsetSet() - Set the contents of an internal file to those of an external file
- Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory
- Phar::delete() - Delete a file within a phar archive

# Phar::running

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive

### Description

final public static Phar::running(bool `$returnPhar` = `true`): string

Returns the full path to the running phar archive. This is intended for use much like the `__FILE__` magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running() returns `""`. Simply use `__FILE__` to access the current running phar inside a stub.

### Parameters

`returnPhar`

  If `false`, the full path on disk to the phar archive is returned. If `true`, a full phar URL is returned.

### Return Values

Returns the filename if valid, empty string otherwise.

### Examples

Example #1 A Phar::running() example

For the following example, assume the phar archive is located at `/path/to/phar/my.phar`.

`<?php
$a = Phar::running(); // $a is "phar:///path/to/my.phar"
$b = Phar::running(false); // $b is "/path/to/my.phar"
?>`

# Phar::setAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

### Description

public Phar::setAlias(string `$alias`): true

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

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the `phar` stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include or to use Phar::interceptFileFuncs() and use relative paths.

### Parameters

`alias`

  A shorthand string that this archive can be referred to in `phar` stream wrapper access.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

### Changelog

Version | Description
--- | ---
8.4.0 | Phar::setAlias() now has a tentative return of true.

### Examples

Example #1 A Phar::setAlias() example

`<?php
try {
$phar = new Phar('myphar.phar');
$phar->setAlias('myp.phar');
} catch (Exception $e) {
// handle error
}
?>`

### See Also

- Phar::__construct() - Construct a Phar archive object
- Phar::interceptFileFuncs() - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

# Phar::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

### Description

public Phar::setDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): true

> 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 a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

### Parameters

`index`

  Relative path within the phar archive to run if accessed on the command-line

`webIndex`

  Relative path within the phar archive to run if accessed through a web browser

### Return Values

Always returns `true`.

### Errors/Exceptions

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

### Changelog

Version | Description
--- | ---
8.4.0 | Phar::setDefaultStub() now has a tentative return of true.
8.0.0 | `webIndex` is nullable now.

### Examples

Example #1 A Phar::setDefaultStub() example

`<?php
try {
$phar = new Phar('myphar.phar');
$phar->setDefaultStub('cli.php', 'web/index.php');
// this is the same as:
// $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>`

### See Also

- Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
- Phar::createDefaultStub() - Create a phar-file format specific stub

# Phar::setMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

### Description

public Phar::setMetadata(mixed `$metadata`): void

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

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

### Parameters

`metadata`

  Any PHP variable containing information to store that describes the phar archive

### Return Values

No value is returned.

### Examples

Example #1 A Phar::setMetadata() 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 create and/or modify phar:', $e;
}
?>`

The above example will output:

    array(1) {
      ["bootstrap"]=>
      string(8) "file.php"
    }

### See Also

- Phar::getMetadata() - Returns phar archive meta-data
- Phar::delMetadata() - Deletes the global metadata of the phar
- Phar::hasMetadata() - Returns whether phar has global meta-data

# Phar::setSignatureAlgorithm

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

### Description

public Phar::setSignatureAlgorithm(int `$algo`, ?string `$privateKey` = `null`): void

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

set the signature algorithm for a phar and apply it. The signature algorithm must be one of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL`.

Note that all executable phar archives have a signature created automatically, `SHA1` by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm().

### Parameters

`algo`

  One of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL`

`privateKey`

  The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

  `<?php
  $private = openssl_get_privatekey(file_get_contents('private.pem'));
  $pkey = '';
  openssl_pkey_export($private, $pkey);
  $p->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
  ?>`
  See phar introduction for instructions on naming and placement of the public key file.

### Return Values

No value is returned.

### Errors/Exceptions

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

### Changelog

Version | Description
--- | ---
8.0.0 | `privateKey` is now nullable.

### See Also

- Phar::getSupportedSignatures() - Return array of supported signature types
- Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

# Phar::setStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive

### Description

public Phar::setStub(resource|string `$stub`, int `$length` = -1): bool

> 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 add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

`<?php
include 'myphar.phar';
?>`

The loader is not accessed when including a file through the `phar` stream wrapper like so:

`<?php
include 'phar://myphar.phar/somefile.php';
?>`

### Parameters

`stub`

  A string or an open stream handle to use as the executable stub for this phar archive.

`length`

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

### Changelog

Version | Description
--- | ---
8.3.0 | Calling Phar::setStub() with a resource and a `length` is now deprecated. Such calls should be replaced by: `$phar->setStub(stream_get_contents($resource));`

### Examples

Example #1 A Phar::setStub() example

`<?php
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['a.php'] = '<?php var_dump("Hello");';
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = '<?php var_dump("World");';
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
} catch (Exception $e) {
echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>`

The above example will output:

    string(5) "Hello"
    string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
    string(5) "World"
    string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

### See Also

- Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
- Phar::createDefaultStub() - Create a phar-file format specific stub

# Phar::startBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk

### Description

public Phar::startBuffering(): void

Although technically unnecessary, the Phar::startBuffering() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the `foo.phar` Phar archive does not affect changes to the `bar.phar` Phar archive.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Examples

Example #1 A Phar::startBuffering() 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->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub("<?php
function __autoload($class)
{
include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
?>`

### See Also

- Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk
- Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

# Phar::stopBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk

### Description

public Phar::stopBuffering(): void

Phar::stopBuffering() is used in conjunction with the Phar::startBuffering() method. Phar::startBuffering() can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the `foo.phar` Phar archive does not affect changes to the `bar.phar` Phar archive.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

PharException is thrown if any problems are encountered flushing changes to disk.

### Examples

Example #1 A Phar::stopBuffering() example

`<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
var_dump($p->getStub());
?>`

The above example will output:

    string(24) "<?php __HALT_COMPILER();"
    string(195) "<?php
    function __autoload($class)
    {
        include 'phar://' . str_replace('_', '/', $class);
    }
    Phar::mapPhar('brandnewphar.phar');
    include 'phar://brandnewphar.phar/startup.php';
    __HALT_COMPILER();"

### See Also

- Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
- Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

# Phar::unlinkArchive

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

### Description

final public static Phar::unlinkArchive(string `$filename`): true

Removes a phar archive from disk and memory.

### Parameters

`filename`

  The path on disk to the phar archive.

### Return Values

Always returns `true`.

### Errors/Exceptions

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

### Examples

Example #1 A Phar::unlinkArchive() example

`<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');
// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>`

### See Also

- Phar::delete() - Delete a file within a phar archive
- Phar::offsetUnset() - Remove a file from a phar

# Phar::webPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive

### Description

final public static Phar::webPhar(
?string `$alias` = `null`,
?string `$index` = `null`,
?string `$fileNotFoundScript` = `null`,
array `$mimeTypes` = [],
?callable `$rewrite` = `null`
): void

Phar::webPhar() serves as Phar::mapPhar() for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. It simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web application can be used unmodified from a phar archive.

Phar::webPhar() should only be called from the stub of a phar archive (see here for more information on what a stub is).

### Parameters

`alias`

  The alias that can be used in `phar://` URLs to refer to this archive, rather than its full path.

`index`

  The location within the phar of the directory index.

`fileNotFoundScript`

  The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

`mimeTypes`

  An array mapping additional file extensions to MIME type. If the default mapping is sufficient, pass an empty array. By default, these extensions are mapped to these MIME types:

  `<?php
  $mimes = array(
  'phps' => Phar::PHPS, // pass to highlight_file()
  'c' => 'text/plain',
  'cc' => 'text/plain',
  'cpp' => 'text/plain',
  'c++' => 'text/plain',
  'dtd' => 'text/plain',
  'h' => 'text/plain',
  'log' => 'text/plain',
  'rng' => 'text/plain',
  'txt' => 'text/plain',
  'xsd' => 'text/plain',
  'php' => Phar::PHP, // parse as PHP
  'inc' => Phar::PHP, // parse as PHP
  'avi' => 'video/avi',
  'bmp' => 'image/bmp',
  'css' => 'text/css',
  'gif' => 'image/gif',
  'htm' => 'text/html',
  'html' => 'text/html',
  'htmls' => 'text/html',
  'ico' => 'image/x-ico',
  'jpe' => 'image/jpeg',
  'jpg' => 'image/jpeg',
  'jpeg' => 'image/jpeg',
  'js' => 'application/x-javascript',
  'midi' => 'audio/midi',
  'mid' => 'audio/midi',
  'mod' => 'audio/mod',
  'mov' => 'movie/quicktime',
  'mp3' => 'audio/mp3',
  'mpg' => 'video/mpeg',
  'mpeg' => 'video/mpeg',
  'pdf' => 'application/pdf',
  'png' => 'image/png',
  'swf' => 'application/shockwave-flash',
  'tif' => 'image/tiff',
  'tiff' => 'image/tiff',
  'wav' => 'audio/wav',
  'xbm' => 'image/xbm',
  'xml' => 'text/xml',
  );
  ?>`
`rewrite`

  The rewrites function is passed a string as its only parameter and must return a string or `false`.

  If you are using fast-cgi or cgi then the parameter passed to the function is the value of the $_SERVER['PATH_INFO'] variable. Otherwise, the parameter passed to the function is the value of the $_SERVER['REQUEST_URI'] variable.

  If a string is returned it is used as the internal file path. If `false` is returned then webPhar() will send a HTTP 403 Denied Code.

### Return Values

No value is returned.

### Errors/Exceptions

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into `mimeTypes` or an invalid callback is passed into `rewrite`, then UnexpectedValueException is thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | `fileNotFoundScript` and `rewrite` are nullable now.

### Examples

Example #1 A Phar::webPhar() example

With the example below, the created phar will display `Hello World` if one browses to `/myphar.phar/index.php` or to `/myphar.phar`, and will display the source of `index.phps` if one browses to `/myphar.phar/index.phps`.

`<?php
// creating the phar archive:
try {
$phar = new Phar('myphar.phar');
$phar['index.php'] = '<?php echo "Hello World"; ?>';
$phar['index.phps'] = '<?php echo "Hello World"; ?>';
$phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>');
} catch (Exception $e) {
// handle error here
}
?>`

### See Also

- Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that should be modified for execution
- Phar::interceptFileFuncs() - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

## Table of Contents

- Phar::addEmptyDir — Add an empty directory to the phar archive
- Phar::addFile — Add a file from the filesystem to the phar archive
- Phar::addFromString — Add a file from a string to the phar archive
- Phar::apiVersion — Returns the api version
- Phar::buildFromDirectory — Construct a phar archive from the files within a directory
- Phar::buildFromIterator — Construct a phar archive from an iterator
- Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
- Phar::canWrite — Returns whether phar extension supports writing and creating phars
- Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::compressFiles — Compresses all files in the current Phar archive
- Phar::__construct — Construct a Phar archive object
- Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
- Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
- Phar::copy — Copy a file internal to the phar archive to another new file within the phar
- Phar::count — Returns the number of entries (files) in the Phar archive
- Phar::createDefaultStub — Create a phar-file format specific stub
- Phar::decompress — Decompresses the entire Phar archive
- Phar::decompressFiles — Decompresses all files in the current Phar archive
- Phar::delMetadata — Deletes the global metadata of the phar
- Phar::delete — Delete a file within a phar archive
- Phar::__destruct — Destructs a Phar archive object
- Phar::extractTo — Extract the contents of a phar archive to a directory
- Phar::getAlias — Get the alias for Phar
- Phar::getMetadata — Returns phar archive meta-data
- Phar::getModified — Return whether phar was modified
- Phar::getPath — Get the real path to the Phar archive on disk
- Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
- Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
- Phar::getSupportedCompression — Return array of supported compression algorithms
- Phar::getSupportedSignatures — Return array of supported signature types
- Phar::getVersion — Return version info of Phar archive
- Phar::hasMetadata — Returns whether phar has global meta-data
- Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
- Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
- Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
- Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
- Phar::isWritable — Returns true if the phar archive can be modified
- Phar::loadPhar — Loads any phar archive with an alias
- Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
- Phar::mount — Mount an external path or file to a virtual location within the phar archive
- Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
- Phar::offsetExists — Determines whether a file exists in the phar
- Phar::offsetGet — Gets a PharFileInfo object for a specific file
- Phar::offsetSet — Set the contents of an internal file to those of an external file
- Phar::offsetUnset — Remove a file from a phar
- Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
- Phar::setAlias — Set the alias for the Phar archive
- Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
- Phar::setMetadata — Sets phar archive meta-data
- Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
- Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
- Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
- Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
- Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
- Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive

# The PharData class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

## Introduction

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if `phar.readonly` php.ini setting is `1`.

## Class synopsis

class PharData extends RecursiveDirectoryIterator implements Countable, ArrayAccess {
/* Inherited constants */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* Methods */
public __construct(
string `$filename`,
int `$flags` = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS,
?string `$alias` = `null`,
int `$format` = 0
)
public addEmptyDir(string `$directory`): void
public addFile(string `$filename`, ?string `$localName` = `null`): void
public addFromString(string `$localName`, string `$contents`): void
public buildFromDirectory(string `$directory`, string `$pattern` = ""): array
public buildFromIterator(Traversable `$iterator`, ?string `$baseDirectory` = `null`): array
public compress(int `$compression`, ?string `$extension` = `null`): ?PharData
public compressFiles(int `$compression`): void
public convertToData(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?PharData
public convertToExecutable(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?Phar
public copy(string `$from`, string `$to`): true
public decompress(?string `$extension` = `null`): ?PharData
public decompressFiles(): true
public delMetadata(): true
public delete(string `$localName`): true
public extractTo(string `$directory`, array|string|null `$files` = `null`, bool `$overwrite` = `false`): bool
public isWritable(): bool
public offsetSet(string `$localName`, resource|string `$value`): void
public offsetUnset(string `$localName`): void
public setAlias(string `$alias`): bool
public setDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): bool
public setMetadata(mixed `$metadata`): void
public setSignatureAlgorithm(int `$algo`, ?string `$privateKey` = `null`): void
public setStub(string `$stub`, int `$len` = -1): bool
public __destruct()
/* Inherited methods */
public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator
public RecursiveDirectoryIterator::getSubPath(): string
public RecursiveDirectoryIterator::getSubPathname(): string
public RecursiveDirectoryIterator::hasChildren(bool `$allowLinks` = `false`): bool
public RecursiveDirectoryIterator::key(): string
public RecursiveDirectoryIterator::next(): void
public RecursiveDirectoryIterator::rewind(): void
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int `$flags`): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string `$suffix` = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int `$offset`): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string `$suffix` = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string `$class` = `null`): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string `$class` = `null`): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string `$mode` = "r", bool `$useIncludePath` = `false`, ?resource `$context` = `null`): SplFileObject
public SplFileInfo::setFileClass(string `$class` = `SplFileObject::class`): void
public SplFileInfo::setInfoClass(string `$class` = `SplFileInfo::class`): void
public SplFileInfo::__toString(): string
}

# PharData::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add an empty directory to the tar/zip archive

### Description

public PharData::addEmptyDir(string `$directory`): void

With this method, an empty directory is created with path `dirname`. This method is similar to ZipArchive::addEmptyDir().

### Parameters

`directory`

  The name of the empty directory to create in the phar archive

### Return Values

no return value, exception is thrown on failure.

### Examples

Example #1 A PharData::addEmptyDir() example

`<?php
try {
$a = new PharData('/path/to/my.tar');
$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
}
?>`

### See Also

- Phar::addEmptyDir() - Add an empty directory to the phar archive
- PharData::addFile() - Add a file from the filesystem to the tar/zip archive
- PharData::addFromString() - Add a file from a string to the tar/zip archive

# PharData::addFile

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addFile — Add a file from the filesystem to the tar/zip archive

### Description

public PharData::addFile(string `$filename`, ?string `$localName` = `null`): void

With this method, any file or URL can be added to the tar/zip 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().

### Parameters

`filename`

  Full or relative path to a file on disk to be added to the phar archive.

`localName`

  Path that the file will be stored in the archive.

### Return Values

no return value, exception is thrown on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `localName` is now nullable.

### Examples

Example #1 A PharData::addFile() example

`<?php
try {
$a = new PharData('/path/to/my.tar');
$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
}
?>`

### Notes

> Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

### See Also

- PharData::offsetSet() - Set the contents of a file within the tar/zip to those of an external file or string
- Phar::addFile() - Add a file from the filesystem to the phar archive
- PharData::addFromString() - Add a file from a string to the tar/zip archive
- PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

# PharData::addFromString

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addFromString — Add a file from a string to the tar/zip archive

### Description

public PharData::addFromString(string `$localName`, string `$contents`): void

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with `localname` as its path. This method is similar to ZipArchive::addFromString().

### Parameters

`localName`

  Path that the file will be stored in the archive.

`contents`

  The file contents to store

### Return Values

no return value, exception is thrown on failure.

### Examples

Example #1 A PharData::addFromString() example

`<?php
try {
$a = new PharData('/path/to/my.tar');
$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
}
?>`

### Notes

> Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

### See Also

- PharData::offsetSet() - Set the contents of a file within the tar/zip to those of an external file or string
- Phar::addFromString() - Add a file from a string to the phar archive
- PharData::addFile() - Add a file from the filesystem to the tar/zip archive
- PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

# PharData::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory

### Description

public PharData::buildFromDirectory(string `$directory`, string `$pattern` = ""): array

Populate a tar/zip 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 PharData::buildFromIterator().

### Parameters

`directory`

  The full or relative path to the directory that contains all files to add to the archive.

`pattern`

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

### Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem, or `false` on failure.

### Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

### Changelog

Version | Description
--- | ---
8.1.0 | PharData::buildFromDirectory() no longer returns `false`.

### Examples

Example #1 A PharData::buildFromDirectory() example

`<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>`

### See Also

- Phar::buildFromDirectory() - Construct a phar archive from the files within a directory
- PharData::buildFromIterator() - Construct a tar or zip archive from an iterator

# PharData::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct a tar or zip archive from an iterator

### Description

public PharData::buildFromIterator(Traversable `$iterator`, ?string `$baseDirectory` = `null`): array

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip 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.

### Parameters

`iterator`

  Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

`baseDirectory`

  For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

### Return Values

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

### Errors/Exceptions

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 `baseDirectory` parameter, or a PharException if there were errors saving the phar archive.

### Changelog

Version | Description
--- | ---
8.1.0 | PharData::buildFromIterator() no longer returns `false`.
8.0.0 | `baseDirectory` is now nullable.

### Examples

Example #1 A PharData::buildFromIterator() with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip 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.tar" tar archive:

`<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
?>`

The file `project.tar` can then be used immediately. PharData::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator() can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

`<?php
$phar = new PharData('project.tar');
$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 PharData::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
$phar = new PharData('project.tar');
$phar->buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
?>`

### See Also

- Phar::buildFromIterator() - Construct a phar archive from an iterator

# PharData::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression

### Description

public PharData::compress(int `$compression`, ?string `$extension` = `null`): ?PharData

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

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.

### Parameters

`compression`

  Compression must be one of `Phar::GZ`, `Phar::BZ2` to add compression, or `Phar::NONE` to remove compression.

`extension`

  By default, the extension is `.tar.gz` or `.tar.bz2` for compressing a tar, and `.tar` for decompressing.

### Return Values

A PharData object is returned on success, or `null` on failure.

### Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

### Changelog

Version | Description
--- | ---
8.0.0 | `extension` is now nullable.

### Examples

Example #1 A PharData::compress() example

`<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.tar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.tar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.tar already exists
?>`

### See Also

- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression

# PharData::compressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses all files in the current tar/zip archive

### Description

public PharData::compressFiles(int `$compression`): void

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the 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.

### Parameters

`compression`

  Compression must be one of `Phar::GZ`, `Phar::BZ2` to add compression, or `Phar::NONE` to remove compression.

### Return Values

No value is returned.

### Errors/Exceptions

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.

### Examples

Example #1 A PharData::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)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- PharData::decompressFiles() - Decompresses all files in the current zip archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- PharData::decompress() - Decompresses the entire Phar archive

# PharData::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::__construct — Construct a non-executable tar or zip archive object

### Description

public PharData::__construct(
string `$filename`,
int `$flags` = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS,
?string `$alias` = `null`,
int `$format` = 0
)

### Parameters

`filename`

  Path to an existing tar/zip archive or to-be-created archive

`flags`

  Flags to pass to Phar parent class RecursiveDirectoryIterator.

`alias`

  Alias with which this Phar archive should be referred to in calls to stream functionality.

`format`

  One of the file format constants available within the Phar class.

### Errors/Exceptions

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

### Examples

Example #1 A PharData::__construct() example

`<?php
try {
$p = new PharData('/path/to/my.tar', Phar::CURRENT_AS_FILEINFO | Phar::KEY_AS_FILENAME);
} catch (UnexpectedValueException $e) {
die('Could not open my.tar');
} catch (BadMethodCallException $e) {
echo 'technically, this cannot happen';
}
echo file_get_contents('phar:///path/to/my.tar/example.txt');
?>`

# PharData::convertToData

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::convertToData — Convert a phar archive to a non-executable tar or zip file

### Description

public PharData::convertToData(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?PharData

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress() method for logical consistency.

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.

### Parameters

`format`

  This should be one of `Phar::TAR` or `Phar::ZIP`. If set to `null`, the existing file format will be preserved.

`compression`

  This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.

`extension`

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

### Return Values

The method returns a PharData object on success, or `null` on failure.

### Errors/Exceptions

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.

### Changelog

Version | Description
--- | ---
8.0.0 | `format`, `compression`, and `extension` are now nullable.

### Examples

Example #1 A PharData::convertToData() example

Using PharData::convertToData():

`<?php
try {
$tarphar = new PharData('myphar.tar');
// note that myphar.tar is *not* unlinked
// convert it to the non-executable tar file format
// creates myphar.zip
$zip = $tarphar->convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>`

### See Also

- Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
- Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
- PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive

# PharData::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive

### Description

public PharData::convertToExecutable(?int `$format` = `null`, ?int `$compression` = `null`, ?string `$extension` = `null`): ?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.

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

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.

### Parameters

`format`

  This should be one of `Phar::PHAR`, `Phar::TAR`, or `Phar::ZIP`. If set to `null`, the existing file format will be preserved.

`compression`

  This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.

`extension`

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

### Return Values

The method returns a Phar object on success, or `null` on failure.

### Errors/Exceptions

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.

### Changelog

Version | Description
--- | ---
8.0.0 | `format`, `compression`, and `localName` are now nullable.

### Examples

Example #1 A PharData::convertToExecutable() example

Using PharData::convertToExecutable():

`<?php
try {
$tarphar = new PharData('myphar.tar');
// convert it to the phar file format
// note that myphar.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 = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>`

### See Also

- Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
- Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
- PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

# PharData::copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::copy — Copy a file internal to the tar/zip archive to another new file within the same archive

### Description

public PharData::copy(string `$from`, string `$to`): true

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy() with the phar stream wrapper.

### Parameters

`from`

`to`

### Return Values

Always returns `true`.

### Errors/Exceptions

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.

### Examples

Example #1 A PharData::copy() example

This example shows using PharData::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error().

`<?php
try {
$phar = new PharData('myphar.tar');
$phar['a'] = 'hi';
$phar->copy('a', 'b');
echo $phar['b']; // Outputs "phar://myphar.tar/b"
} catch (Exception $e) {
// Handle error
}
// The stream wrapper equivalent of the above code.
// E_WARNING are triggered on error rather than exceptions
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // Outputs "hi"
?>`

# PharData::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::decompress — Decompresses the entire Phar archive

### Description

public PharData::decompress(?string `$extension` = `null`): ?PharData

For tar-based archives, this method decompresses the entire archive.

For Zip-based 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.

In addition, this method automatically renames the file extension of the archive, `.tar` by default. Alternatively, a file extension may be specified with the `extension` parameter.

### Parameters

`extension`

  For decompressing, the default file extension is `.tar`. Use this parameter to specify another file extension. Be aware that only executable archives can contain `.phar` in their filename.

### Return Values

A PharData object is returned on success, or `null` on failure.

### Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

### Changelog

Version | Description
--- | ---
8.0.0 | `extension` is now nullable.

### Examples

Example #1 A PharData::decompress() example

`<?php
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar
?>`

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- PharData::compressFiles() - Compresses all files in the current tar/zip archive
- PharData::decompressFiles() - Decompresses all files in the current zip archive

# PharData::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses all files in the current zip archive

### Description

public PharData::decompressFiles(): true

> 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 archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

### Examples

Example #1 A PharData::decompressFiles() example

`<?php
$p = new PharData('/path/to/my.zip');
$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)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- PharData::compressFiles() - Compresses all files in the current tar/zip archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- PharData::decompress() - Decompresses the entire Phar archive

# PharData::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes the global metadata of a zip archive

### Description

public PharData::delMetadata(): true

> 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 zip archive

### Parameters

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

Example #1 A PharData::delMetaData() example

`<?php
try {
$phar = new PharData('myphar.zip');
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

### See Also

- Phar::delMetadata() - Deletes the global metadata of the phar

# PharData::delete

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::delete — Delete a file within a tar/zip archive

### Description

public PharData::delete(string `$localName`): true

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.

### Parameters

`localName`

  Path within an archive to the file to delete.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

Example #1 A PharData::delete() example

`<?php
try {
$phar = new PharData('myphar.zip');
$phar->delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>`

### See Also

- Phar::delete() - Delete a file within a phar archive

# PharData::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::__destruct — Destructs a non-executable tar or zip archive object

### Description

public PharData::__destruct()

### Parameters

This function has no parameters.

# PharData::extractTo

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::extractTo — Extract the contents of a tar/zip archive to a directory

### Description

public PharData::extractTo(string `$directory`, array|string|null `$files` = `null`, bool `$overwrite` = `false`): bool

Extract all files within a tar/zip 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().

### Parameters

`directory`

  Path to extract the given `files` to

`files`

  The 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

### Return Values

returns `true` on success, but it is better to check for thrown exception, and assume success if none is thrown.

### Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

### Examples

Example #1 A PharData::extractTo() example

`<?php
try {
$phar = new PharData('myphar.tar');
$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
}
?>`

### Notes

> Note:

> Windows NTFS file systems do not support some characters in filenames, namely `<|>*?":`. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

### See Also

- Phar::extractTo() - Extract the contents of a phar archive to a directory

# PharData::isWritable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::isWritable — Returns true if the tar/zip archive can be modified

### Description

public PharData::isWritable(): bool

This method returns `true` if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable(), data-only tar/zip archives can be modified even if `phar.readonly` is set to `1`.

### Parameters

No parameters.

### Return Values

Returns `true` if the tar/zip archive can be modified

### See Also

- Phar::canWrite() - Returns whether phar extension supports writing and creating phars
- Phar::isWritable() - Returns true if the phar archive can be modified

# PharData::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string

### Description

public PharData::offsetSet(string `$localName`, resource|string `$value`): void

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

### Parameters

`localName`

  The filename (relative path) to modify in a tar or zip archive.

`value`

  Content of the file.

### Return Values

No return values.

### Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

### Examples

Example #1 A PharData::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the `[]` operator.

`<?php
$p = new PharData('/path/to/my.tar');
try {
// calls offsetSet
$p['file.txt'] = 'Hi there';
} catch (Exception $e) {
echo 'Could not modify file.txt:', $e;
}
?>`

### Notes

> Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

### See Also

- Phar::offsetSet() - Set the contents of an internal file to those of an external file

# PharData::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::offsetUnset — Remove a file from a tar/zip archive

### Description

public PharData::offsetUnset(string `$localName`): void

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

### Parameters

`localName`

  The filename (relative path) to modify in the tar/zip archive.

### Return Values

No value is returned.

### Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

### Examples

Example #1 A PharData::offsetUnset() example

`<?php
$p = new PharData('/path/to/my.zip');
try {
// deletes file.txt from my.zip by calling offsetUnset
unset($p['file.txt']);
} catch (Exception $e) {
echo 'Could not delete file.txt: ', $e;
}
?>`

### See Also

- Phar::offsetUnset() - Remove a file from a phar

# PharData::setAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)

### Description

public PharData::setAlias(string `$alias`): bool

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

### Parameters

`alias`

  A shorthand string that this archive can be referred to in `phar` stream wrapper access. This parameter is ignored.

### Return Values

### Errors/Exceptions

Throws PharException on all method calls

### See Also

- Phar::setAlias() - Set the alias for the Phar archive

# PharData::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)

### Description

public PharData::setDefaultStub(?string `$index` = `null`, ?string `$webIndex` = `null`): bool

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

### Parameters

`index`

  Relative path within the phar archive to run if accessed on the command-line

`webIndex`

  Relative path within the phar archive to run if accessed through a web browser

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws PharException on all method calls

### Changelog

Version | Description
--- | ---
8.0.0 | `webIndex` is nullable now.

### See Also

- Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

# PharData::setMetadata

(No version information available, might only be in Git)

PharData::setMetadata — Sets phar archive meta-data

### Description

public PharData::setMetadata(mixed `$metadata`): void

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

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

### Parameters

`metadata`

  Any PHP variable containing information to store that describes the phar archive

### Return Values

No value is returned.

### Examples

Example #1 A Phar::setMetadata() 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 create and/or modify phar:', $e;
}
?>`

The above example will output:

    array(1) {
      ["bootstrap"]=>
      string(8) "file.php"
    }

### See Also

- Phar::getMetadata() - Returns phar archive meta-data
- Phar::delMetadata() - Deletes the global metadata of the phar
- Phar::hasMetadata() - Returns whether phar has global meta-data

# PharData::setSignatureAlgorithm

(No version information available, might only be in Git)

PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

### Description

public PharData::setSignatureAlgorithm(int `$algo`, ?string `$privateKey` = `null`): void

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

Set the signature algorithm for a phar and apply it. The signature algorithm must be one of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL`.

### Parameters

`algo`

  One of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL`

### Return Values

No value is returned.

### Errors/Exceptions

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

### Changelog

Version | Description
--- | ---
8.0.0 | `privateKey` is now nullable.

### See Also

- Phar::getSupportedSignatures() - Return array of supported signature types
- Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

# PharData::setStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)

### Description

public PharData::setStub(string `$stub`, int `$len` = -1): bool

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

### Parameters

`stub`

  A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

`len`

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws PharException on all method calls

### See Also

- Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

## Table of Contents

- PharData::addEmptyDir — Add an empty directory to the tar/zip archive
- PharData::addFile — Add a file from the filesystem to the tar/zip archive
- PharData::addFromString — Add a file from a string to the tar/zip archive
- PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory
- PharData::buildFromIterator — Construct a tar or zip archive from an iterator
- PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- PharData::compressFiles — Compresses all files in the current tar/zip archive
- PharData::__construct — Construct a non-executable tar or zip archive object
- PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
- PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
- PharData::copy — Copy a file internal to the tar/zip archive to another new file within the same archive
- PharData::decompress — Decompresses the entire Phar archive
- PharData::decompressFiles — Decompresses all files in the current zip archive
- PharData::delMetadata — Deletes the global metadata of a zip archive
- PharData::delete — Delete a file within a tar/zip archive
- PharData::__destruct — Destructs a non-executable tar or zip archive object
- PharData::extractTo — Extract the contents of a tar/zip archive to a directory
- PharData::isWritable — Returns true if the tar/zip archive can be modified
- PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string
- PharData::offsetUnset — Remove a file from a tar/zip archive
- PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)
- PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)
- PharData::setMetadata — Sets phar archive meta-data
- PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
- PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)

# The PharFileInfo class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

## Introduction

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

## Class synopsis

class PharFileInfo extends SplFileInfo {
/* Methods */
public __construct(string `$filename`)
public chmod(int `$perms`): void
public compress(int `$compression`): true
public decompress(): true
public delMetadata(): true
public getCRC32(): int
public getCompressedSize(): int
public getContent(): string
public getMetadata(array `$unserializeOptions` = []): mixed
public getPharFlags(): int
public hasMetadata(): bool
public isCRCChecked(): bool
public isCompressed(?int `$compression` = `null`): bool
public setMetadata(mixed `$metadata`): void
public __destruct()
/* Inherited methods */
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string `$suffix` = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string `$class` = `null`): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string `$class` = `null`): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string `$mode` = "r", bool `$useIncludePath` = `false`, ?resource `$context` = `null`): SplFileObject
public SplFileInfo::setFileClass(string `$class` = `SplFileObject::class`): void
public SplFileInfo::setInfoClass(string `$class` = `SplFileInfo::class`): void
public SplFileInfo::__toString(): string
}

# PharFileInfo::chmod

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

### Description

public PharFileInfo::chmod(int `$perms`): void

PharFileInfo::chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

### Parameters

`perms`

  permissions (see chmod())

### Return Values

No value is returned.

### Examples

Example #1 A PharFileInfo::chmod() example

`<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.sh'] = '#!/usr/local/lib/php
<?php echo "hi"; ?>';
// set executable bit
$p['file.sh']->chmod(0555);
var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>`

The above example will output:

    bool(true)

# PharFileInfo::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression

### Description

public PharFileInfo::compress(int `$compression`): true

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

### Parameters

`compression`

  Compression must be `Phar::GZ` or `Phar::BZ2`.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

### Examples

Example #1 A PharFileInfo::compress() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->isCompressed(Phar::BZ2));
$p['myfile.txt']->compress(Phar::BZ2);
var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
echo 'Create/modify operations on my.phar failed: ', $e;
}
?>`

The above example will output:

    bool(false)
    bool(true)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms

# PharFileInfo::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

### Description

public PharFileInfo::__construct(string `$filename`)

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

### Parameters

`filename`

  The full url to retrieve a file. If you wish to retrieve the information for the file `my/file.php` from the phar `boo.phar`, the entry should be `phar://boo.phar/my/file.php`.

### Errors/Exceptions

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

### Examples

Example #1 A PharFileInfo::__construct() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['testfile.txt'] = "hi\nthere\ndude";
$file = $p['testfile.txt'];
foreach ($file as $line => $text) {
echo "line number $line: $text";
}
// this also works
$file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
foreach ($file as $line => $text) {
echo "line number $line: $text";
}
} catch (Exception $e) {
echo 'Phar operations failed: ', $e;
}
?>`

The above example will output:

    line number 1: hi
    line number 2: there
    line number 3: dude
    line number 1: hi
    line number 2: there
    line number 3: dude

# PharFileInfo::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

### Description

public PharFileInfo::decompress(): true

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

### Examples

Example #1 A PharFileInfo::decompress() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
$file->compress(Phar::GZ);
var_dump($file->isCompressed());
$p['myfile.txt']->decompress();
var_dump($file->isCompressed());
} catch (Exception $e) {
echo 'Create/modify failed for my.phar: ', $e;
}
?>`

The above example will output:

    int(4096)
    bool(false)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compressFiles() - Compresses all files in the current Phar archive
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms

# PharFileInfo::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

### Description

public PharFileInfo::delMetadata(): true

Deletes the metadata of the entry, if any.

### Parameters

No parameters.

### Return Values

Always returns `true`. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

### Errors/Exceptions

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

### Examples

Example #1 A PharFileInfo::delMetaData() example

`<?php
try {
$a = new Phar('myphar.phar');
$a['hi'] = 'hi';
var_dump($a['hi']->delMetadata());
$a['hi']->setMetadata('there');
var_dump($a['hi']->delMetadata());
var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
// handle errors
}
?>`

The above example will output:

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

### See Also

- PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
- PharFileInfo::hasMetadata() - Returns the metadata of the entry
- PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::hasMetadata() - Returns whether phar has global meta-data
- Phar::getMetadata() - Returns phar archive meta-data

# PharFileInfo::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::__destruct — Destructs a Phar entry object

### Description

public PharFileInfo::__destruct()

### Parameters

This function has no parameters.

# PharFileInfo::getCRC32

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified

### Description

public PharFileInfo::getCRC32(): int

This returns the crc32() checksum of the file within the Phar archive.

### Parameters

This function has no parameters.

### Return Values

The crc32() checksum of the file within the Phar archive.

### Errors/Exceptions

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

### Examples

Example #1 A PharFileInfo::getCRC32() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
echo $file->getCRC32();
} catch (Exception $e) {
echo 'Write operations on my.phar.phar failed: ', $e;
}
?>`

The above example will output:

    3633523372

# PharFileInfo::getCompressedSize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive

### Description

public PharFileInfo::getCompressedSize(): int

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize()

### Parameters

This function has no parameters.

### Return Values

The size in bytes of the file within the Phar archive on disk.

### Examples

Example #1 A PharFileInfo::getCompressedSize() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
echo $file->getCompressedSize();
} catch (Exception $e) {
echo 'Write operations failed on my.phar: ', $e;
}
?>`

The above example will output:

    2

### See Also

- PharFileInfo::isCompressed() - Returns whether the entry is compressed
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::compressFiles() - Compresses all files in the current Phar archive

# PharFileInfo::getContent

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

PharFileInfo::getContent — Get the complete file contents of the entry

### Description

public PharFileInfo::getContent(): string

This function behaves like file_get_contents() but for Phar.

### Parameters

This function has no parameters.

### Return Values

Returns the file contents.

# PharFileInfo::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file

### Description

public PharFileInfo::getMetadata(array `$unserializeOptions` = []): mixed

Return meta-data that was saved in the Phar archive's manifest for this file.

### Parameters

### Return Values

any PHP variable that can be serialized and is stored as meta-data for the file, or `null` if no meta-data is stored.

### Changelog

Version | Description
--- | ---
8.0.0 | The parameter `unserializeOptions` has been added.

### Examples

Example #1 A PharFileInfo::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.txt'] = 'hello';
$p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetadata());
} catch (Exception $e) {
echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>`

The above example will output:

    array(2) {
      ["user"]=>
      string(4) "bill"
      ["mime-type"]=>
      string(10) "text/plain"
    }

### See Also

- PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
- PharFileInfo::hasMetadata() - Returns the metadata of the entry
- PharFileInfo::delMetadata() - Deletes the metadata of the entry
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::hasMetadata() - Returns whether phar has global meta-data
- Phar::getMetadata() - Returns phar archive meta-data

# PharFileInfo::getPharFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

### Description

public PharFileInfo::getPharFlags(): int

This returns the flags set in the manifest for a Phar. This will always return `0` in the current implementation.

### Parameters

This function has no parameters.

### Return Values

The Phar flags (always `0` in the current implementation)

### Examples

Example #1 A PharFileInfo::getPharFlags() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->getPharFlags());
} catch (Exception $e) {
echo 'Could not create/modify my.phar: ', $e;
}
?>`

The above example will output:

    int(0)

# PharFileInfo::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

### Description

public PharFileInfo::hasMetadata(): bool

Returns the metadata of a file within a phar archive.

### Parameters

No parameters.

### Return Values

Returns `false` if no metadata is set or is `null`, `true` if metadata is not `null`

### See Also

- PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
- PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
- PharFileInfo::delMetadata() - Deletes the metadata of the entry
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::hasMetadata() - Returns whether phar has global meta-data
- Phar::getMetadata() - Returns phar archive meta-data

# PharFileInfo::isCRCChecked

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

### Description

public PharFileInfo::isCRCChecked(): bool

This returns whether a file within a Phar archive has had its CRC verified.

### Parameters

This function has no parameters.

### Return Values

`true` if the file has had its CRC verified, `false` if not.

### Examples

Example #1 A PharFileInfo::isCRCChecked() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->isCRCChecked());
} catch (Exception $e) {
echo 'Create/modify operations failed on my.phar: ', $e;
}
?>`

The above example will output:

    bool(true)

# PharFileInfo::isCompressed

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

### Description

public PharFileInfo::isCompressed(?int `$compression` = `null`): bool

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

### Parameters

`compression`

  One of `Phar::GZ` or `Phar::BZ2`, defaults to any compression.

### Return Values

`true` if the file is compressed within the Phar archive, `false` if not.

### Changelog

Version | Description
--- | ---
8.0.0 | `compression` is now nullable.

### Examples

Example #1 A PharFileInfo::isCompressed() example

`<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p['myfile2.txt']->setCompressedGZ();
$file = $p['myfile.txt'];
$file2 = $p['myfile2.txt'];
var_dump($file->isCompressed());
var_dump($file2->isCompressed());
} catch (Exception $e) {
echo 'Create/modify on phar my.phar failed: ', $e;
}
?>`

The above example will output:

    bool(false)
    bool(true)

### See Also

- PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
- PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
- Phar::decompress() - Decompresses the entire Phar archive
- Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
- Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::getSupportedCompression() - Return array of supported compression algorithms
- Phar::decompressFiles() - Decompresses all files in the current Phar archive
- Phar::compressFiles() - Compresses all files in the current Phar archive

# PharFileInfo::setMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

### Description

public PharFileInfo::setMetadata(mixed `$metadata`): void

PharFileInfo::setMetadata() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

### Parameters

`metadata`

  Any PHP variable containing information to store alongside a file

### Return Values

No value is returned.

### Examples

Example #1 A PharFileInfo::setMetadata() example

`<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.txt'] = 'hello';
$p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>`

The above example will output:

    array(2) {
      ["user"]=>
      string(4) "bill"
      ["mime-type"]=>
      string(10) "text/plain"
    }

### See Also

- PharFileInfo::hasMetadata() - Returns the metadata of the entry
- PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
- PharFileInfo::delMetadata() - Deletes the metadata of the entry
- Phar::setMetadata() - Sets phar archive meta-data
- Phar::hasMetadata() - Returns whether phar has global meta-data
- Phar::getMetadata() - Returns phar archive meta-data

## Table of Contents

- PharFileInfo::chmod — Sets file-specific permission bits
- PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::__construct — Construct a Phar entry object
- PharFileInfo::decompress — Decompresses the current Phar entry within the phar
- PharFileInfo::delMetadata — Deletes the metadata of the entry
- PharFileInfo::__destruct — Destructs a Phar entry object
- PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
- PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::getContent — Get the complete file contents of the entry
- PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
- PharFileInfo::getPharFlags — Returns the Phar file entry flags
- PharFileInfo::hasMetadata — Returns the metadata of the entry
- PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
- PharFileInfo::isCompressed — Returns whether the entry is compressed
- PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

# The PharException class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

## Introduction

The PharException class provides a phar-specific exception class for try/catch blocks.

## Class synopsis

class PharException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Using Phar Archives
  - Using Phar Archives: Introduction
  - Using Phar Archives: the phar stream wrapper
  - Using Phar Archives: the Phar and PharData class
- Creating Phar Archives
  - Creating Phar Archives: Introduction
- What makes a phar a phar and not a tar or a zip?
  - Ingredients of all Phar archives, independent of file format
  - Phar file stub
  - Head-to-head comparison of Phar, Tar and Zip
  - Tar-based phars
  - Zip-based phars
  - Phar File Format
  - Global Phar bitmapped flags
  - Phar manifest file entry definition
  - Phar Signature format
- Phar — The Phar class
  - Phar::addEmptyDir — Add an empty directory to the phar archive
  - Phar::addFile — Add a file from the filesystem to the phar archive
  - Phar::addFromString — Add a file from a string to the phar archive
  - Phar::apiVersion — Returns the api version
  - Phar::buildFromDirectory — Construct a phar archive from the files within a directory
  - Phar::buildFromIterator — Construct a phar archive from an iterator
  - Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
  - Phar::canWrite — Returns whether phar extension supports writing and creating phars
  - Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
  - Phar::compressFiles — Compresses all files in the current Phar archive
  - Phar::__construct — Construct a Phar archive object
  - Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
  - Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
  - Phar::copy — Copy a file internal to the phar archive to another new file within the phar
  - Phar::count — Returns the number of entries (files) in the Phar archive
  - Phar::createDefaultStub — Create a phar-file format specific stub
  - Phar::decompress — Decompresses the entire Phar archive
  - Phar::decompressFiles — Decompresses all files in the current Phar archive
  - Phar::delMetadata — Deletes the global metadata of the phar
  - Phar::delete — Delete a file within a phar archive
  - Phar::__destruct — Destructs a Phar archive object
  - Phar::extractTo — Extract the contents of a phar archive to a directory
  - Phar::getAlias — Get the alias for Phar
  - Phar::getMetadata — Returns phar archive meta-data
  - Phar::getModified — Return whether phar was modified
  - Phar::getPath — Get the real path to the Phar archive on disk
  - Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  - Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
  - Phar::getSupportedCompression — Return array of supported compression algorithms
  - Phar::getSupportedSignatures — Return array of supported signature types
  - Phar::getVersion — Return version info of Phar archive
  - Phar::hasMetadata — Returns whether phar has global meta-data
  - Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
  - Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
  - Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  - Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
  - Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
  - Phar::isWritable — Returns true if the phar archive can be modified
  - Phar::loadPhar — Loads any phar archive with an alias
  - Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
  - Phar::mount — Mount an external path or file to a virtual location within the phar archive
  - Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
  - Phar::offsetExists — Determines whether a file exists in the phar
  - Phar::offsetGet — Gets a PharFileInfo object for a specific file
  - Phar::offsetSet — Set the contents of an internal file to those of an external file
  - Phar::offsetUnset — Remove a file from a phar
  - Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
  - Phar::setAlias — Set the alias for the Phar archive
  - Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
  - Phar::setMetadata — Sets phar archive meta-data
  - Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
  - Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
  - Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
  - Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
  - Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  - Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive
- PharData — The PharData class
  - PharData::addEmptyDir — Add an empty directory to the tar/zip archive
  - PharData::addFile — Add a file from the filesystem to the tar/zip archive
  - PharData::addFromString — Add a file from a string to the tar/zip archive
  - PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory
  - PharData::buildFromIterator — Construct a tar or zip archive from an iterator
  - PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  - PharData::compressFiles — Compresses all files in the current tar/zip archive
  - PharData::__construct — Construct a non-executable tar or zip archive object
  - PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
  - PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
  - PharData::copy — Copy a file internal to the tar/zip archive to another new file within the same archive
  - PharData::decompress — Decompresses the entire Phar archive
  - PharData::decompressFiles — Decompresses all files in the current zip archive
  - PharData::delMetadata — Deletes the global metadata of a zip archive
  - PharData::delete — Delete a file within a tar/zip archive
  - PharData::__destruct — Destructs a non-executable tar or zip archive object
  - PharData::extractTo — Extract the contents of a tar/zip archive to a directory
  - PharData::isWritable — Returns true if the tar/zip archive can be modified
  - PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string
  - PharData::offsetUnset — Remove a file from a tar/zip archive
  - PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)
  - PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)
  - PharData::setMetadata — Sets phar archive meta-data
  - PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
  - PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)
- PharFileInfo — The PharFileInfo class
  - PharFileInfo::chmod — Sets file-specific permission bits
  - PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
  - PharFileInfo::__construct — Construct a Phar entry object
  - PharFileInfo::decompress — Decompresses the current Phar entry within the phar
  - PharFileInfo::delMetadata — Deletes the metadata of the entry
  - PharFileInfo::__destruct — Destructs a Phar entry object
  - PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
  - PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
  - PharFileInfo::getContent — Get the complete file contents of the entry
  - PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
  - PharFileInfo::getPharFlags — Returns the Phar file entry flags
  - PharFileInfo::hasMetadata — Returns the metadata of the entry
  - PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
  - PharFileInfo::isCompressed — Returns whether the entry is compressed
  - PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
- PharException — The PharException class

# Rar Archiving

# Introduction

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by the UnRar library and is directly prohibited by its license.

More information about Rar and UnRar can be found at » http://www.rarlabs.com/.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

Rar is currently available through PECL » https://pecl.php.net/package/rar.

Also you can use the PECL installer to install the Rar extension, using the following command: pecl -v install rar.

You can always download the tar.gz package and install Rar by hand:

Example #1 Rar installation

    gunzip rar-xxx.tgz
    tar -xvf rar-xxx.tar
    cd rar-xxx
    phpize
    ./configure && make && make install

Windows users will enable php_rar.dll inside of php.ini in order to use these functions.

## Resource Types

This extension registers three internal classes: the archive representations returned by rar_open() – RarArchive, the entry representations returned by rar_list() and rar_entry_get() – RarEntry and the exception type RarException.

This extension also register a stream resource, called "rar" and a URL wrapper called "rar wrapper" and registered under the prefix "rar".

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

`RAR_HOST_MSDOS` (int)
  Use `RarEntry::HOST_MSDOS` instead.
`RAR_HOST_OS2` (int)
  Use `RarEntry::HOST_OS2` instead.
`RAR_HOST_WIN32` (int)
  Use `RarEntry::HOST_WIN32` instead.
`RAR_HOST_UNIX` (int)
  Use `RarEntry::HOST_UNIX` instead.
`RAR_HOST_BEOS` (int)
  Use `RarEntry::HOST_BEOS` instead.

# Examples

See also the examples under `rar://` wrapper.

Example #1 On-the-fly decompression

`<?php
if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
die("Index unspecified or non-numeric");
$index = (int) $_GET["i"];
$arch = RarArchive::open("example.rar");
if ($arch === FALSE)
die("Cannot open example.rar");
$entries = $arch->getEntries();
if ($entries === FALSE)
die("Cannot retrieve entries");
if (!array_key_exists($index, $entries))
die("No such index: $index");
$orfilename = $entries[$index]->getName(); //UTF-8 encoded
$filesize = $entries[$index]->getUnpackedSize();
/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
* $entries[$index]->getFileTime(). You could also send a
* "Last modified" header */
$fp = $entries[$index]->getStream();
if ($fp === FALSE)
die("Cannot open file with index $index insided the archive.");
$arch->close(); //no longer needed; stream is independent
function detectUserAgent() {
if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
return "Other";
$uas = $_SERVER['HTTP_USER_AGENT'];
if (preg_match("@Opera/@", $uas))
return "Opera";
if (preg_match("@Firefox/@", $uas))
return "Firefox";
if (preg_match("@Chrome/@", $uas))
return "Chrome";
if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
if (((float) $matches[1]) >= 7.0)
return "IE";
}
return "Other";
}
/*
* We have 3 options:
* - For FF and Opera, which support RFC 2231, use that format.
* - For IE and Chrome, use attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - For the others, convert to ISO-8859-1, if possible
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';
switch (detectUserAgent()) {
case "Opera":
case "Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;
case "IE":
case "Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (function_exists('iconv'))
$orfilename =
@iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}
header(sprintf($format, $orfilename));
//cannot send error messages from now on (headers already sent)
//replace by real content type, perhaps infering from the file extension
$contentType = "application/octet-stream";
header("Content-Type: $contentType");
header("Content-Transfer-Encoding: binary");
header("Content-Length: $filesize");
if ($_SERVER['REQUEST_METHOD'] == "HEAD")
die();
while (!feof($fp)) {
$s = @fread($fp, 8192);
if ($s === false)
break; //useless to send error messages
echo $s;
}
?>`

This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

Example #2 RAR extension filesystem extraction example

`<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>`

This example opens a RAR file archive and extracts each entry to the specified directory.

# Rar Functions

# rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

### Description

rar_wrapper_cache_stats(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

# The RarArchive class

(PECL rar >= 2.0.0)

## Introduction

This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).

Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through RarArchive::getEntry() and RarArchive::getEntries().

## Class synopsis

final class RarArchive implements Traversable {
/* Methods */
public close(): bool
public getComment(): string
public getEntries(): array|false
public getEntry(string `$entryname`): RarEntry|false
public isBroken(): bool
public isSolid(): bool
public static open(string `$filename`, string `$password` = NULL, callable `$volume_callback` = NULL): RarArchive|false
public setAllowBroken(bool `$allow_broken`): bool
public __toString(): string
}

# RarArchive::close

# rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_close — Close RAR archive and free all resources

### Description

Object-oriented style (method):

public RarArchive::close(): bool

Procedural style:

rar_close(RarArchive `$rarfile`): bool

Close RAR archive and free all allocated resources.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL rar 2.0.0 | The RAR entries returned by RarArchive::getEntry() and RarArchive::getEntries() are now invalidated when calling this method. This means that all instance methods called for such entries and not guaranteed to succeed.

### Examples

Example #1 Object-oriented style

`<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>`

The above example will output something similar to:

    RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
    RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Example #2 Procedural style

`<?php
$rar_arch = rar_open('latest_winrar.rar');
echo $rar_arch."\n";
rar_close($rar_arch);
echo $rar_arch."\n";
?>`

# RarArchive::getComment

# rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_get — Get comment text from the RAR archive

### Description

Object-oriented style (method):

public RarArchive::getComment(): string

Procedural style:

rar_comment_get(RarArchive `$rarfile`): string

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

> Note: This extension does not support comments at the entry level.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().

### Return Values

Returns the comment or `null` if there is none.

> Note: RAR has currently no support for unicode comments. The encoding of the result of this function is not specified, but it will probably be Windows-1252.

### Examples

Example #1 Object-oriented style

`<?php
$rar_arch = RarArchive::open('commented.rar');
echo $rar_arch->getComment();
?>`

The above example will output something similar to:

    This is the comment of the file commented.rar.

Example #2 Procedural style

`<?php
$rar_arch = rar_open('commented.rar');
echo rar_comment_get($rar_arch);
?>`

# RarArchive::getEntries

# rar_list

(PECL rar >= 2.0.0)

RarArchive::getEntries -- rar_list — Get full list of entries from the RAR archive

### Description

Object-oriented style (method):

public RarArchive::getEntries(): array|false

Procedural style:

rar_list(RarArchive `$rarfile`): array|false

Get entries list (files and directories) from the RAR archive.

> Note: If the archive has entries with the same name, this method, together with RarArchive `foreach` iteration and array-like access with numeric indexes, are the only ones to access all the entries (i.e., RarArchive::getEntry() and the `rar://` wrapper are insufficient).

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().

### Return Values

rar_list() returns array of RarEntry objects or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

### Examples

Example #1 Object-oriented style

`<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entries = $rar_arch->getEntries();
if ($rar_entries === FALSE)
die("Could not retrieve entries.");
echo "Found " . count($rar_entries) . " entries.\n";
foreach ($rar_entries as $e) {
echo $e;
echo "\n";
}
$rar_arch->close();
?>`

The above example will output something similar to:

    Found 2 entries.
    RarEntry for file "tese.txt" (23b93a7a)
    RarEntry for file "unrardll.txt" (2ed64b6e)

Example #2 Procedural style

`<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entries = rar_list($rar_arch);
if ($rar_entries === FALSE)
die("Could retrieve entries.");
echo "Found " . count($rar_entries) . " entries.\n";
foreach ($rar_entries as $e) {
echo $e;
echo "\n";
}
rar_close($rar_arch);
?>`

### See Also

- RarArchive::getEntry() - Get entry object from the RAR archive
- `rar://` wrapper

# RarArchive::getEntry

# rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_get — Get entry object from the RAR archive

### Description

Object-oriented style (method):

public RarArchive::getEntry(string `$entryname`): RarEntry|false

Procedural style:

rar_entry_get(RarArchive `$rarfile`, string `$entryname`): RarEntry|false

Get entry object (file or directory) from the RAR archive.

> Note: You can also get entry objects using RarArchive::getEntries(). Note that a RAR archive can have multiple entries with the same name; this method will retrieve only the first.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().
`entryname`
  Path to the entry within the RAR archive.

  > Note: The path must be the same returned by RarEntry::getName().

### Return Values

Returns the matching RarEntry object or `false` on failure.

### Examples

Example #1 Object-oriented style

`<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entry = $rar_arch->getEntry('tese.txt');
if ($rar_entry === FALSE)
die("Could not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>`

The above example will output something similar to:

    RarEntry
    RarEntry for file "tese.txt" (23b93a7a)

Example #2 Procedural style

`<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entry = rar_entry_get($rar_arch, 'tese.txt');
if ($rar_entry === FALSE)
die("Could not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
rar_close($rar_arch);
?>`

### See Also

- RarArchive::getEntries() - Get full list of entries from the RAR archive
- `rar://` wrapper

# RarArchive::isBroken

# rar_broken_is

(PECL rar >= 3.0.0)

RarArchive::isBroken -- rar_broken_is — Test whether an archive is broken (incomplete)

### Description

Object-oriented style (method):

public RarArchive::isBroken(): bool

Procedural style:

rar_broken_is(RarArchive `$rarfile`): bool

This function determines whether an archive is incomplete, i.e., if a volume is missing or a volume is truncated.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().

### Return Values

Returns `true` if the archive is broken, `false` otherwise. This function may also return `false` if the passed file has already been closed. The only way to tell the two cases apart is to enable exceptions with RarException::setUsingExceptions(); however, this should be unnecessary as a program should not operate on closed files.

### Examples

Example #1 Object-oriented style

`<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = RarArchive::open($file, null, 'retnull');
var_dump($arch->isBroken());
?>`

The above example will output something similar to:

    bool(true)

Example #2 Procedural style

`<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = rar_open($file, null, 'retnull');
var_dump(rar_broken_is($arch));
?>`

### See Also

- RarArchive::setAllowBroken() - Whether opening broken archives is allowed

# RarArchive::isSolid

# rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_is — Check whether the RAR archive is solid

### Description

Object-oriented style (method):

public RarArchive::isSolid(): bool

Procedural style:

rar_solid_is(RarArchive `$rarfile`): bool

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().

### Return Values

Returns `true` if the archive is solid, `false` otherwise.

### Examples

Example #1 Object-oriented style

`<?php
$arch1 = RarArchive::open("store_method.rar");
$arch2 = RarArchive::open("solid.rar");
echo "$arch1: " . ($arch1->isSolid()?'yes':'no') ."\n";
echo "$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>`

The above example will output something similar to:

    RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
    RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Example #2 Procedural style

`<?php
$arch1 = rar_open("store_method.rar");
$arch2 = rar_open("solid.rar");
echo "$arch1: " . (rar_solid_is($arch1)?'yes':'no') ."\n";
echo "$arch2: " . (rar_solid_is($arch2)?'yes':'no') . "\n";
?>`

# RarArchive::open

# rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_open — Open RAR archive

### Description

Object-oriented style (method):

public static RarArchive::open(string `$filename`, string `$password` = NULL, callable `$volume_callback` = NULL): RarArchive|false

Procedural style:

rar_open(string `$filename`, string `$password` = NULL, callable `$volume_callback` = NULL): RarArchive|false

Open specified RAR archive and return RarArchive instance representing it.

> Note: If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.

### Parameters

`filename`
  Path to the Rar archive.
`password`
  A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.
`volume_callback`
  A function that receives one parameter – the path of the volume that was not found – and returns a string with the correct path for such volume or `null` if such volume does not exist or is not known. The programmer should ensure the passed function doesn't cause loops as this function is called repeatedly if the path returned in a previous call did not correspond to the needed volume. Specifying this parameter omits the notice that would otherwise be emitted whenever a volume is not found; an implementation that only returns `null` can therefore be used to merely omit such notices.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

### Return Values

Returns the requested RarArchive instance or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL rar 3.0.0 | `volume_callback` was added.

### Examples

Example #1 Object-oriented style

`<?php
$rar_arch = RarArchive::open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");
$entries = $rar_arch->getEntries();
if ($entries === FALSE)
die("Failed fetching entries");
echo "Found " . count($entries) . " files.\n";
if (empty($entries))
die("No valid entries found.");
$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");
$rar_arch->close();
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>`

The above example will output something similar to:

    Found 2 files.
    Content of first one follows:
    Encrypted file 1 contents.

Example #2 Procedural style

`<?php
$rar_arch = rar_open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");
$entries = rar_list($rar_arch);
if ($entries === FALSE)
die("Failed fetching entries");
echo "Found " . count($entries) . " files.\n";
if (empty($entries))
die("No valid entries found.");
$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");
rar_close($rar_arch);
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>`

Example #3 Volume Callback

`<?php
/* In this example, there's a volume named multi_broken.part1.rar
* whose next volume is named multi.part2.rar */
function resolve($vol) {
if (preg_match('/_broken/', $vol))
return str_replace('_broken', '', $vol);
else
return null;
}
$rar_file1 = rar_open(dirname(__FILE__).'/multi_broken.part1.rar', null, 'resolve');
$entry = $rar_file1->getEntry('file2.txt');
$entry->extract(null, dirname(__FILE__) . "/temp_file2.txt");
?>`

### See Also

- `rar://` wrapper

# RarArchive::setAllowBroken

(PECL rar >= 3.0.0)

RarArchive::setAllowBroken — Whether opening broken archives is allowed

### Description

Object-oriented style (method):

public RarArchive::setAllowBroken(bool `$allow_broken`): bool

Procedural style:

rar_allow_broken_set(RarArchive `$rarfile`, bool `$allow_broken`): bool

This method defines whether broken archives can be read or all the operations that attempt to extract the archive entries will fail. Broken archives are archives for which no error is detected when the file is opened but an error occurs when reading the entries.

### Parameters

`rarfile`
  A RarArchive object, opened with rar_open().
`allow_broken`
  Whether to allow reading broken files (`true`) or not (`false`).

### Return Values

Returns `true` or `false` on failure. It will only fail if the file has already been closed.

### Examples

Example #1 Object-oriented style

`<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = RarArchive::open($file, null, 'retnull');
$a->setAllowBroken(true);
foreach ($a->getEntries() as $e) {
echo "$e\n";
}
var_dump(count($a));
?>`

The above example will output something similar to:

    RarEntry for file "file1.txt" (52b28202)
    int(1)

Example #2 Procedural style

`<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = rar_open($file, null, 'retnull');
rar_allow_broken_set($a, true);
foreach (rar_list($a) as $e) {
echo "$e\n";
}
var_dump(count($a));
?>`

### See Also

- RarArchive::isBroken() - Test whether an archive is broken (incomplete)

# RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get text representation

### Description

public RarArchive::__toString(): string

Provides a string representation for this RarArchive object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to RarArchive::close().

This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted.

### Parameters

This function has no parameters.

### Return Values

A textual representation of this RarArchive object. The content of this representation is unspecified.

### Examples

Example #1 RarArchive::__toString() example

`<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>`

The above example will output something similar to:

    RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
    RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

## Table of Contents

- RarArchive::close — Close RAR archive and free all resources
- RarArchive::getComment — Get comment text from the RAR archive
- RarArchive::getEntries — Get full list of entries from the RAR archive
- RarArchive::getEntry — Get entry object from the RAR archive
- RarArchive::isBroken — Test whether an archive is broken (incomplete)
- RarArchive::isSolid — Check whether the RAR archive is solid
- RarArchive::open — Open RAR archive
- RarArchive::setAllowBroken — Whether opening broken archives is allowed
- RarArchive::__toString — Get text representation

# The RarEntry class

(PECL rar >= 0.1)

## Introduction

A RAR entry, representing a directory or a compressed file inside a RAR archive.

## Class synopsis

final class RarEntry {
/* Constants */
const int HOST_MSDOS = 0;
const int HOST_OS2 = 1;
const int HOST_WIN32 = 2;
const int HOST_UNIX = 3;
const int HOST_MACOS = 4;
const int HOST_BEOS = 5;
const int ATTRIBUTE_WIN_READONLY = 1;
const int ATTRIBUTE_WIN_HIDDEN = 2;
const int ATTRIBUTE_WIN_SYSTEM = 4;
const int ATTRIBUTE_WIN_DIRECTORY = 16;
const int ATTRIBUTE_WIN_ARCHIVE = 32;
const int ATTRIBUTE_WIN_DEVICE = 64;
const int ATTRIBUTE_WIN_NORMAL = 128;
const int ATTRIBUTE_WIN_TEMPORARY = 256;
const int ATTRIBUTE_WIN_SPARSE_FILE = 512;
const int ATTRIBUTE_WIN_REPARSE_POINT = 1024;
const int ATTRIBUTE_WIN_COMPRESSED = 2048;
const int ATTRIBUTE_WIN_OFFLINE = 4096;
const int ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192;
const int ATTRIBUTE_WIN_ENCRYPTED = 16384;
const int ATTRIBUTE_WIN_VIRTUAL = 65536;
const int ATTRIBUTE_UNIX_WORLD_EXECUTE = 1;
const int ATTRIBUTE_UNIX_WORLD_WRITE = 2;
const int ATTRIBUTE_UNIX_WORLD_READ = 4;
const int ATTRIBUTE_UNIX_GROUP_EXECUTE = 8;
const int ATTRIBUTE_UNIX_GROUP_WRITE = 16;
const int ATTRIBUTE_UNIX_GROUP_READ = 32;
const int ATTRIBUTE_UNIX_OWNER_EXECUTE = 64;
const int ATTRIBUTE_UNIX_OWNER_WRITE = 128;
const int ATTRIBUTE_UNIX_OWNER_READ = 256;
const int ATTRIBUTE_UNIX_STICKY = 512;
const int ATTRIBUTE_UNIX_SETGID = 1024;
const int ATTRIBUTE_UNIX_SETUID = 2048;
const int ATTRIBUTE_UNIX_FINAL_QUARTET = 61440;
const int ATTRIBUTE_UNIX_FIFO = 4096;
const int ATTRIBUTE_UNIX_CHAR_DEV = 8192;
const int ATTRIBUTE_UNIX_DIRECTORY = 16384;
const int ATTRIBUTE_UNIX_BLOCK_DEV = 24576;
const int ATTRIBUTE_UNIX_REGULAR_FILE = 32768;
const int ATTRIBUTE_UNIX_SYM_LINK = 40960;
const int ATTRIBUTE_UNIX_SOCKET = 49152;
/* Methods */
public extract(
string `$dir`,
string `$filepath` = "",
string `$password` = NULL,
bool `$extended_data` = `false`
): bool
public getAttr(): int
public getCrc(): string
public getFileTime(): string
public getHostOs(): int
public getMethod(): int
public getName(): string
public getPackedSize(): int
public getStream(string `$password` = ?): resource|false
public getUnpackedSize(): int
public getVersion(): int
public isDirectory(): bool
public isEncrypted(): bool
public __toString(): string
}

## Predefined Constants

`RarEntry::HOST_MSDOS`
  If the return value of RarEntry::getHostOs() equals this constant, MS-DOS was used to add this entry. Use instead of `RAR_HOST_MSDOS`.
`RarEntry::HOST_OS2`
  If the return value of RarEntry::getHostOs() equals this constant, OS/2 was used to add this entry. Intended to replace `RAR_HOST_OS2`.
`RarEntry::HOST_WIN32`
  If the return value of RarEntry::getHostOs() equals this constant, Microsoft Windows was used to add this entry. Intended to replace `RAR_HOST_WIN32`.
`RarEntry::HOST_UNIX`
  If the return value of RarEntry::getHostOs() equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace `RAR_HOST_UNIX`.
`RarEntry::HOST_MACOS`
  If the return value of RarEntry::getHostOs() equals this constant, Mac OS was used to add this entry.
`RarEntry::HOST_BEOS`
  If the return value of RarEntry::getHostOs() equals this constant, BeOS was used to add this entry. Intended to replace `RAR_HOST_BEOS`.
`RarEntry::ATTRIBUTE_WIN_READONLY`
  Bit that represents a Windows entry with a read-only attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_HIDDEN`
  Bit that represents a Windows entry with a hidden attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_SYSTEM`
  Bit that represents a Windows entry with a system attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_DIRECTORY`
  Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.
`RarEntry::ATTRIBUTE_WIN_ARCHIVE`
  Bit that represents a Windows entry with an archive attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_DEVICE`
  Bit that represents a Windows entry with a device attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_NORMAL`
  Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.
`RarEntry::ATTRIBUTE_WIN_TEMPORARY`
  Bit that represents a Windows entry with a temporary attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_SPARSE_FILE`
  Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_REPARSE_POINT`
  Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_COMPRESSED`
  Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_OFFLINE`
  Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED`
  Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_ENCRYPTED`
  Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_WIN_VIRTUAL`
  Bit that represents a Windows entry with a virtual attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
`RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE`
  Bit that represents a UNIX entry that is world executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE`
  Bit that represents a UNIX entry that is world writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_WORLD_READ`
  Bit that represents a UNIX entry that is world readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE`
  Bit that represents a UNIX entry that is group executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE`
  Bit that represents a UNIX entry that is group writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_GROUP_READ`
  Bit that represents a UNIX entry that is group readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE`
  Bit that represents a UNIX entry that is owner executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE`
  Bit that represents a UNIX entry that is owner writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_OWNER_READ`
  Bit that represents a UNIX entry that is owner readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_STICKY`
  Bit that represents the UNIX sticky bit. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_SETGID`
  Bit that represents the UNIX setgid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_SETUID`
  Bit that represents the UNIX setuid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.
`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`
  Mask to isolate the last four bits (nibble) of UNIX attributes (_S_IFMT, the type of file mask). To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constants `RarEntry::ATTRIBUTE_UNIX_FIFO`, `RarEntry::ATTRIBUTE_UNIX_CHAR_DEV`, `RarEntry::ATTRIBUTE_UNIX_DIRECTORY`, `RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV`, `RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE`, `RarEntry::ATTRIBUTE_UNIX_SYM_LINK` and `RarEntry::ATTRIBUTE_UNIX_SOCKET`.
`RarEntry::ATTRIBUTE_UNIX_FIFO`
  Unix FIFOs will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`.
`RarEntry::ATTRIBUTE_UNIX_CHAR_DEV`
  Unix character devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`.
`RarEntry::ATTRIBUTE_UNIX_DIRECTORY`
  Unix directories will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.
`RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV`
  Unix block devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`.
`RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE`
  Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.
`RarEntry::ATTRIBUTE_UNIX_SYM_LINK`
  Unix symbolic links will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`.
`RarEntry::ATTRIBUTE_UNIX_SOCKET`
  Unix sockets will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant `RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`.

# RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extract — Extract entry from the archive

### Description

public RarEntry::extract(
string `$dir`,
string `$filepath` = "",
string `$password` = NULL,
bool `$extended_data` = `false`
): bool

RarEntry::extract() extracts the entry's data. It will create new file in the specified `dir` with the name identical to the entry's name, unless the second argument is specified. See below for more information.

### Parameters

`dir`
  Path to the directory where files should be extracted. This parameter is considered if and only if `filepath` is not. If both parameters are empty an extraction to the current directory will be attempted.
`filepath`
  Path (relative or absolute) containing the directory and filename of the extracted file. This parameter overrides both the parameter `dir` and the original file name.
`password`
  The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), CRC checking will fail and this method will fail and return `false`. If no password is given and one is required, this method will fail and return `false`. You can check whether an entry is encrypted with RarEntry::isEncrypted().
`extended_data`
  If `true`, extended information such as NTFS ACLs and Unix owner information will be set in the extract files, as long as it's present in the archive.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL rar 3.0.0 | `extended_data` was added.
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

### Examples

Example #1 RarEntry::extract() example

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt
?>`

Example #2 How to extract all files in archive:

`<?php
/* example by Erik Jenssen aka erix */
$filename = "foobar.rar";
$filepath = "/home/foo/bar/";
$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
$entry = rar_entry_get($rar_file, $file);
$entry->extract("."); // extract to the current dir
}
rar_close($rar_file);
?>`

### See Also

- RarEntry::getStream() - Get file handler for entry
- `rar://` wrapper

# RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get attributes of the entry

### Description

public RarEntry::getAttr(): int

Returns the OS-dependent attributes of the archive entry.

### Parameters

This function has no parameters.

### Return Values

Returns the attributes or `false` on error.

### Examples

Example #1 RarEntry::getAttr() example

`<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");
$host_os = $entry->getHostOs();
$attr = $entry->getAttr();
switch($host_os) {
case RAR_HOST_MSDOS:
case RAR_HOST_OS2:
case RAR_HOST_WIN32:
case RAR_HOST_MACOS:
printf("%c%c%c%c%c%c\n",
($attr & 0x08) ? 'V' : '.',
($attr & 0x10) ? 'D' : '.',
($attr & 0x01) ? 'R' : '.',
($attr & 0x02) ? 'H' : '.',
($attr & 0x04) ? 'S' : '.',
($attr & 0x20) ? 'A' : '.');
break;
case RAR_HOST_UNIX:
case RAR_HOST_BEOS:
switch ($attr & 0xF000)
{
case 0x4000:
printf("d");
break;
case 0xA000:
printf("l");
break;
default:
printf("-");
break;
}
printf("%c%c%c%c%c%c%c%c%c\n",
($attr & 0x0100) ? 'r' : '-',
($attr & 0x0080) ? 'w' : '-',
($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
($attr & 0x0020) ? 'r' : '-',
($attr & 0x0010) ? 'w' : '-',
($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
($attr & 0x0004) ? 'r' : '-',
($attr & 0x0002) ? 'w' : '-',
($attr & 0x0001) ? 'x' : '-');
break;
}
rar_close($rar_file);
?>`

### See Also

- RarEntry::getHostOs() - Get entry host OS
- The constants in RarEntry

# RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get CRC of the entry

### Description

public RarEntry::getCrc(): string

Returns an hexadecimal string representation of the CRC of the archive entry.

### Parameters

This function has no parameters.

### Return Values

Returns the CRC of the archive entry or `false` on error.

### Changelog

Version | Description
--- | ---
PECL rar 2.0.0 | This method now returns correct values for multiple volume archives.

# RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get entry last modification time

### Description

public RarEntry::getFileTime(): string

Gets entry last modification time.

### Parameters

This function has no parameters.

### Return Values

Returns entry last modification time as string in format `YYYY-MM-DD HH:II:SS`, or `false` on error.

# RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get entry host OS

### Description

public RarEntry::getHostOs(): int

Returns the code of the host OS of the archive entry.

### Parameters

This function has no parameters.

### Return Values

Returns the code of the host OS, or `false` on error.

### Examples

Example #1 RarEntry::getHostOs() example (version >= 2.0.0)

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
switch ($entry->getHostOs()) {
case RarEntry::HOST_MSDOS:
echo "MS-DOS\n";
break;
case RarEntry::HOST_OS2:
echo "OS2\n";
break;
case RarEntry::HOST_WIN32:
echo "Win32\n";
break;
case RarEntry::HOST_MACOS:
echo "MacOS\n";
break;
case RarEntry::HOST_UNIX:
echo "Unix/Linux\n";
break;
case RarEntry::HOST_BEOS:
echo "BeOS\n";
break;
}
?>`

Example #2 RarEntry::getHostOs() example (version <= 1.0.0)

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
switch ($entry->getHostOs()) {
case RAR_HOST_MSDOS:
echo "MS-DOS\n";
break;
case RAR_HOST_OS2:
echo "OS2\n";
break;
case RAR_HOST_WIN32:
echo "Win32\n";
break;
case RAR_HOST_MACOS:
echo "MacOS\n";
break;
case RAR_HOST_UNIX:
echo "Unix/Linux\n";
break;
case RAR_HOST_BEOS:
echo "BeOS\n";
break;
}
?>`

### See Also

- RarEntry::extract() - Extract entry from the archive

# RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get pack method of the entry

### Description

public RarEntry::getMethod(): int

RarEntry::getMethod() returns number of the method used when adding current archive entry.

### Parameters

This function has no parameters.

### Return Values

Returns the method number or `false` on error.

### Examples

Example #1 RarEntry::getMethod() example

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
echo "Method number: " . $entry->getMethod();
?>`

# RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get name of the entry

### Description

public RarEntry::getName(): string

Returns the name (with path) of the archive entry.

### Parameters

This function has no parameters.

### Return Values

Returns the entry name as a string, or `false` on error.

### Changelog

Version | Description
--- | ---
PECL rar 2.0.0 | As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

### Examples

Example #1 RarEntry::getName() example

`<?php
//this example is safe even in pages not encoded in UTF-8
//for those encoded in UTF-8, the call to mb_convert_encoding is unnecessary
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
echo "Entry name: " . mb_convert_encoding(
htmlentities(
$entry->getName(),
ENT_COMPAT,
"UTF-8"
),
"HTML-ENTITIES",
"UTF-8"
);
?>`

# RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get packed size of the entry

### Description

public RarEntry::getPackedSize(): int

Get packed size of the archive entry.

> Note: Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant `PHP_INT_MAX`.

### Parameters

This function has no parameters.

### Return Values

Returns the packed size, or `false` on error.

### Changelog

Version | Description
--- | ---
PECL rar 2.0.0 | This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit ints and never returns negative values on other platforms.

### Examples

Example #1 RarEntry::getPackedSize() example

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
echo "Packed size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";
?>`

# RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get file handler for entry

### Description

public RarEntry::getStream(string `$password` = ?): resource|false

Returns a file handler that supports read operations. This handler provides on-the-fly decompression for this entry.

The handler is not invalidated by calling rar_close().

Warning

The resulting stream has no integrity verification. In particular, file corruption and decryption with a wrong a key will not be detected. It is the programmer's responsability to use the entry's CRC to check for integrity, if he so wishes.

### Parameters

`password`
  The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), this method's resulting stream will produce wrong output. If no password is given and one is required, this method will fail and return `false`. You can check whether an entry is encrypted with RarEntry::isEncrypted().

### Return Values

The file handler or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

### Examples

Example #1 RarEntry::getStream() example

`<?php
$rar_file = rar_open('example.rar');
if ($rar_file === false)
die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt');
if ($entry === false)
die("Failed to find such entry");
$stream = $entry->getStream();
if ($stream === false)
die("Failed to obtain stream.");
rar_close($rar_file); //stream is independent from file
while (!feof($stream)) {
$buff = fread($stream, 8192);
if ($buff !== false)
echo $buff;
else
break; //fread error
}
fclose($stream);
?>`

### See Also

- RarEntry::extract() - Extract entry from the archive
- `rar://` wrapper

# RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get unpacked size of the entry

### Description

public RarEntry::getUnpackedSize(): int

Get unpacked size of the archive entry.

> Note: Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant `PHP_INT_MAX`.

### Parameters

This function has no parameters.

### Return Values

Returns the unpacked size, or `false` on error.

### Changelog

Version | Description
--- | ---
PECL rar 2.0.0 | This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit ints and never returns negative values on other platforms.

### Return Values

Example #1 RarEntry::getUnpackedSize() example

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
echo "Unpacked size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";
?>`

# RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry

### Description

public RarEntry::getVersion(): int

Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 * major version + minor version.

### Parameters

This function has no parameters.

### Return Values

Returns the version or `false` on error.

### Examples

Example #1 RarEntry::getVersion() example

`<?php
$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");
$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");
echo "Rar version required for unpacking: " . $entry->getVersion();
?>`

# RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test whether an entry represents a directory

### Description

public RarEntry::isDirectory(): bool

Tests whether the current entry is a directory.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this entry is a directory and `false` otherwise.

### Notes

This function is only available starting with version 2.0.0, but one can also test whether an entry is a directory by checking the entry attributes, like this (only works for files compressed in RAR for Windows or Unix):

`<?php
//...
//Open file, get entry and store in variable $e...
//...
$isDirectory = (bool) ((($e->getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
(($e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));
?>`

# RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test whether an entry is encrypted

### Description

public RarEntry::isEncrypted(): bool

Tests whether the current entry contents are encrypted.

> Note: The password used may differ between files inside the same RAR archive.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the current entry is encrypted and `false` otherwise.

# RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get text representation of entry

### Description

public RarEntry::__toString(): string

RarEntry::__toString() returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon.

### Parameters

This function has no parameters.

### Return Values

A textual representation for the entry.

## Table of Contents

- RarEntry::extract — Extract entry from the archive
- RarEntry::getAttr — Get attributes of the entry
- RarEntry::getCrc — Get CRC of the entry
- RarEntry::getFileTime — Get entry last modification time
- RarEntry::getHostOs — Get entry host OS
- RarEntry::getMethod — Get pack method of the entry
- RarEntry::getName — Get name of the entry
- RarEntry::getPackedSize — Get packed size of the entry
- RarEntry::getStream — Get file handler for entry
- RarEntry::getUnpackedSize — Get unpacked size of the entry
- RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
- RarEntry::isDirectory — Test whether an entry represents a directory
- RarEntry::isEncrypted — Test whether an entry is encrypted
- RarEntry::__toString — Get text representation of entry

# The RarException class

(PECL rar >= 2.0.0)

## Introduction

This class serves two purposes: it is the type of the exceptions thrown by the RAR extension functions and methods and it allows, through static methods to query and define the error behaviour of the extension, i.e., whether exceptions are thrown or only warnings are emitted.

The following error codes are used:

- -1 - error outside UnRAR library
- 11 - insufficient memory
- 12 - bad data
- 13 - bad archive
- 14 - unknown format
- 15 - file open error
- 16 - file create error
- 17 - file close error
- 18 - read error
- 19 - write error
- 20 - buffer too small
- 21 - unknown RAR error
- 22 - password required but not given

## Class synopsis

final class RarException extends Exception {
/* Methods */
public static isUsingExceptions(): bool
public static setUsingExceptions(bool `$using_exceptions`): void
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check whether error handling with exceptions is in use

### Description

public static RarException::isUsingExceptions(): bool

Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).

### Parameters

This function has no parameters.

### Return Values

Returns `true` if exceptions are being used, `false` otherwise.

### Examples

Example #1 RarException::isUsingExceptions() example

`<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>`

The above example will output something similar to:

    bool(false)

### See Also

- RarException::setUsingExceptions() - Activate and deactivate error handling with exceptions

# RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

### Description

public static RarException::setUsingExceptions(bool `$using_exceptions`): void

If and only if the argument is `true`, then, instead of emitting warnings and returning a special value indicating error when the UnRAR library encounters an error, an exception of type RarException will be thrown.

Exceptions will also be thrown for the following errors, which occur outside the library (their error code will be -1):

- attempting some operations on a closed RarArchive object or a RarEntry object relative to the first;
- attempting to get an entry that does not exist with RarArchive::getEntry().

### Parameters

`using_exceptions`
  Should be `true` to activate exception throwing, `false` to deactivate (the default).

### Return Values

No value is returned.

### Examples

Example #1 RarException::setUsingExceptions() example

`<?php
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch);
RarException::setUsingExceptions(true);
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch); //not reached
?>`

The above example will output something similar to:

    bool(false)

    Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
    bool(false)
    bool(true)

    Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
    Stack trace:
    #0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
    #1 {main}
      thrown in C:\php_rar\trunk\tests\test.php on line 8

### See Also

- RarException::isUsingExceptions() - Check whether error handling with exceptions is in use

## Table of Contents

- RarException::isUsingExceptions — Check whether error handling with exceptions is in use
- RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- Examples
- Rar Functions
  - rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
- RarArchive — The RarArchive class
  - RarArchive::close — Close RAR archive and free all resources
  - RarArchive::getComment — Get comment text from the RAR archive
  - RarArchive::getEntries — Get full list of entries from the RAR archive
  - RarArchive::getEntry — Get entry object from the RAR archive
  - RarArchive::isBroken — Test whether an archive is broken (incomplete)
  - RarArchive::isSolid — Check whether the RAR archive is solid
  - RarArchive::open — Open RAR archive
  - RarArchive::setAllowBroken — Whether opening broken archives is allowed
  - RarArchive::__toString — Get text representation
- RarEntry — The RarEntry class
  - RarEntry::extract — Extract entry from the archive
  - RarEntry::getAttr — Get attributes of the entry
  - RarEntry::getCrc — Get CRC of the entry
  - RarEntry::getFileTime — Get entry last modification time
  - RarEntry::getHostOs — Get entry host OS
  - RarEntry::getMethod — Get pack method of the entry
  - RarEntry::getName — Get name of the entry
  - RarEntry::getPackedSize — Get packed size of the entry
  - RarEntry::getStream — Get file handler for entry
  - RarEntry::getUnpackedSize — Get unpacked size of the entry
  - RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
  - RarEntry::isDirectory — Test whether an entry represents a directory
  - RarEntry::isEncrypted — Test whether an entry is encrypted
  - RarEntry::__toString — Get text representation of entry
- RarException — The RarException class
  - RarException::isUsingExceptions — Check whether error handling with exceptions is in use
  - RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

# Zip

# Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

This extension requires » libzip. Version 1.1.2 was bundled in PHP until version 7.3.

Minimal supported version is 0.11, but higher is highly recommended.

- Version 1.2 required for encryption support, see ZipArchive::setEncryptionIndex()
- Version 1.3 required for progress support, see ZipArchive::registerProgressCallback()
- Version 1.6 required for cancel support, see ZipArchive::registerCancelCallback()

## Installation

## Linux systems

In order to use these functions PHP must be compiled with ZIP support by using the --with-zip configure option.

Prior to PHP 7.4.0, libzip was bundled with PHP, and to compile the extension one needed to use the --enable-zip configure option. Building against the bundled libzip was discouraged as of PHP 7.3.0, but still possible by using the --without-libzip configure option.

A --with-libzip=DIR configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

## Windows

As of PHP 8.2.0, php_zip.dll DLL must be enabled in php.ini. Previously, this extension was built-in.

## Installation via PECL

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: » https://pecl.php.net/package/zip.

## Resource Types

There are two resource types used in the Zip module. The first one is the Zip directory for the Zip archive, the second Zip Entry for the archive entries.

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

ZipArchive uses class constants. There are various types of constants, main are: Flags (prefixed with `FL_`), Global flags (prefixed with `AFL_`), errors (prefixed with `ER_`) and mode (no prefix).

Archive open modes
`ZipArchive::CREATE` (int)
  Create the archive if it does not exist.
`ZipArchive::OVERWRITE` (int)
  If archive exists, ignore its current contents. In other words, handle it the same way as an empty archive.
`ZipArchive::EXCL` (int)
  Error if archive already exists.
`ZipArchive::RDONLY` (int)
  Open archive in read only mode. Available as of PHP 7.4.3 and PECL zip 1.17.1, respectively, if built against libzip ≥ 1.0.0.
`ZipArchive::CHECKCONS` (int)
  Perform additional consistency checks on the archive, and error if they fail.

Archive global flags
`ZipArchive::AFL_RDONLY` (int)
  Archive is read only, cannot be cleared. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.
`ZipArchive::AFL_IS_TORRENTZIP` (int)
  Current archive is torrentzipped. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.
`ZipArchive::AFL_WANT_TORRENTZIP` (int)
  Write archive in torrentzip format. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.
`ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE` (int)
  Don't remove file if archive is empty. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.

Archive flags
`ZipArchive::FL_NOCASE` (int)
  Ignore case on name lookup
`ZipArchive::FL_NODIR` (int)
  Ignore directory component
`ZipArchive::FL_COMPRESSED` (int)
  Read compressed data
`ZipArchive::FL_UNCHANGED` (int)
  Use original data, ignoring changes.
`ZipArchive::FL_RECOMPRESS` (int)
  Force recompression of data. Available as of PHP 8.0.0 and PECL zip 1.18.0. Deprecated as of PHP 8.3.0 and PECL zip 1.22.1, will be removed in a future version of libzip.
`ZipArchive::FL_ENCRYPTED` (int)
  Read encrypted data (implies FL_COMPRESSED). Available as of PHP 8.0.0 and PECL zip 1.18.0.
`ZipArchive::FL_OVERWRITE` (int)
  If file with name exists, overwrite (replace) it. Available as of PHP 8.0.0 and PECL zip 1.18.0.
`ZipArchive::FL_LOCAL` (int)
  In local header. Available as of PHP 8.0.0 and PECL zip 1.18.0.
`ZipArchive::FL_CENTRAL` (int)
  In central directory. Available as of PHP 8.0.0 and PECL zip 1.18.0.
`ZipArchive::FL_ENC_GUESS` (int)
  Guess string encoding (is default). Available as of PHP 7.0.8.
`ZipArchive::FL_ENC_RAW` (int)
  Get unmodified string. Available as of PHP 7.0.8.
`ZipArchive::FL_ENC_STRICT` (int)
  Follow specification strictly. Available as of PHP 7.0.8.
`ZipArchive::FL_ENC_UTF_8` (int)
  String is UTF-8 encoded. Available as of PHP 7.0.8.
`ZipArchive::FL_ENC_CP437` (int)
  String is CP437 encoded. Available as of PHP 7.0.8.
`ZipArchive::FL_OPEN_FILE_NOW` (int)
  Open the file when added instead of waiting for archive to be closed. Be aware of file descriptors consumption. Available as of PHP 8.3.0 and PECL zip 1.22.1.

Compression modes
`ZipArchive::CM_DEFAULT` (int)
  better of deflate or store.
`ZipArchive::CM_STORE` (int)
  stored (uncompressed).
`ZipArchive::CM_SHRINK` (int)
  shrunk
`ZipArchive::CM_REDUCE_1` (int)
  reduced with factor 1
`ZipArchive::CM_REDUCE_2` (int)
  reduced with factor 2
`ZipArchive::CM_REDUCE_3` (int)
  reduced with factor 3
`ZipArchive::CM_REDUCE_4` (int)
  reduced with factor 4
`ZipArchive::CM_IMPLODE` (int)
  imploded
`ZipArchive::CM_DEFLATE` (int)
  deflated
`ZipArchive::CM_DEFLATE64` (int)
  deflate64
`ZipArchive::CM_PKWARE_IMPLODE` (int)
  PKWARE imploding
`ZipArchive::CM_BZIP2` (int)
  BZIP2 algorithm
`ZipArchive::CM_LZMA` (int)
  LZMA algorithm
`ZipArchive::CM_LZMA2` (int)
  LZMA2 algorithm. Available as of PHP 7.4.3 and PECL zip 1.16.0, respectively, if built against libzip ≥ 1.6.0.
`ZipArchive::CM_ZSTD` (int)
  Zstandard algorithm. Available as of PHP 8.0.0 and PECL zip 1.19.1, respectively, if built against libzip ≥ 1.8.0.
`ZipArchive::CM_XZ` (int)
  XZ algorithm. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.6.0.
`ZipArchive::CM_TERSE` (int)
`ZipArchive::CM_LZ77` (int)
`ZipArchive::CM_WAVPACK` (int)
`ZipArchive::CM_PPMD` (int)

Errors
`ZipArchive::ER_OK` (int)
  No error.
`ZipArchive::ER_MULTIDISK` (int)
  Multi-disk zip archives not supported.
`ZipArchive::ER_RENAME` (int)
  Renaming temporary file failed.
`ZipArchive::ER_CLOSE` (int)
  Closing zip archive failed
`ZipArchive::ER_SEEK` (int)
  Seek error
`ZipArchive::ER_READ` (int)
  Read error
`ZipArchive::ER_WRITE` (int)
  Write error
`ZipArchive::ER_CRC` (int)
  CRC error
`ZipArchive::ER_ZIPCLOSED` (int)
  Containing zip archive was closed
`ZipArchive::ER_NOENT` (int)
  No such file.
`ZipArchive::ER_EXISTS` (int)
  File already exists
`ZipArchive::ER_OPEN` (int)
  Can't open file
`ZipArchive::ER_TMPOPEN` (int)
  Failure to create temporary file.
`ZipArchive::ER_ZLIB` (int)
  Zlib error
`ZipArchive::ER_MEMORY` (int)
  Memory allocation failure
`ZipArchive::ER_CHANGED` (int)
  Entry has been changed
`ZipArchive::ER_COMPNOTSUPP` (int)
  Compression method not supported.
`ZipArchive::ER_EOF` (int)
  Premature EOF
`ZipArchive::ER_INVAL` (int)
  Invalid argument
`ZipArchive::ER_NOZIP` (int)
  Not a zip archive
`ZipArchive::ER_INTERNAL` (int)
  Internal error
`ZipArchive::ER_INCONS` (int)
  Zip archive inconsistent
`ZipArchive::ER_REMOVE` (int)
  Can't remove file
`ZipArchive::ER_DELETED` (int)
  Entry has been deleted
`ZipArchive::ER_ENCRNOTSUPP` (int)
  Encryption method not supported. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
`ZipArchive::ER_RDONLY` (int)
  Read-only archive. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
`ZipArchive::ER_NOPASSWD` (int)
  No password provided. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
`ZipArchive::ER_WRONGPASSWD` (int)
  Wrong password provided. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
`ZipArchive::ER_OPNOTSUPP` (int)
  Operation not supported. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.0.0.
`ZipArchive::ER_INUSE` (int)
  Resource still in use. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.0.0.
`ZipArchive::ER_TELL` (int)
  Tell error. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.0.0.
`ZipArchive::ER_COMPRESSED_DATA` (int)
  Compressed data invalid. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.6.0.
`ZipArchive::ER_CANCELLED` (int)
  Operation cancelled. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.6.0.
`ZipArchive::ER_DATA_LENGTH` (int)
  Unexpected length of data. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.
`ZipArchive::ER_NOT_ALLOWED` (int)
  Not allowed in torrentzip. Available as of PHP 8.3.0 and PECL zip 1.22.0, respectively, if built against libzip ≥ 1.10.0.
`ZipArchive::ER_TRUNCATED_ZIP` (int)
  Possibly truncated or corrupted zip archive. Available as of PHP 8.4.0 and PECL zip 1.22.4, respectively, if built against libzip ≥ 1.11.1.

Encryption modes
`ZipArchive::EM_NONE` (int)
  No encryption. Available as of PHP 7.2.0 and PECL zip 1.14.0, respectively.
`ZipArchive::EM_TRAD_PKWARE` (int)
  Traditional PKWARE encryption. Available as of PHP 8.0.0 and PECL zip 1.19.0, respectively.
`ZipArchive::EM_AES_128` (int)
  AES 128 encryption. Available as of PHP 7.2.0 and PECL zip 1.14.0, respectively, if built against libzip ≥ 1.2.0.
`ZipArchive::EM_AES_192` (int)
  AES 192 encryption. Available as of PHP 7.2.0 and PECL zip 1.14.0, respectively, if built against libzip ≥ 1.2.0.
`ZipArchive::EM_AES_256` (int)
  AES 256 encryption. Available as of PHP 7.2.0 and PECL zip 1.14.0, respectively, if built against libzip ≥ 1.2.0.
`ZipArchive::EM_UNKNOWN` (int)
  Unknown encryption algorithm. Available as of PHP 8.0.0 and PECL zip 1.19.0, respectively.

Length parameter constants
`ZipArchive::LENGTH_TO_END` (int)
  Use file size, if the file grows additionnal data is ignored, if the file shrinks an error is raised (`ZipArchive::ER_DATA_LENGTH`). Available as of PHP 8.3.0 and PECL zip 1.22.2.
`ZipArchive::LENGTH_UNCHECKED` (int)
  Use all available data. Available as of PHP 8.3.0 and PECL zip 1.22.2, if built against libzip ≥ 1.10.1.

Other constants
`ZipArchive::LIBZIP_VERSION` (string)
  Zip library version. Available as of PHP 7.4.3 and PECL zip 1.16.0.

Operating system constants for external attributes
`ZipArchive::OPSYS_DOS` (int)
`ZipArchive::OPSYS_AMIGA` (int)
`ZipArchive::OPSYS_OPENVMS` (int)
`ZipArchive::OPSYS_UNIX` (int)
`ZipArchive::OPSYS_VM_CMS` (int)
`ZipArchive::OPSYS_ATARI_ST` (int)
`ZipArchive::OPSYS_OS_2` (int)
`ZipArchive::OPSYS_MACINTOSH` (int)
`ZipArchive::OPSYS_Z_SYSTEM` (int)
`ZipArchive::OPSYS_CPM` (int)
`ZipArchive::OPSYS_WINDOWS_NTFS` (int)
`ZipArchive::OPSYS_MVS` (int)
`ZipArchive::OPSYS_VSE` (int)
`ZipArchive::OPSYS_ACORN_RISC` (int)
`ZipArchive::OPSYS_VFAT` (int)
`ZipArchive::OPSYS_ALTERNATE_MVS` (int)
`ZipArchive::OPSYS_BEOS` (int)
`ZipArchive::OPSYS_TANDEM` (int)
`ZipArchive::OPSYS_OS_400` (int)
`ZipArchive::OPSYS_OS_X` (int)
`ZipArchive::OPSYS_DEFAULT` (int)
  Since PECL zip 1.12.4

# Examples

Example #1 Create a Zip archive

`<?php
$zip = new ZipArchive();
$filename = "./test112.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>`

Example #2 Dump the archive details and listing

`<?php
$za = new ZipArchive();
$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";
for ($i=0; $i<$za->numFiles;$i++) {
echo "index: $i\n";
print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>`

Example #3 Zip stream wrapper, read an OpenOffice meta info

`<?php
$reader = new XMLReader();
$reader->open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader->read()) {
if ($reader->nodeType == XMLREADER::ELEMENT) {
$elm = $reader->name;
} else {
if ($reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
break;
}
if (!trim($reader->value)) {
continue;
}
$odt_meta[$elm] = $reader->value;
}
}
print_r($odt_meta);
?>`

This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example #4 Zip Usage Example

`<?php
$zip = zip_open("/tmp/test2.zip");
if ($zip) {
while ($zip_entry = zip_read($zip)) {
echo "Name: " . zip_entry_name($zip_entry) . "\n";
echo "Actual Filesize: " . zip_entry_filesize($zip_entry) . "\n";
echo "Compressed Size: " . zip_entry_compressedsize($zip_entry) . "\n";
echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";
if (zip_entry_open($zip, $zip_entry, "r")) {
echo "File Contents:\n";
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
echo "$buf\n";
zip_entry_close($zip_entry);
}
echo "\n";
}
zip_close($zip);
}
?>`

# The ZipArchive class

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

## Introduction

A file archive, compressed with Zip.

## Class synopsis

class ZipArchive implements Countable {
/* Constants */
public const int CREATE;
public const int EXCL;
public const int CHECKCONS;
public const int OVERWRITE;
public const int RDONLY;
public const int FL_NOCASE;
public const int FL_NODIR;
public const int FL_COMPRESSED;
public const int FL_UNCHANGED;
public const int FL_RECOMPRESS;
public const int FL_ENCRYPTED;
public const int FL_OVERWRITE;
public const int FL_LOCAL;
public const int FL_CENTRAL;
public const int FL_ENC_GUESS;
public const int FL_ENC_RAW;
public const int FL_ENC_STRICT;
public const int FL_ENC_UTF_8;
public const int FL_ENC_CP437;
public const int FL_OPEN_FILE_NOW;
public const int CM_DEFAULT;
public const int CM_STORE;
public const int CM_SHRINK;
public const int CM_REDUCE_1;
public const int CM_REDUCE_2;
public const int CM_REDUCE_3;
public const int CM_REDUCE_4;
public const int CM_IMPLODE;
public const int CM_DEFLATE;
public const int CM_DEFLATE64;
public const int CM_PKWARE_IMPLODE;
public const int CM_BZIP2;
public const int CM_LZMA;
public const int CM_LZMA2;
public const int CM_ZSTD;
public const int CM_XZ;
public const int CM_TERSE;
public const int CM_LZ77;
public const int CM_WAVPACK;
public const int CM_PPMD;
public const int ER_OK;
public const int ER_MULTIDISK;
public const int ER_RENAME;
public const int ER_CLOSE;
public const int ER_SEEK;
public const int ER_READ;
public const int ER_WRITE;
public const int ER_CRC;
public const int ER_ZIPCLOSED;
public const int ER_NOENT;
public const int ER_EXISTS;
public const int ER_OPEN;
public const int ER_TMPOPEN;
public const int ER_ZLIB;
public const int ER_MEMORY;
public const int ER_CHANGED;
public const int ER_COMPNOTSUPP;
public const int ER_EOF;
public const int ER_INVAL;
public const int ER_NOZIP;
public const int ER_INTERNAL;
public const int ER_INCONS;
public const int ER_REMOVE;
public const int ER_DELETED;
public const int ER_ENCRNOTSUPP;
public const int ER_RDONLY;
public const int ER_NOPASSWD;
public const int ER_WRONGPASSWD;
public const int ER_OPNOTSUPP;
public const int ER_INUSE;
public const int ER_TELL;
public const int ER_COMPRESSED_DATA;
public const int ER_CANCELLED;
public const int ER_DATA_LENGTH;
public const int ER_NOT_ALLOWED;
public const int ER_TRUNCATED_ZIP;
public const int AFL_RDONLY;
public const int AFL_IS_TORRENTZIP;
public const int AFL_WANT_TORRENTZIP;
public const int AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE;
public const int OPSYS_DOS;
public const int OPSYS_AMIGA;
public const int OPSYS_OPENVMS;
public const int OPSYS_UNIX;
public const int OPSYS_VM_CMS;
public const int OPSYS_ATARI_ST;
public const int OPSYS_OS_2;
public const int OPSYS_MACINTOSH;
public const int OPSYS_Z_SYSTEM;
public const int OPSYS_CPM;
public const int OPSYS_WINDOWS_NTFS;
public const int OPSYS_MVS;
public const int OPSYS_VSE;
public const int OPSYS_ACORN_RISC;
public const int OPSYS_VFAT;
public const int OPSYS_ALTERNATE_MVS;
public const int OPSYS_BEOS;
public const int OPSYS_TANDEM;
public const int OPSYS_OS_400;
public const int OPSYS_OS_X;
public const int OPSYS_DEFAULT;
public const int EM_NONE;
public const int EM_TRAD_PKWARE;
public const int EM_AES_128;
public const int EM_AES_192;
public const int EM_AES_256;
public const int EM_UNKNOWN;
public const string LIBZIP_VERSION;
public const int LENGTH_TO_END;
public const int LENGTH_UNCHECKED;
/* Properties */
public readonly int $lastId;
public readonly int $status;
public readonly int $statusSys;
public readonly int $numFiles;
public readonly string $filename;
public readonly string $comment;
/* Methods */
public addEmptyDir(string `$dirname`, int `$flags` = 0): bool
public addFile(
string `$filepath`,
string `$entryname` = "",
int `$start` = 0,
int `$length` = `ZipArchive::LENGTH_TO_END`,
int `$flags` = `ZipArchive::FL_OVERWRITE`
): bool
public addFromString(string `$name`, string `$content`, int `$flags` = `ZipArchive::FL_OVERWRITE`): bool
public addGlob(string `$pattern`, int `$flags` = 0, array `$options` = []): array|false
public addPattern(string `$pattern`, string `$path` = ".", array `$options` = []): array|false
public clearError(): void
public close(): bool
public count(): int
public deleteIndex(int `$index`): bool
public deleteName(string `$name`): bool
public extractTo(string `$pathto`, array|string|null `$files` = `null`): bool
public getArchiveComment(int `$flags` = 0): string|false
public getArchiveFlag(int `$flag`, int `$flags` = 0): int
public getCommentIndex(int `$index`, int `$flags` = 0): string|false
public getCommentName(string `$name`, int `$flags` = 0): string|false
public getExternalAttributesIndex(
int `$index`,
int `&$opsys`,
int `&$attr`,
int `$flags` = 0
): bool
public getExternalAttributesName(
string `$name`,
int `&$opsys`,
int `&$attr`,
int `$flags` = 0
): bool
public getFromIndex(int `$index`, int `$len` = 0, int `$flags` = 0): string|false
public getFromName(string `$name`, int `$len` = 0, int `$flags` = 0): string|false
public getNameIndex(int `$index`, int `$flags` = 0): string|false
public getStatusString(): string
public getStream(string `$name`): resource|false
public getStreamIndex(int `$index`, int `$flags` = 0): resource|false
public getStreamName(string `$name`, int `$flags` = 0): resource|false
public static isCompressionMethodSupported(int `$method`, bool `$enc` = `true`): bool
public static isEncryptionMethodSupported(int `$method`, bool `$enc` = `true`): bool
public locateName(string `$name`, int `$flags` = 0): int|false
public open(string `$filename`, int `$flags` = 0): bool|int
public registerCancelCallback(callable `$callback`): bool
public registerProgressCallback(float `$rate`, callable `$callback`): bool
public renameIndex(int `$index`, string `$new_name`): bool
public renameName(string `$name`, string `$new_name`): bool
public replaceFile(
string `$filepath`,
int `$index`,
int `$start` = 0,
int `$length` = `ZipArchive::LENGTH_TO_END`,
int `$flags` = 0
): bool
public setArchiveComment(string `$comment`): bool
public setArchiveFlag(int `$flag`, int `$value`): bool
public setCommentIndex(int `$index`, string `$comment`): bool
public setCommentName(string `$name`, string `$comment`): bool
public setCompressionIndex(int `$index`, int `$method`, int `$compflags` = 0): bool
public setCompressionName(string `$name`, int `$method`, int `$compflags` = 0): bool
public setEncryptionIndex(int `$index`, int `$method`, #[\SensitiveParameter] ?string `$password` = `null`): bool
public setEncryptionName(string `$name`, int `$method`, #[\SensitiveParameter] ?string `$password` = `null`): bool
public setExternalAttributesIndex(
int `$index`,
int `$opsys`,
int `$attr`,
int `$flags` = 0
): bool
public setExternalAttributesName(
string `$name`,
int `$opsys`,
int `$attr`,
int `$flags` = 0
): bool
public setMtimeIndex(int `$index`, int `$timestamp`, int `$flags` = 0): bool
public setMtimeName(string `$name`, int `$timestamp`, int `$flags` = 0): bool
public setPassword(#[\SensitiveParameter] string `$password`): bool
public statIndex(int `$index`, int `$flags` = 0): array|false
public statName(string `$name`, int `$flags` = 0): array|false
public unchangeAll(): bool
public unchangeArchive(): bool
public unchangeIndex(int `$index`): bool
public unchangeName(string `$name`): bool
}

## Properties

lastId

  Index value of last added entry (file or directory). Available as of PHP 8.0.0 and PECL zip 1.18.0.

status

  Status of the Zip Archive. Available for closed archive, as of PHP 8.0.0 and PECL zip 1.18.0.

statusSys

  System status of the Zip Archive. Available for closed archive, as of PHP 8.0.0 and PECL zip 1.18.0.

numFiles

  Number of files in archive

filename

  File name in the file system

comment

  Comment for the archive

# ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

### Description

public ZipArchive::addEmptyDir(string `$dirname`, int `$flags` = 0): bool

Adds an empty directory in the archive.

### Parameters

`dirname`

  The directory to add.

`flags`

  Bitmask consisting of `ZipArchive::FL_ENC_GUESS`, `ZipArchive::FL_ENC_UTF_8`, `ZipArchive::FL_ENC_CP437`. The behaviour of these constants is described on the ZIP constants page.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL zip 1.18.0 | `flags` was added.

### Examples

Example #1 Create a new directory in an archive

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
if($zip->addEmptyDir('newDirectory')) {
echo 'Created a new root directory';
} else {
echo 'Could not create the directory';
}
$zip->close();
} else {
echo 'failed';
}
?>`

# ZipArchive::addFile

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

### Description

public ZipArchive::addFile(
string `$filepath`,
string `$entryname` = "",
int `$start` = 0,
int `$length` = `ZipArchive::LENGTH_TO_END`,
int `$flags` = `ZipArchive::FL_OVERWRITE`
): bool

Adds a file to a ZIP archive from a given path.

> Note: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames.

### Parameters

`filepath`

  The path to the file to add.

`entryname`

  If supplied and not empty, this is the local name inside the ZIP archive that will override the `filepath`.

`start`

  For partial copy, start position.

`length`

  For partial copy, length to be copied, if `ZipArchive::LENGTH_TO_END` (0) the file size is used, if `ZipArchive::LENGTH_UNCHECKED` the whole file is used (starting from `start`).

`flags`

  Bitmask consisting of `ZipArchive::FL_OVERWRITE`, `ZipArchive::FL_ENC_GUESS`, `ZipArchive::FL_ENC_UTF_8`, `ZipArchive::FL_ENC_CP437`, `ZipArchive::FL_OPEN_FILE_NOW`. The behaviour of these constants is described on the ZIP constants page.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL zip 1.18.0 | `flags` was added.
8.3.0, PECL zip 1.22.1 | `ZipArchive::FL_OPEN_FILE_NOW` was added.
8.3.0, PECL zip 1.22.2 | `ZipArchive::LENGTH_TO_END` and `ZipArchive::LENGTH_UNCHECKED` were added.

### Examples

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Example #1 Open and add

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

### Notes

> Note:

> When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the ZipArchive object has been closed, either via ZipArchive::close() or the ZipArchive object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released.

### See Also

- ZipArchive::replaceFile() - Replace file in ZIP archive with a given path

# ZipArchive::addFromString

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add a file to a ZIP archive using its contents

### Description

public ZipArchive::addFromString(string `$name`, string `$content`, int `$flags` = `ZipArchive::FL_OVERWRITE`): bool

Add a file to a ZIP archive using its contents.

> Note: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames.

### Parameters

`name`

  The name of the entry to create.

`content`

  The contents to use to create the entry. It is used in a binary safe mode.

`flags`

  Bitmask consisting of `ZipArchive::FL_OVERWRITE`, `ZipArchive::FL_ENC_GUESS`, `ZipArchive::FL_ENC_UTF_8`, `ZipArchive::FL_ENC_CP437`. The behaviour of these constants is described on the ZIP constants page.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL zip 1.18.0 | `flags` was added.

### Examples

Example #1 Add an entry to a new archive

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

Example #2 Add file to a directory inside an archive

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->addFromString('dir/test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::addGlob

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL zip >= 1.9.0)

ZipArchive::addGlob — Add files from a directory by glob pattern

### Description

public ZipArchive::addGlob(string `$pattern`, int `$flags` = 0, array `$options` = []): array|false

Add files from a directory which match the glob `pattern`.

> Note: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames.

### Parameters

`pattern`

  A glob() pattern against which files will be matched.

`flags`

  A bit mask of `glob()` flags.

`options`

  An associative array of options. Available options are:

  - `"add_path"`

    Prefix to prepend when translating to the local path of the file within the archive. This is applied after any remove operations defined by the `"remove_path"` or `"remove_all_path"` options.

  - `"remove_path"`

    Prefix to remove from matching file paths before adding to the archive.

  - `"remove_all_path"`

    `true` to use the file name only and add to the root of the archive.

  - `"flags"`

    Bitmask consisting of `ZipArchive::FL_OVERWRITE`, `ZipArchive::FL_ENC_GUESS`, `ZipArchive::FL_ENC_UTF_8`, `ZipArchive::FL_ENC_CP437`, `ZipArchive::FL_OPEN_FILE_NOW`. The behaviour of these constants is described on the ZIP constants page.

  - `"comp_method"`

    Compression method, one of the `ZipArchive::CM_*` constants.

  - `"comp_flags"`

    Compression level.

  - `"enc_method"`

    Encryption method, one of the `ZipArchive::EM_*` constants.

  - `"enc_password"`

    Password used for encryption.

### Return Values

An array of added files on success or `false` on failure

### Changelog

Version | Description
--- | ---
8.0.0, PECL zip 1.18.0 | `"flags"` in `options` was added.
8.0.0, PECL zip 1.18.1 | `"comp_method"`, `"comp_flags"`, `"enc_method"` and `"enc_password"` in `options` were added.
8.3.0, PECL zip 1.22.1 | `ZipArchive::FL_OPEN_FILE_NOW` was added.

### Examples

Example #1 ZipArchive::addGlob() example

Add all php scripts and text files from current working directory

`<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
printf('Failed with code %d', $ret);
} else {
$options = array('add_path' => 'sources/', 'remove_all_path' => TRUE);
$zip->addGlob('*.{php,txt}', GLOB_BRACE, $options);
$zip->close();
}
?>`

### See Also

- ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
- ZipArchive::addPattern() - Add files from a directory by PCRE pattern

# ZipArchive::addPattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL zip >= 1.9.0)

ZipArchive::addPattern — Add files from a directory by PCRE pattern

### Description

public ZipArchive::addPattern(string `$pattern`, string `$path` = ".", array `$options` = []): array|false

Add files from a directory which match the regular expression `pattern`. The operation is not recursive. The pattern will be matched against the file name only.

### Parameters

`pattern`

  A PCRE pattern against which files will be matched.

`path`

  The directory that will be scanned. Defaults to the current working directory.

`options`

  An associative array of options accepted by ZipArchive::addGlob().

### Return Values

An array of added files on success or `false` on failure

### Examples

Example #1 ZipArchive::addPattern() example

Add all php scripts and text files from current directory

`<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
printf('Failed with code %d', $ret);
} else {
$directory = realpath('.');
$options = array('add_path' => 'sources/', 'remove_path' => $directory);
$zip->addPattern('/\.(?:php|txt)$/', $directory, $options);
$zip->close();
}
?>`

### See Also

- ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
- ZipArchive::addGlob() - Add files from a directory by glob pattern

# ZipArchive::clearError

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::clearError — Clear the status error message, system and/or zip messages

### Description

public ZipArchive::clearError(): void

Clear the status error message, system and/or zip messages.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- ZipArchive::getStatusString() - Returns the status error message, system and/or zip messages

# ZipArchive::close

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::close — Close the active archive (opened or newly created)

### Description

public ZipArchive::close(): bool

Close opened or created archive and save changes. This method is automatically called at the end of the script.

If the archive contains no files, the file is completely removed by default (no empty archive is written) according to the value of the `ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE` global flag.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ZipArchive::setArchiveFlag() - Set a global flag of a ZIP archive

# ZipArchive::count

(PHP 7 >= 7.2.0, PHP 8, PECL zip >= 1.15.0)

ZipArchive::count — Counts the number of files in the archive

### Description

public ZipArchive::count(): int

### Parameters

This function has no parameters.

### Return Values

Returns the number of files in the archive.

# ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — Delete an entry in the archive using its index

### Description

public ZipArchive::deleteIndex(int `$index`): bool

Delete an entry in the archive using its index.

### Parameters

`index`

  Index of the entry to delete.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Delete file from archive using its index

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->deleteIndex(2);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::deleteName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::deleteName — Delete an entry in the archive using its name

### Description

public ZipArchive::deleteName(string `$name`): bool

Delete an entry in the archive using its name.

### Parameters

`name`

  Name of the entry to delete.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Deleting a file and directory from an archive, using names

`<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
$zip->deleteName('testfromfile.php');
$zip->deleteName('testDir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::extractTo

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract the archive contents

### Description

public ZipArchive::extractTo(string `$pathto`, array|string|null `$files` = `null`): bool

Extract the complete archive or the given files to the specified destination.

Warning

The default permissions for extracted files and directories give the widest possible access. This can be restricted by setting the current umask, which can be changed using umask().

For security reasons, the original permissions are not restored. For an example of how to restore them, see the code sample on the ZipArchive::getExternalAttributesIndex() page.

### Parameters

`pathto`

  Location where to extract the files.

`files`

  The entries to extract. It accepts either a single entry name or an array of names.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Extract all entries

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

Example #2 Extract two entries

`<?php
$zip = new ZipArchive;
$res = $zip->open('test_im.zip');
if ($res === TRUE) {
$zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

### Notes

> Note:

> Windows NTFS file systems do not support some characters in filenames, namely `<|>*?":`. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

# ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

### Description

public ZipArchive::getArchiveComment(int `$flags` = 0): string|false

Returns the Zip archive comment.

### Parameters

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged comment is returned.

### Return Values

Returns the Zip archive comment or `false` on failure.

### Examples

Example #1 Dump an archive comment

`<?php
$zip = new ZipArchive;
$res = $zip->open('test_with_comment.zip');
if ($res === TRUE) {
var_dump($zip->getArchiveComment());
/* Or using the archive property */
var_dump($zip->comment);
} else {
echo 'failed, code:' . $res;
}
?>`

# ZipArchive::getArchiveFlag

(PHP >= 8.3.0, PECL zip >= 1.22.0)

ZipArchive::getArchiveFlag — Returns the value of a Zip archive global flag

### Description

public ZipArchive::getArchiveFlag(int `$flag`, int `$flags` = 0): int

Returns a Zip archive global flag value.

### Parameters

`flag`

  The global flag to retrieve, among `AFL_*` constants:

  - `ZipArchive::AFL_RDONLY`

  - `ZipArchive::AFL_IS_TORRENTZIP`

  - `ZipArchive::AFL_WANT_TORRENTZIP`

  - `ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE`

`flags`

  If `flags` is set to `ZipArchive::FL_UNCHANGED`, the original unchanged flag is returned.

### Return Values

Returns 1 if flag is set for archive, 0 if not, and -1 if an error occurred.

### Examples

Example #1 Test if archive is a torrentzip format

`<?php
$zip = new ZipArchive();
$res = $zip->open('test.zip');
if ($res === true) {
var_dump($zip->getArchiveFlag(ZipArchive::AFL_IS_TORRENTZIP));
} else {
echo 'Failed, code: ' . $res;
}
?>`

### See Also

- ZipArchive::setArchiveFlag() - Set a global flag of a ZIP archive

# ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

### Description

public ZipArchive::getCommentIndex(int `$index`, int `$flags` = 0): string|false

Returns the comment of an entry using the entry index.

### Parameters

`index`

  Index of the entry

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged comment is returned.

### Return Values

Returns the comment on success or `false` on failure.

### Examples

Example #1 Dump an entry comment

`<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentIndex(1));
} else {
echo 'failed, code:' . $res;
}
?>`

# ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

### Description

public ZipArchive::getCommentName(string `$name`, int `$flags` = 0): string|false

Returns the comment of an entry using the entry name.

### Parameters

`name`

  Name of the entry

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged comment is returned.

### Return Values

Returns the comment on success or `false` on failure.

### Examples

Example #1 Dump an entry comment

`<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentName('test/entry1.txt'));
} else {
echo 'failed, code:' . $res;
}
?>`

# ZipArchive::getExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index

### Description

public ZipArchive::getExternalAttributesIndex(
int `$index`,
int `&$opsys`,
int `&$attr`,
int `$flags` = 0
): bool

Retrieve the external attributes of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`opsys`

  On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

`attr`

  On success, receive the external attributes. Value depends on operating system.

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged attributes are returned.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example extract all the entries of a ZIP archive test.zip and set the Unix rights from external attributes.

Example #1 Extract all entries with Unix rights

`<?php
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
if ($zip->extractTo('.', $s['name'])) {
if ($zip->getExternalAttributesIndex($idx, $opsys, $attr)
&& $opsys==ZipArchive::OPSYS_UNIX) {
chmod($s['name'], ($attr >> 16) & 0777);
}
}
}
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>`

# ZipArchive::getExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name

### Description

public ZipArchive::getExternalAttributesName(
string `$name`,
int `&$opsys`,
int `&$attr`,
int `$flags` = 0
): bool

Retrieve the external attributes of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`opsys`

  On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

`attr`

  On success, receive the external attributes. Value depends on operating system.

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged attributes are returned.

### Return Values

Returns `true` on success or `false` on failure.

# ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getFromIndex — Returns the entry contents using its index

### Description

public ZipArchive::getFromIndex(int `$index`, int `$len` = 0, int `$flags` = 0): string|false

Returns the entry contents using its index.

### Parameters

`index`

  Index of the entry

`len`

  The length to be read from the entry. If `0`, then the entire entry is read.

`flags`

  The flags to use to open the archive. the following values may be ORed to it.

  - `ZipArchive::FL_UNCHANGED`

  - `ZipArchive::FL_COMPRESSED`

### Return Values

Returns the contents of the entry on success or `false` on failure.

### Examples

Example #1 Get the file contents

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
echo $zip->getFromIndex(2);
$zip->close();
} else {
echo 'failed';
}
?>`

### See Also

- ZipArchive::getFromName() - Returns the entry contents using its name

# ZipArchive::getFromName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

### Description

public ZipArchive::getFromName(string `$name`, int `$len` = 0, int `$flags` = 0): string|false

Returns the entry contents using its name.

### Parameters

`name`

  Name of the entry

`len`

  The length to be read from the entry. If `0`, then the entire entry is read.

`flags`

  The flags to use to find the entry. The following values may be ORed.

  - `ZipArchive::FL_UNCHANGED`

  - `ZipArchive::FL_COMPRESSED`

  - `ZipArchive::FL_NOCASE`

### Return Values

Returns the contents of the entry on success or `false` on failure.

### Examples

Example #1 Get the file contents

`<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
echo $zip->getFromName('testfromfile.php');
$zip->close();
} else {
echo 'failed';
}
?>`

Example #2 Convert an image from a zip entry

`<?php
$z = new ZipArchive();
if ($z->open(dirname(__FILE__) . '/test_im.zip')) {
$im_string = $z->getFromName("pear_item.gif");
$im = imagecreatefromstring($im_string);
imagepng($im, 'b.png');
}
?>`

### See Also

- ZipArchive::getFromIndex() - Returns the entry contents using its index

# ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

### Description

public ZipArchive::getNameIndex(int `$index`, int `$flags` = 0): string|false

Returns the name of an entry using its index.

### Parameters

`index`

  Index of the entry.

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged name is returned.

### Return Values

Returns the name on success or `false` on failure.

### Examples

Example #1 ZipArchive::getNameIndex() example

`<?php
if ($zip->open('test.zip') == TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
// ...
}
}
?>`

# ZipArchive::getStatusString

(PHP 5 >= 5.2.7, PHP 7, PHP 8)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

### Description

public ZipArchive::getStatusString(): string

Returns the status error message, system and/or zip messages.

### Parameters

This function has no parameters.

### Return Values

Returns a string with the status message.

### Changelog

Version | Description
--- | ---
8.0.0, PECL zip 1.18.0 | This method can be called on closed archive.
8.0.0, PECL zip 1.18.0 | This method no longer returns `false` on failure.

# ZipArchive::getStream

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)

### Description

public ZipArchive::getStream(string `$name`): resource|false

Get a file handler to the entry defined by its name. For now, it only supports read operations.

### Parameters

`name`

  The name of the entry to use.

### Return Values

Returns a file pointer (resource) on success or `false` on failure.

### Examples

Example #1 Get the entry contents with fread() and store it

`<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStream('test');
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
fclose($fp);
file_put_contents('t',$contents);
echo "done.\n";
}
?>`

Example #2 Same as the previous example but with fopen() and the zip stream wrapper

`<?php
$contents = '';
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
exit("cannot open\n");
}
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
echo "$contents\n";
fclose($fp);
echo "done.\n";
?>`

Example #3 Stream wrapper and image, can be used with the xml function as well

`<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>`

### See Also

- ZipArchive::getStreamIndex() - Get a file handler to the entry defined by its index (read only)
- ZipArchive::getStreamName() - Get a file handler to the entry defined by its name (read only)
- Compression Streams

# ZipArchive::getStreamIndex

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)

### Description

public ZipArchive::getStreamIndex(int `$index`, int `$flags` = 0): resource|false

Get a file handler to the entry defined by its index. For now, it only supports read operations.

### Parameters

`index`

  Index of the entry

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged stream is returned.

### Return Values

Returns a file pointer (resource) on success or `false` on failure.

### Examples

Example #1 Get the entry contents with fread() and store it

`<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStreamIndex(1, ZipArchive::FL_UNCHANGED);
if(!$fp) die($z->getStatusString());
echo stream_get_contents($fp);
fclose($fp);
}
?>`

### See Also

- ZipArchive::getStreamName() - Get a file handler to the entry defined by its name (read only)

# ZipArchive::getStreamName

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)

### Description

public ZipArchive::getStreamName(string `$name`, int `$flags` = 0): resource|false

Get a file handler to the entry defined by its name. For now, it only supports read operations.

### Parameters

`name`

  The name of the entry to use.

`flags`

  If flags is set to `ZipArchive::FL_UNCHANGED`, the original unchanged stream is returned.

### Return Values

Returns a file pointer (resource) on success or `false` on failure.

### Examples

Example #1 Get the entry contents with fread() and store it

`<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStreamName('test', ZipArchive::FL_UNCHANGED);
if(!$fp) die($z->getStatusString());
echo stream_get_contents($fp);
fclose($fp);
}
?>`

### See Also

- ZipArchive::getStreamIndex() - Get a file handler to the entry defined by its index (read only)

# ZipArchive::isCompressionMethodSupported

(PHP >= 8.0.0, PECL zip >= 1.19.0)

ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip

### Description

public static ZipArchive::isCompressionMethodSupported(int `$method`, bool `$enc` = `true`): bool

Check if a compression method is supported by libzip.

### Parameters

`method`

  The compression method, one of the `ZipArchive::CM_*` constants.

`enc`

  If `true` check for compression, else check for decompression.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.7.0.

### See Also

- ZipArchive::setCompressionIndex() - Set the compression method of an entry defined by its index
- ZipArchive::setCompressionName() - Set the compression method of an entry defined by its name

# ZipArchive::isEncryptionMethodSupported

(PHP >= 8.0.0, PECL zip >= 1.19.0)

ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip

### Description

public static ZipArchive::isEncryptionMethodSupported(int `$method`, bool `$enc` = `true`): bool

Check if a compression method is supported by libzip.

### Parameters

`method`

  The encryption method, one of the `ZipArchive::EM_*` constants.

`enc`

  If `true` check for encryption, else check for decryption.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.7.0.

### See Also

- ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index
- ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

# ZipArchive::locateName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

### Description

public ZipArchive::locateName(string `$name`, int `$flags` = 0): int|false

Locates an entry using its name.

### Parameters

`name`

  The name of the entry to look up

`flags`

  The flags are specified by ORing the following values, or 0 for none of them.

  - `ZipArchive::FL_NOCASE`

  - `ZipArchive::FL_NODIR`

### Return Values

Returns the index of the entry on success or `false` on failure.

### Examples

Example #1 Create an archive and then use it with ZipArchive::locateName()

`<?php
$file = 'testlocate.zip';
$zip = new ZipArchive;
if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {
exit('failed');
}
$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');
if ($zip->status !== ZipArchive::ER_OK) {
echo "failed to write zip\n";
}
$zip->close();
if ($zip->open($file) !== TRUE) {
exit('failed');
}
echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZipArchive::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR) . "\n";
$zip->close();
?>`

The above example will output:

    0

    1
    2

# ZipArchive::open

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

### Description

public ZipArchive::open(string `$filename`, int `$flags` = 0): bool|int

Opens a new or existing zip archive for reading, writing or modifying.

Since libzip 1.6.0, an empty file is not a valid archive any longer.

### Parameters

`filename`

  The file name of the ZIP archive to open.

`flags`

  The mode to use to open the archive.

  - `ZipArchive::OVERWRITE`

  - `ZipArchive::CREATE`

  - `ZipArchive::RDONLY`

  - `ZipArchive::EXCL`

  - `ZipArchive::CHECKCONS`

### Return Values

Returns `true` on success, `false` or one of the following error codes on error:

`ZipArchive::ER_EXISTS`
  File already exists.
`ZipArchive::ER_INCONS`
  Zip archive inconsistent.
`ZipArchive::ER_INVAL`
  Invalid argument.
`ZipArchive::ER_MEMORY`
  Malloc failure.
`ZipArchive::ER_NOENT`
  No such file.
`ZipArchive::ER_NOZIP`
  Not a zip archive.
`ZipArchive::ER_OPEN`
  Can't open file.
`ZipArchive::ER_READ`
  Read error.
`ZipArchive::ER_SEEK`
  Seek error.

### Examples

Example #1 Open and extract

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
echo 'ok';
$zip->extractTo('test');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>`

Example #2 Create an archive

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

Example #3 Create an temporary archive

`<?php
$name = tempnam(sys_get_temp_dir(), "FOO");
$zip = new ZipArchive;
$res = $zip->open($name, ZipArchive::OVERWRITE); /* truncate as empty file is not valid */
if ($res === TRUE) {
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::registerCancelCallback

(PHP >= 8.0.0, PECL zip >= 1.17.0)

ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.

### Description

public ZipArchive::registerCancelCallback(callable `$callback`): bool

Register a `callback` function to allow cancellation during archive close.

### Parameters

`callback`

  If this function return 0 operation will continue, other value it will be cancelled.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example creates a ZIP file archive php.zip and cancel operation on some run condition.

Example #1 Archive a file

`<?php
$zip = new ZipArchive();
if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
$zip->addFile(PHP_BINARY, 'php');
$zip->registerCancelCallback(function () {
return ($someruncondition ? -1 : 0);
});
$zip->close();
}`

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.6.0.

### See Also

- ZipArchive::registerProgressCallback() - Register a callback to provide updates during archive close.

# ZipArchive::registerProgressCallback

(PHP >= 8.0.0, PECL zip >= 1.17.0)

ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.

### Description

public ZipArchive::registerProgressCallback(float `$rate`, callable `$callback`): bool

Register a `callback` function to provide updates during archive close.

### Parameters

`rate`

  Change between each call of the callback (from 0.0 to 1.0).

`callback`

  This function will receive the current `state` as a float (from 0.0 to 1.0).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example creates a ZIP file archive php.zip and show progression.

Example #1 Archive a file

`$zip = new ZipArchive();
if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
$zip->addFile(PHP_BINARY, 'php');
$zip->registerProgressCallback(0.05, function ($r) {
printf("%d%%\n", $r * 100);
});
$zip->close();
}`

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.3.0.

### See Also

- ZipArchive::registerCancelCallback() - Register a callback to allow cancellation during archive close.

# ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

### Description

public ZipArchive::renameIndex(int `$index`, string `$new_name`): bool

Renames an entry defined by its index.

### Parameters

`index`

  Index of the entry to rename.

`new_name`

  New name.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Rename one entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->renameIndex(2,'newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>`

# ZipArchive::renameName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

### Description

public ZipArchive::renameName(string `$name`, string `$new_name`): bool

Renames an entry defined by its name.

### Parameters

`name`

  Name of the entry to rename.

`new_name`

  New name.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Rename one entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->renameName('currentname.txt','newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>`

# ZipArchive::replaceFile

(PHP >= 8.0.0, PECL zip >= 1.18.0)

ZipArchive::replaceFile — Replace file in ZIP archive with a given path

### Description

public ZipArchive::replaceFile(
string `$filepath`,
int `$index`,
int `$start` = 0,
int `$length` = `ZipArchive::LENGTH_TO_END`,
int `$flags` = 0
): bool

Replace file in ZIP archive with a given path.

> Note: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames.

### Parameters

`filepath`

  The path to the file to add.

`index`

  The index of the file to be replaced, its name is unchanged.

`start`

  For partial copy, start position.

`length`

  For partial copy, length to be copied, if `ZipArchive::LENGTH_TO_END` (0) the file size is used, if `ZipArchive::LENGTH_UNCHECKED` the whole file is used (starting from `start`).

`flags`

  Bitmask consisting of `ZipArchive::FL_ENC_GUESS`, `ZipArchive::FL_ENC_UTF_8`, `ZipArchive::FL_ENC_CP437`, `ZipArchive::FL_OPEN_FILE_NOW`. The behaviour of these constants is described on the ZIP constants page.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0, PECL zip 1.22.1 | `ZipArchive::FL_OPEN_FILE_NOW` was added.
8.3.0, PECL zip 1.22.2 | `ZipArchive::LENGTH_TO_END` and `ZipArchive::LENGTH_UNCHECKED` were added.

### Examples

This example opens a ZIP file archive test.zip and replaces index 1 entry with /path/to/index.txt.

Example #1 Open and replace

`<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->replaceFile('/path/to/index.txt', 1);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

### See Also

- ZipArchive::addFile() - Adds a file to a ZIP archive from the given path

# ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

### Description

public ZipArchive::setArchiveComment(string `$comment`): bool

Set the comment of a ZIP archive.

### Parameters

`comment`

  The contents of the comment.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Create an archive and set a comment

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->setArchiveComment('new archive comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::setArchiveFlag

(PHP >= 8.3.0, PECL zip >= 1.22.0)

ZipArchive::setArchiveFlag — Set a global flag of a ZIP archive

### Description

public ZipArchive::setArchiveFlag(int `$flag`, int `$value`): bool

Set a global flag of a ZIP archive.

### Parameters

`flag`

  The global flag to change, among `AFL_*` constants.

  - `ZipArchive::AFL_WANT_TORRENTZIP`

  - `ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE`

`value`

  The new value of the flag.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Create a torrentzip archive

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->setArchiveFlag(ZipArchive::AFL_WANT_TORRENTZIP, 1);
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

### See Also

- ZipArchive::getArchiveFlag() - Returns the value of a Zip archive global flag

# ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

### Description

public ZipArchive::setCommentIndex(int `$index`, string `$comment`): bool

Set the comment of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`comment`

  The contents of the comment.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Open an archive and set a comment for an entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->setCommentIndex(2, 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

### Description

public ZipArchive::setCommentName(string `$name`, string `$comment`): bool

Set the comment of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`comment`

  The contents of the comment.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Open an archive and set a comment for an entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->setCommentName('entry1.txt', 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::setCompressionIndex

(PHP 7, PHP 8, PECL zip >= 1.13.0)

ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index

### Description

public ZipArchive::setCompressionIndex(int `$index`, int `$method`, int `$compflags` = 0): bool

Set the compression method of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`method`

  The compression method, one of the `ZipArchive::CM_*` constants.

`compflags`

  Compression level.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Add files with different compression methods to an archive

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionIndex(0, ZipArchive::CM_STORE);
$zip->setCompressionIndex(1, ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::setCompressionName

(PHP 7, PHP 8, PECL zip >= 1.13.0)

ZipArchive::setCompressionName — Set the compression method of an entry defined by its name

### Description

public ZipArchive::setCompressionName(string `$name`, int `$method`, int `$compflags` = 0): bool

Set the compression method of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`method`

  The compression method, one of the `ZipArchive::CM_*` constants.

`compflags`

  Compression level.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Add files with different compression methods to an archive

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionName('foo', ZipArchive::CM_STORE);
$zip->setCompressionName('bar', ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

Example #2 Add file and set compression method

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFile('foo.jpg', 'bar.jpg');
$zip->setCompressionName('bar.jpg', ZipArchive::CM_XZ);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>`

# ZipArchive::setEncryptionIndex

(PHP >= 7.2.0, PHP 8, PECL zip >= 1.14.0)

ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index

### Description

public ZipArchive::setEncryptionIndex(int `$index`, int `$method`, #[\SensitiveParameter] ?string `$password` = `null`): bool

Set the encryption method of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`method`

  The encryption method defined by one of the ZipArchive::EM_ constants.

`password`

  Optional password, default used when missing.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `password` is now nullable.

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.2.0.

### See Also

- ZipArchive::setPassword() - Set the password for the active archive
- ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

# ZipArchive::setEncryptionName

(PHP >= 7.2.0, PHP 8, PECL zip >= 1.14.0)

ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name

### Description

public ZipArchive::setEncryptionName(string `$name`, int `$method`, #[\SensitiveParameter] ?string `$password` = `null`): bool

Set the encryption method of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`method`

  The encryption method defined by one of the ZipArchive::EM_ constants.

`password`

  Optional password, default used when missing.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `password` is now nullable.

### Examples

This example creates a ZIP file archive test.zip and add the file test.txt encrypted using the AES 256 method.

Example #1 Archive and encrypt a file

`<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->setPassword('secret');
$zip->addFile('text.txt');
$zip->setEncryptionName('text.txt', ZipArchive::EM_AES_256);
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>`

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.2.0.

### See Also

- ZipArchive::setPassword() - Set the password for the active archive
- ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index

# ZipArchive::setExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index

### Description

public ZipArchive::setExternalAttributesIndex(
int `$index`,
int `$opsys`,
int `$attr`,
int `$flags` = 0
): bool

Set the external attributes of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`opsys`

  The operating system code defined by one of the ZipArchive::OPSYS_ constants.

`attr`

  The external attributes. Value depends on operating system.

`flags`

  Optional flags. Currently unused.

### Return Values

Returns `true` on success or `false` on failure.

# ZipArchive::setExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name

### Description

public ZipArchive::setExternalAttributesName(
string `$name`,
int `$opsys`,
int `$attr`,
int `$flags` = 0
): bool

Set the external attributes of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`opsys`

  The operating system code defined by one of the ZipArchive::OPSYS_ constants.

`attr`

  The external attributes. Value depends on operating system.

`flags`

  Optional flags. Currently unused.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example opens a ZIP file archive test.zip and add the file test.txt with its Unix rights as external attributes.

Example #1 Archive a file, with its Unix rights

`<?php
$zip = new ZipArchive();
$stat = stat($filename='test.txt');
if (is_array($stat) && $zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile($filename);
$zip->setExternalAttributesName($filename, ZipArchive::OPSYS_UNIX, $stat['mode'] << 16);
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>`

# ZipArchive::setMtimeIndex

(PHP >= 8.0.0, PECL zip >= 1.16.0)

ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index

### Description

public ZipArchive::setMtimeIndex(int `$index`, int `$timestamp`, int `$flags` = 0): bool

Set the modification time of an entry defined by its index.

### Parameters

`index`

  Index of the entry.

`timestamp`

  The modification time (unix timestamp) of the file.

`flags`

  Optional flags, unused for now.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example creates a ZIP file archive test.zip and add the file test.txt with its modification date.

Example #1 Archive a file

`<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile('text.txt');
$zip->setMtimeIndex(0, mktime(0,0,0,12,25,2019));
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>`

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.0.0.

### See Also

- ZipArchive::setMtimeName() - Set the modification time of an entry defined by its name

# ZipArchive::setMtimeName

(PHP >= 8.0.0, PECL zip >= 1.16.0)

ZipArchive::setMtimeName — Set the modification time of an entry defined by its name

### Description

public ZipArchive::setMtimeName(string `$name`, int `$timestamp`, int `$flags` = 0): bool

Set the modification time of an entry defined by its name.

### Parameters

`name`

  Name of the entry.

`timestamp`

  The modification time (unix timestamp) of the file.

`flags`

  Optional flags, unused for now.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

This example creates a ZIP file archive test.zip and add the file test.txt with its modification date.

Example #1 Archive a file

`<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile('text.txt');
$zip->setMtimeName('text.txt', mktime(0,0,0,12,25,2019));
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>`

### Notes

> Note:

> This function is only available if built against libzip ≥ 1.0.0.

### See Also

- ZipArchive::setMtimeIndex() - Set the modification time of an entry defined by its index

# ZipArchive::setPassword

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setPassword — Set the password for the active archive

### Description

public ZipArchive::setPassword(#[\SensitiveParameter] string `$password`): bool

Sets the password for the active archive.

### Parameters

`password`

  The password to be used for the archive.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note:

> As of PHP 7.2.0 and libzip 1.2.0 the password is used to decompress the archive, and is also the default password for ZipArchive::setEncryptionName() and ZipArchive::setEncryptionIndex(). Formerly, this function only set the password to be used to decompress the archive; it did not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

### See Also

- ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index
- ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

# ZipArchive::statIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index

### Description

public ZipArchive::statIndex(int `$index`, int `$flags` = 0): array|false

The function obtains information about the entry defined by its index.

### Parameters

`index`

  Index of the entry

`flags`

  `ZipArchive::FL_UNCHANGED` may be ORed to it to request information about the original file in the archive, ignoring any changes made.

### Return Values

Returns an array containing the entry details or `false` on failure.

### Examples

Example #1 Dump the stat info of an entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
print_r($zip->statIndex(3));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>`

The above example will output something similar to:

    Array
    (
        [name] => foobar/baz
        [index] => 3
        [crc] => 499465816
        [size] => 27
        [mtime] => 1123164748
        [comp_size] => 24
        [comp_method] => 8
    )

# ZipArchive::statName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name

### Description

public ZipArchive::statName(string `$name`, int `$flags` = 0): array|false

The function obtains information about the entry defined by its name.

### Parameters

`name`

  Name of the entry

`flags`

  The flags argument specifies how the name lookup should be done. Also, `ZipArchive::FL_UNCHANGED` may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  - `ZipArchive::FL_NOCASE`

  - `ZipArchive::FL_NODIR`

  - `ZipArchive::FL_UNCHANGED`

### Return Values

Returns an array containing the entry details or `false` on failure.

### Examples

Example #1 Dump the stat info of an entry

`<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
print_r($zip->statName('foobar/baz'));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>`

The above example will output something similar to:

    Array
    (
        [name] => foobar/baz
        [index] => 3
        [crc] => 499465816
        [size] => 27
        [mtime] => 1123164748
        [comp_size] => 24
        [comp_method] => 8
    )

# ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

### Description

public ZipArchive::unchangeAll(): bool

Undo all changes done in the archive.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

# ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive

### Description

public ZipArchive::unchangeArchive(): bool

Revert all global changes to the archive. For now, this only reverts archive comment changes.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

# ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

### Description

public ZipArchive::unchangeIndex(int `$index`): bool

Revert all changes done to an entry at the given index.

### Parameters

`index`

  Index of the entry.

### Return Values

Returns `true` on success or `false` on failure.

# ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name

### Description

public ZipArchive::unchangeName(string `$name`): bool

Revert all changes done to an entry.

### Parameters

`name`

  Name of the entry.

### Return Values

Returns `true` on success or `false` on failure.

## Table of Contents

- ZipArchive::addEmptyDir — Add a new directory
- ZipArchive::addFile — Adds a file to a ZIP archive from the given path
- ZipArchive::addFromString — Add a file to a ZIP archive using its contents
- ZipArchive::addGlob — Add files from a directory by glob pattern
- ZipArchive::addPattern — Add files from a directory by PCRE pattern
- ZipArchive::clearError — Clear the status error message, system and/or zip messages
- ZipArchive::close — Close the active archive (opened or newly created)
- ZipArchive::count — Counts the number of files in the archive
- ZipArchive::deleteIndex — Delete an entry in the archive using its index
- ZipArchive::deleteName — Delete an entry in the archive using its name
- ZipArchive::extractTo — Extract the archive contents
- ZipArchive::getArchiveComment — Returns the Zip archive comment
- ZipArchive::getArchiveFlag — Returns the value of a Zip archive global flag
- ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
- ZipArchive::getCommentName — Returns the comment of an entry using the entry name
- ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
- ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
- ZipArchive::getFromIndex — Returns the entry contents using its index
- ZipArchive::getFromName — Returns the entry contents using its name
- ZipArchive::getNameIndex — Returns the name of an entry using its index
- ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
- ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)
- ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)
- ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)
- ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip
- ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip
- ZipArchive::locateName — Returns the index of the entry in the archive
- ZipArchive::open — Open a ZIP file archive
- ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.
- ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.
- ZipArchive::renameIndex — Renames an entry defined by its index
- ZipArchive::renameName — Renames an entry defined by its name
- ZipArchive::replaceFile — Replace file in ZIP archive with a given path
- ZipArchive::setArchiveComment — Set the comment of a ZIP archive
- ZipArchive::setArchiveFlag — Set a global flag of a ZIP archive
- ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
- ZipArchive::setCommentName — Set the comment of an entry defined by its name
- ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index
- ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
- ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index
- ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name
- ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
- ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
- ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index
- ZipArchive::setMtimeName — Set the modification time of an entry defined by its name
- ZipArchive::setPassword — Set the password for the active archive
- ZipArchive::statIndex — Get the details of an entry defined by its index
- ZipArchive::statName — Get the details of an entry defined by its name
- ZipArchive::unchangeAll — Undo all changes done in the archive
- ZipArchive::unchangeArchive — Revert all global changes done in the archive
- ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
- ZipArchive::unchangeName — Revert all changes done to an entry with the given name

# Zip Functions

Warning

The procedural API is deprecated as of PHP 8.0.0. ZipArchive should be used instead.

# zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_close — Close a ZIP file archive

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_close(resource `$zip`): void

Closes the given ZIP file archive.

### Parameters

`zip`

  A ZIP file previously opened with zip_open().

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::close().

### See Also

- zip_open() - Open a ZIP file archive
- zip_read() - Read next entry in a ZIP file archive

# zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_close — Close a directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_close(resource `$zip_entry`): bool

Closes the specified directory entry.

### Parameters

`zip_entry`

  A directory entry previously opened zip_entry_open().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API.

### See Also

- zip_entry_open() - Open a directory entry for reading
- zip_entry_read() - Read from an open directory entry

# zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_compressedsize(resource `$zip_entry`): int|false

Returns the compressed size of the specified directory entry.

### Parameters

`zip_entry`

  A directory entry returned by zip_read().

### Return Values

The compressed size, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::statIndex().

### See Also

- zip_open() - Open a ZIP file archive
- zip_read() - Read next entry in a ZIP file archive

# zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_compressionmethod(resource `$zip_entry`): string|false

Returns the compression method of the directory entry specified by `zip_entry`.

### Parameters

`zip_entry`

  A directory entry returned by zip_read().

### Return Values

The compression method, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::statIndex().

### See Also

- zip_open() - Open a ZIP file archive
- zip_read() - Read next entry in a ZIP file archive

# zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_filesize(resource `$zip_entry`): int|false

Returns the actual size of the specified directory entry.

### Parameters

`zip_entry`

  A directory entry returned by zip_read().

### Return Values

The size of the directory entry, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::statIndex().

### See Also

- zip_open() - Open a ZIP file archive
- zip_read() - Read next entry in a ZIP file archive

# zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_name — Retrieve the name of a directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_name(resource `$zip_entry`): string|false

Returns the name of the specified directory entry.

### Parameters

`zip_entry`

  A directory entry returned by zip_read().

### Return Values

The name of the directory entry, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::statIndex().

### See Also

- zip_open() - Open a ZIP file archive
- zip_read() - Read next entry in a ZIP file archive

# zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_open(resource `$zip_dp`, resource `$zip_entry`, string `$mode` = "rb"): bool

Opens a directory entry in a zip file for reading.

### Parameters

`zip_dp`

  A valid resource handle returned by zip_open().

`zip_entry`

  A directory entry returned by zip_read().

`mode`

  Any of the modes specified in the documentation of fopen().

  > Note:

  > Currently, `mode` is ignored and is always `"rb"`. This is due to the fact that zip support in PHP is read only access.

### Return Values

Returns `true` on success or `false` on failure.

> Note:

> Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API.

### See Also

- zip_entry_close() - Close a directory entry
- zip_entry_read() - Read from an open directory entry

# zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_entry_read(resource `$zip_entry`, int `$len` = 1024): string|false

Reads from an open directory entry.

### Parameters

`zip_entry`

  A directory entry returned by zip_read().

`len`

  The number of bytes to return.

  > Note:

  > This should be the uncompressed length you wish to read.

### Return Values

Returns the data read, empty string on end of a file, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::getFromIndex().

### See Also

- zip_entry_open() - Open a directory entry for reading
- zip_entry_close() - Close a directory entry
- zip_entry_filesize() - Retrieve the actual file size of a directory entry

# zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_open(string `$filename`): resource|int|false

Opens a new zip archive for reading.

### Parameters

`filename`

  The file name of the ZIP archive to open.

### Return Values

Returns a resource handle for later use with zip_read() and zip_close() or returns either `false` or the number of error if `filename` does not exist or in case of other error.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::open().

### See Also

- zip_read() - Read next entry in a ZIP file archive
- zip_close() - Close a ZIP file archive

# zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
zip_read(resource `$zip`): resource|false

Reads the next entry in a zip file archive.

### Parameters

`zip`

  A ZIP file previously opened with zip_open().

### Return Values

Returns a directory entry resource for later use with the `zip_entry_...` functions, or `false` if there are no more entries to read, or an error code if an error occurred.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is deprecated in favor of the Object API, see ZipArchive::statIndex().

### See Also

- zip_open() - Open a ZIP file archive
- zip_close() - Close a ZIP file archive
- zip_entry_open() - Open a directory entry for reading
- zip_entry_read() - Read from an open directory entry

## Table of Contents

- zip_close — Close a ZIP file archive
- zip_entry_close — Close a directory entry
- zip_entry_compressedsize — Retrieve the compressed size of a directory entry
- zip_entry_compressionmethod — Retrieve the compression method of a directory entry
- zip_entry_filesize — Retrieve the actual file size of a directory entry
- zip_entry_name — Retrieve the name of a directory entry
- zip_entry_open — Open a directory entry for reading
- zip_entry_read — Read from an open directory entry
- zip_open — Open a ZIP file archive
- zip_read — Read next entry in a ZIP file archive

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- Examples
- ZipArchive — The ZipArchive class
  - ZipArchive::addEmptyDir — Add a new directory
  - ZipArchive::addFile — Adds a file to a ZIP archive from the given path
  - ZipArchive::addFromString — Add a file to a ZIP archive using its contents
  - ZipArchive::addGlob — Add files from a directory by glob pattern
  - ZipArchive::addPattern — Add files from a directory by PCRE pattern
  - ZipArchive::clearError — Clear the status error message, system and/or zip messages
  - ZipArchive::close — Close the active archive (opened or newly created)
  - ZipArchive::count — Counts the number of files in the archive
  - ZipArchive::deleteIndex — Delete an entry in the archive using its index
  - ZipArchive::deleteName — Delete an entry in the archive using its name
  - ZipArchive::extractTo — Extract the archive contents
  - ZipArchive::getArchiveComment — Returns the Zip archive comment
  - ZipArchive::getArchiveFlag — Returns the value of a Zip archive global flag
  - ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
  - ZipArchive::getCommentName — Returns the comment of an entry using the entry name
  - ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
  - ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
  - ZipArchive::getFromIndex — Returns the entry contents using its index
  - ZipArchive::getFromName — Returns the entry contents using its name
  - ZipArchive::getNameIndex — Returns the name of an entry using its index
  - ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
  - ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)
  - ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)
  - ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)
  - ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip
  - ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip
  - ZipArchive::locateName — Returns the index of the entry in the archive
  - ZipArchive::open — Open a ZIP file archive
  - ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.
  - ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.
  - ZipArchive::renameIndex — Renames an entry defined by its index
  - ZipArchive::renameName — Renames an entry defined by its name
  - ZipArchive::replaceFile — Replace file in ZIP archive with a given path
  - ZipArchive::setArchiveComment — Set the comment of a ZIP archive
  - ZipArchive::setArchiveFlag — Set a global flag of a ZIP archive
  - ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
  - ZipArchive::setCommentName — Set the comment of an entry defined by its name
  - ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index
  - ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
  - ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index
  - ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name
  - ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
  - ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
  - ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index
  - ZipArchive::setMtimeName — Set the modification time of an entry defined by its name
  - ZipArchive::setPassword — Set the password for the active archive
  - ZipArchive::statIndex — Get the details of an entry defined by its index
  - ZipArchive::statName — Get the details of an entry defined by its name
  - ZipArchive::unchangeAll — Undo all changes done in the archive
  - ZipArchive::unchangeArchive — Revert all global changes done in the archive
  - ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
  - ZipArchive::unchangeName — Revert all changes done to an entry with the given name
- Zip Functions
  - zip_close — Close a ZIP file archive
  - zip_entry_close — Close a directory entry
  - zip_entry_compressedsize — Retrieve the compressed size of a directory entry
  - zip_entry_compressionmethod — Retrieve the compression method of a directory entry
  - zip_entry_filesize — Retrieve the actual file size of a directory entry
  - zip_entry_name — Retrieve the name of a directory entry
  - zip_entry_open — Open a directory entry for reading
  - zip_entry_read — Read from an open directory entry
  - zip_open — Open a ZIP file archive
  - zip_read — Read next entry in a ZIP file archive

# Zlib Compression

# Introduction

This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).

> Note:

> PHP comes with a fopen-wrapper for .gz-files. More information is available in the section about zlib://.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. As of PHP 8.4.0, the minimum zlib version required is 1.2.11. Prior to PHP 8.4.0, the minimum zlib version required was 1.2.0.4.

## Installation

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

Zlib Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
zlib.output_compression | "0" | `INI_ALL` |
zlib.output_compression_level | "-1" | `INI_ALL` |
zlib.output_handler | "" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`zlib.output_compression` bool/int

  Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output. In runtime, it can be set only before sending any output.

  This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

  > Note:

  > output_handler must be empty if this is set 'On' ! Instead you must use `zlib.output_handler`.

`zlib.output_compression_level` int

  Compression level used for transparent output compression. Specify a value between 0 (no compression) to 9 (most compression). The default value, -1, lets the server decide which level to use.

`zlib.output_handler` string

  You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

## Resource Types

This extension defines a file pointer resource returned by gzopen(). Prior to PHP 8.0.0, `zlib.deflate` and `zlib.inflate` resources were also defined.

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

`FORCE_GZIP` (int)
`FORCE_DEFLATE` (int)
`ZLIB_ENCODING_RAW` (int)
  DEFLATE algorithm as per RFC 1951.
`ZLIB_ENCODING_DEFLATE` (int)
  ZLIB compression algorithm as per RFC 1950.
`ZLIB_ENCODING_GZIP` (int)
  GZIP algorithm as per RFC 1952.
`ZLIB_FILTERED` (int)
`ZLIB_HUFFMAN_ONLY` (int)
`ZLIB_FIXED` (int)
`ZLIB_RLE` (int)
`ZLIB_DEFAULT_STRATEGY` (int)
`ZLIB_BLOCK` (int)
`ZLIB_NO_FLUSH` (int)
`ZLIB_PARTIAL_FLUSH` (int)
`ZLIB_SYNC_FLUSH` (int)
`ZLIB_FULL_FLUSH` (int)
`ZLIB_FINISH` (int)
`ZLIB_VERSION` (string)
  `zlib` version number as a string.
`ZLIB_VERNUM` (int)
  `zlib` version number as an int.
`ZLIB_OK` (int)
  No errors or additional status information.
`ZLIB_STREAM_END` (int)
  Stream ended successfully.
`ZLIB_NEED_DICT` (int)
  Preset dictionary is needed.
`ZLIB_ERRNO` (int)
  File operation error.
`ZLIB_STREAM_ERROR` (int)
  Stream state is inconsistent or a parameter is invalid.
`ZLIB_DATA_ERROR` (int)
  Input data is corrupted.
`ZLIB_MEM_ERROR` (int)
  Insufficient memory.
`ZLIB_BUF_ERROR` (int)
  No progress is possible due to insufficient buffer space or unexpected ending of an input stream.
`ZLIB_VERSION_ERROR` (int)
  `zlib` library version is incompatible with the version assumed by the caller.

# Examples

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example #1 Small Zlib Example

`<?php
$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";
// open file for writing with maximum compression
$zp = gzopen($filename, "w9");
// write string to file
gzwrite($zp, $s);
// close file
gzclose($zp);
// open file for reading
$zp = gzopen($filename, "r");
// read 3 char
echo gzread($zp, 3);
// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);
echo "\n";
// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";
?>`

Example #2 Working with the incremental compression and decompression API

`<?php
// Perform GZIP compression:
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP);
$compressed = deflate_add($deflateContext, "Data to compress", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", more data", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", and even more data!", ZLIB_FINISH);
// Perform GZIP decompression:
$inflateContext = inflate_init(ZLIB_ENCODING_GZIP);
$uncompressed = inflate_add($inflateContext, $compressed, ZLIB_NO_FLUSH);
$uncompressed .= inflate_add($inflateContext, NULL, ZLIB_FINISH);
echo $uncompressed;
?>`

The above example will output:

    Data to compress, more data, and even more data!

# Zlib Functions

# deflate_add

(PHP 7, PHP 8)

deflate_add — Incrementally deflate data

### Description

deflate_add(DeflateContext `$context`, string `$data`, int `$flush_mode` = `ZLIB_SYNC_FLUSH`): string|false

Incrementally deflates data in the specified context.

### Parameters

`context`

  A context created with deflate_init().

`data`

  A chunk of data to compress.

`flush_mode`

  One of `ZLIB_BLOCK`, `ZLIB_NO_FLUSH`, `ZLIB_PARTIAL_FLUSH`, `ZLIB_SYNC_FLUSH` (default), `ZLIB_FULL_FLUSH`, `ZLIB_FINISH`. Normally you will want to set `ZLIB_NO_FLUSH` to maximize compression, and `ZLIB_FINISH` to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

### Return Values

Returns a chunk of compressed data, or `false` on failure.

### Errors/Exceptions

If invalid arguments are given, an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` expects a DeflateContext instance now; previously, a resource was expected.

### See Also

- deflate_init() - Initialize an incremental deflate context

# deflate_init

(PHP 7, PHP 8)

deflate_init — Initialize an incremental deflate context

### Description

deflate_init(int `$encoding`, array|object `$options` = []): DeflateContext|false

Initializes an incremental deflate context using the specified `encoding`.

Note that the `window` option here only sets the window size of the algorithm, differently from the zlib filters where the same parameter also sets the encoding to use; the encoding must be set with the `encoding` parameter.

Limitation: there is currently no way to set the header information on a GZIP compressed stream, which are set as follows: GZIP signature (`\x1f\x8B`); compression method (`\x08` == DEFLATE); 6 zero bytes; the operating system set to the current system (`\x00` = Windows, `\x03` = Unix, etc.)

### Parameters

`encoding`

  One of the `ZLIB_ENCODING_*` constants.

`options`

  An associative array which may contain the following elements:

  level

    The compression level in range -1..9; defaults to -1.

  memory

    The compression memory level in range 1..9; defaults to 8.

  window

    The zlib window size (logarithmic) in range `8`..`15`; defaults to `15`. zlib changes a window size of `8` to `9`, and as of zlib 1.2.8 fails with a warning, if a window size of `8` is requested for `ZLIB_ENCODING_RAW` or `ZLIB_ENCODING_GZIP`.

  strategy

    One of `ZLIB_FILTERED`, `ZLIB_HUFFMAN_ONLY`, `ZLIB_RLE`, `ZLIB_FIXED` or `ZLIB_DEFAULT_STRATEGY` (the default).

  dictionary

    A string or an array of strings of the preset dictionary (default: no preset dictionary).

### Return Values

Returns a deflate context resource (`zlib.deflate`) on success, or `false` on failure.

### Errors/Exceptions

If an invalid option is passed to `options` or the context couldn't be created, an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a DeflateContext instance now; previously, a resource was returned.

### See Also

- deflate_add() - Incrementally deflate data
- inflate_init() - Initialize an incremental inflate context

# gzclose

(PHP 4, PHP 5, PHP 7, PHP 8)

gzclose — Close an open gz-file pointer

### Description

gzclose(resource `$stream`): bool

Closes the given gz-file pointer.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 gzclose() example

`<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>`

### See Also

- gzopen() - Open gz-file

# gzcompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

gzcompress — Compress a string

### Description

gzcompress(string `$data`, int `$level` = -1, int `$encoding` = `ZLIB_ENCODING_DEFLATE`): string|false

This function compresses the given string using the `ZLIB` data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

> Note:

> This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

### Parameters

`data`

  The data to compress.

`level`

  The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

  If -1 is used, the default compression of the zlib library is used which is 6.

`encoding`

  One of `ZLIB_ENCODING_*` constants.

### Return Values

The compressed string or `false` if an error occurred.

### Examples

Example #1 gzcompress() example

`<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>`

### See Also

- gzdeflate() - Deflate a string
- gzinflate() - Inflate a deflated string
- gzuncompress() - Uncompress a compressed string
- gzencode() - Create a gzip compressed string

# gzdecode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

gzdecode — Decodes a gzip compressed string

### Description

gzdecode(string `$data`, int `$max_length` = 0): string|false

This function returns a decoded version of the input `data`.

### Parameters

`data`

  The data to decode, encoded by gzencode().

`max_length`

  The maximum length of data to decode.

### Return Values

The decoded string, or or `false` on failure.

### Errors/Exceptions

In case of failure, an `E_WARNING` level error is issued.

### See Also

- gzencode() - Create a gzip compressed string

# gzdeflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzdeflate — Deflate a string

### Description

gzdeflate(string `$data`, int `$level` = -1, int `$encoding` = `ZLIB_ENCODING_RAW`): string|false

This function compresses the given string using the `DEFLATE` data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

### Parameters

`data`

  The data to deflate.

`level`

  The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

`encoding`

  One of `ZLIB_ENCODING_*` constants.

### Return Values

The deflated string or `false` if an error occurred.

### Examples

Example #1 gzdeflate() example

`<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>`

### See Also

- gzinflate() - Inflate a deflated string
- gzcompress() - Compress a string
- gzuncompress() - Uncompress a compressed string
- gzencode() - Create a gzip compressed string

# gzencode

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzencode — Create a gzip compressed string

### Description

gzencode(string `$data`, int `$level` = -1, int `$encoding` = `ZLIB_ENCODING_GZIP`): string|false

This function returns a compressed version of the input `data` compatible with the output of the gzip program.

For more information on the GZIP file format, see the document: » GZIP file format specification version 4.3 (RFC 1952).

### Parameters

`data`

  The data to encode.

`level`

  The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

`encoding`

  The encoding mode. Can be `FORCE_GZIP` (the default) or `FORCE_DEFLATE`.

  `FORCE_DEFLATE` generates RFC 1950 compliant output, consisting of a zlib header, the deflated data, and an Adler checksum.

### Return Values

The encoded string, or `false` if an error occurred.

### Examples

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Example #1 Creating a gzip file

`<?php
$data = file_get_contents("bigfile.txt");
$gzdata = gzencode($data, 9);
file_put_contents("bigfile.txt.gz", $gzdata);
?>`

### See Also

- gzdecode() - Decodes a gzip compressed string
- gzdeflate() - Deflate a string
- gzinflate() - Inflate a deflated string
- gzuncompress() - Uncompress a compressed string
- gzcompress() - Compress a string
- » ZLIB Compressed Data Format Specification (RFC 1950)

# gzeof

(PHP 4, PHP 5, PHP 7, PHP 8)

gzeof — Test for EOF on a gz-file pointer

### Description

gzeof(resource `$stream`): bool

Tests the given GZ file pointer for EOF.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

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

### Examples

Example #1 gzeof() example

`<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
echo gzgetc($gz);
}
gzclose($gz);
?>`

# gzfile

(PHP 4, PHP 5, PHP 7, PHP 8)

gzfile — Read entire gz-file into an array

### Description

gzfile(string `$filename`, bool `$use_include_path` = `false`): array|false

This function is identical to readgzfile(), except that it returns the file in an array.

### Parameters

`filename`

  The file name.

`use_include_path`
  If set to `true`, files in the include_path are searched for too.

### Return Values

An array containing the file, one line per cell, empty lines included, and with newlines still attached, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | `use_include_path` is now of type bool. Previously, it was of type int.

### Examples

Example #1 gzfile() example

`<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
echo $line;
}
?>`

### See Also

- readgzfile() - Output a gz-file
- gzopen() - Open gz-file

# gzgetc

(PHP 4, PHP 5, PHP 7, PHP 8)

gzgetc — Get character from gz-file pointer

### Description

gzgetc(resource `$stream`): string|false

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

The uncompressed character or `false` on EOF (unlike gzeof()).

### Examples

Example #1 gzgetc() example

`<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
echo gzgetc($gz);
}
gzclose($gz);
?>`

### See Also

- gzopen() - Open gz-file
- gzgets() - Get line from file pointer

# gzgets

(PHP 4, PHP 5, PHP 7, PHP 8)

gzgets — Get line from file pointer

### Description

gzgets(resource `$stream`, ?int `$length` = `null`): string|false

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

`length`

  The length of data to get.

### Return Values

The uncompressed string, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` is nullable now; previously, the default was `1024`.

### Examples

Example #1 gzgets() example

`<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
$buffer = gzgets($handle, 4096);
echo $buffer;
}
gzclose($handle);
?>`

### See Also

- gzopen() - Open gz-file
- gzgetc() - Get character from gz-file pointer
- gzwrite() - Binary-safe gz-file write

# gzgetss

(PHP 4, PHP 5, PHP 7)

gzgetss — Get line from gz-file pointer and strip HTML tags

Warning

This function has been DEPRECATED as of PHP 7.3.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

gzgetss(resource `$zp`, int `$length`, string `$allowable_tags` = ?): string

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

### Parameters

`zp`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

`length`

  The length of data to get.

`allowable_tags`

  You can use this optional parameter to specify tags which should not be stripped.

### Return Values

The uncompressed and stripped string, or `false` on error.

### Examples

Example #1 gzgetss() example

`<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
$buffer = gzgetss($handle, 4096);
echo $buffer;
}
gzclose($handle);
?>`

### See Also

- gzopen() - Open gz-file
- gzgets() - Get line from file pointer
- strip_tags() - Strip HTML and PHP tags from a string

# gzinflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzinflate — Inflate a deflated string

### Description

gzinflate(string `$data`, int `$max_length` = 0): string|false

This function inflates a deflated string.

### Parameters

`data`

  The data compressed by gzdeflate().

`max_length`

  The maximum length of decoded data.

### Return Values

The original uncompressed data or `false` on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input `data` or, unless `max_length` is `0`, more than the optional parameter `max_length`.

### Examples

Example #1 gzinflate() example

`<?php
$compressed = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>`

### See Also

- gzdeflate() - Deflate a string
- gzcompress() - Compress a string
- gzuncompress() - Uncompress a compressed string
- gzencode() - Create a gzip compressed string

# gzopen

(PHP 4, PHP 5, PHP 7, PHP 8)

gzopen — Open gz-file

### Description

gzopen(string `$filename`, string `$mode`, bool `$use_include_path` = `false`): resource|false

Opens a gzip (.gz) file for reading or writing.

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

### Parameters

`filename`

  The file name.

`mode`

  As in fopen() (`rb` or `wb`) but can also include a compression level (`wb9`) or a strategy: `f` for filtered data as in `wb6f`, `h` for `Huffman only compression` as in `wb1h`. (See the description of `deflateInit2` in zlib.h for more information about the strategy parameter.)

`use_include_path`
  If set to `true`, files in the include_path are searched for too.

### Return Values

Returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns `false`.

### Changelog

Version | Description
--- | ---
8.5.0 | `use_include_path` is now of type bool. Previously, it was of type int.

### Examples

Example #1 gzopen() Example

`<?php
$fp = gzopen("/tmp/file.gz", "r");
?>`

### See Also

- gzclose() - Close an open gz-file pointer

# gzpassthru

(PHP 4, PHP 5, PHP 7, PHP 8)

gzpassthru — Output all remaining data on a gz-file pointer

### Description

gzpassthru(resource `$stream`): int

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

> Note:

> You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Tip

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

The number of uncompressed characters read from `gz` and passed through to the input.

### Examples

Example #1 gzpassthru() example

`<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>`

# gzputs

(PHP 4, PHP 5, PHP 7, PHP 8)

gzputs — Alias of gzwrite()

### Description

This function is an alias of: gzwrite().

# gzread

(PHP 4, PHP 5, PHP 7, PHP 8)

gzread — Binary-safe gz-file read

### Description

gzread(resource `$stream`, int `$length`): string|false

gzread() reads up to `length` bytes from the given gz-file pointer. Reading stops when `length` (uncompressed) bytes have been read or EOF is reached, whichever comes first.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

`length`

  The number of bytes to read.

### Return Values

The data that have been read, or `false` on failure.

### Changelog

Version | Description
--- | ---
7.4.0 | This functions returns `false` on failure now; previously `0` was returned.

### Examples

Example #1 gzread() example

`<?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?>`

### See Also

- gzwrite() - Binary-safe gz-file write
- gzopen() - Open gz-file
- gzgets() - Get line from file pointer
- gzgetss() - Get line from gz-file pointer and strip HTML tags
- gzfile() - Read entire gz-file into an array
- gzpassthru() - Output all remaining data on a gz-file pointer

# gzrewind

(PHP 4, PHP 5, PHP 7, PHP 8)

gzrewind — Rewind the position of a gz-file pointer

### Description

gzrewind(resource `$stream`): bool

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- gzseek() - Seek on a gz-file pointer
- gztell() - Tell gz-file pointer read/write position

# gzseek

(PHP 4, PHP 5, PHP 7, PHP 8)

gzseek — Seek on a gz-file pointer

### Description

gzseek(resource `$stream`, int `$offset`, int `$whence` = `SEEK_SET`): int

Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) `gzseek(zp, offset, SEEK_SET)`.

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

`offset`

  The seeked offset.

`whence`

  `whence` values are:

  - `SEEK_SET` - Set position equal to `offset` bytes.
  - `SEEK_CUR` - Set position to current location plus `offset`.

  If `whence` is not specified, it is assumed to be `SEEK_SET`.

### Return Values

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

### Examples

Example #1 gzseek() example

`<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>`

### See Also

- gztell() - Tell gz-file pointer read/write position
- gzrewind() - Rewind the position of a gz-file pointer

# gztell

(PHP 4, PHP 5, PHP 7, PHP 8)

gztell — Tell gz-file pointer read/write position

### Description

gztell(resource `$stream`): int|false

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

### Return Values

The position of the file pointer or `false` if an error occurs.

### See Also

- gzopen() - Open gz-file
- gzseek() - Seek on a gz-file pointer
- gzrewind() - Rewind the position of a gz-file pointer

# gzuncompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

gzuncompress — Uncompress a compressed string

### Description

gzuncompress(string `$data`, int `$max_length` = 0): string|false

This function uncompress a compressed string.

### Parameters

`data`

  The data compressed by gzcompress().

`max_length`

  The maximum length of data to decode.

### Return Values

The original uncompressed data or `false` on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input `data` or more than the optional parameter `max_length`.

### Examples

Example #1 gzuncompress() example

`<?php
$compressed = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>`

### See Also

- gzcompress() - Compress a string
- gzinflate() - Inflate a deflated string
- gzdeflate() - Deflate a string
- gzencode() - Create a gzip compressed string

# gzwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

gzwrite — Binary-safe gz-file write

### Description

gzwrite(resource `$stream`, string `$data`, ?int `$length` = `null`): int|false

gzwrite() writes the contents of `data` to the given gz-file.

### Parameters

`stream`

  The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

`data`

  The string to write.

`length`

  The number of uncompressed bytes to write. If supplied, writing will stop after `length` (uncompressed) bytes have been written or the end of `data` is reached, whichever comes first.

### Return Values

Returns the number of (uncompressed) bytes written to the given gz-file stream, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` is nullable now; previously, the default was `0`.
7.4.0 | This functions returns `false` on failure now; previously `0` was returned.

### Examples

Example #1 gzwrite() example

`<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>`

### See Also

- gzread() - Binary-safe gz-file read
- gzopen() - Open gz-file

# inflate_add

(PHP 7, PHP 8)

inflate_add — Incrementally inflate encoded data

### Description

inflate_add(InflateContext `$context`, string `$data`, int `$flush_mode` = `ZLIB_SYNC_FLUSH`): string|false

Incrementally inflates encoded data in the specified `context`.

Limitation: header information from GZIP compressed data are not made available.

### Parameters

`context`

  A context created with inflate_init().

`data`

  A chunk of compressed data.

`flush_mode`

  One of `ZLIB_BLOCK`, `ZLIB_NO_FLUSH`, `ZLIB_PARTIAL_FLUSH`, `ZLIB_SYNC_FLUSH` (default), `ZLIB_FULL_FLUSH`, `ZLIB_FINISH`. Normally you will want to set `ZLIB_NO_FLUSH` to maximize compression, and `ZLIB_FINISH` to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

### Return Values

Returns a chunk of uncompressed data, or `false` on failure.

### Errors/Exceptions

If invalid parameters are given, inflating the data requires a preset dictionary, but none is specified, the compressed stream is corrupt or has an invalid checksum, an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` expects an InflateContext instance now; previously, a resource was expected.

### See Also

- inflate_init() - Initialize an incremental inflate context

# inflate_get_read_len

(PHP 7 >= 7.2.0, PHP 8)

inflate_get_read_len — Get number of bytes read so far

### Description

inflate_get_read_len(InflateContext `$context`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`context`

### Return Values

Returns number of bytes read so far or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` expects an InflateContext instance now; previously, a resource was expected.

# inflate_get_status

(PHP 7 >= 7.2.0, PHP 8)

inflate_get_status — Get decompression status

### Description

inflate_get_status(InflateContext `$context`): int

Usually returns either `ZLIB_OK` or `ZLIB_STREAM_END`.

### Parameters

`context`

### Return Values

Returns decompression status.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` expects an InflateContext instance now; previously, a resource was expected.

# inflate_init

(PHP 7, PHP 8)

inflate_init — Initialize an incremental inflate context

### Description

inflate_init(int `$encoding`, array|object `$options` = []): InflateContext|false

Initialize an incremental inflate context with the specified `encoding`.

### Parameters

`encoding`

  One of the `ZLIB_ENCODING_*` constants.

`options`

  An associative array which may contain the following elements:

  level

    The compression level in range -1..9; defaults to -1.

  memory

    The compression memory level in range 1..9; defaults to 8.

  window

    The zlib window size (logarithmic) in range 8..15; defaults to 15.

  strategy

    One of `ZLIB_FILTERED`, `ZLIB_HUFFMAN_ONLY`, `ZLIB_RLE`, `ZLIB_FIXED` or `ZLIB_DEFAULT_STRATEGY` (the default).

  dictionary

    A string or an array of strings of the preset dictionary (default: no preset dictionary).

### Return Values

Returns an inflate context resource (`zlib.inflate`) on success, or `false` on failure.

### Errors/Exceptions

If an invalid encoding or option is passed to `options`, or the context couldn't be created, an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an InflateContext instance now; previously, a resource was returned.

### Notes

Caution

Unlike gzinflate(), incremental inflate contexts do not constrain the length of the decoded data, so provide no automatic protection against Zip bombs.

### See Also

- inflate_add() - Incrementally inflate encoded data
- deflate_init() - Initialize an incremental deflate context

# ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ob_gzhandler — ob_start callback function to gzip output buffer

### Description

ob_gzhandler(string `$data`, int `$flags`): string|false

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

### Parameters

`data`

`flags`

### Return Values

### Examples

Example #1 ob_gzhandler() example

`<?php
ob_start("ob_gzhandler");
?>
<html>
<body>
<p>This should be a compressed page.</p>
</body>
</html>`

### Notes

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

### See Also

- ob_start() - Turn on output buffering
- ob_end_flush() - Flush (send) the return value of the active output handler and turn the active output buffer off

# readgzfile

(PHP 4, PHP 5, PHP 7, PHP 8)

readgzfile — Output a gz-file

### Description

readgzfile(string `$filename`, bool `$use_include_path` = `false`): int|false

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

### Parameters

`filename`

  The file name. This file will be opened from the filesystem and its contents written to standard output.

`use_include_path`
  When set to `true` the include_path will be used to determine which file to open.

### Return Values

Returns the number of (uncompressed) bytes read from the file on success, or `false` on failure

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Changelog

Version | Description
--- | ---
8.5.0 | `use_include_path` is now of type bool. Previously, it was of type int.

### See Also

- gzpassthru() - Output all remaining data on a gz-file pointer
- gzfile() - Read entire gz-file into an array
- gzopen() - Open gz-file

# zlib_decode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

zlib_decode — Uncompress any raw/gzip/zlib encoded data

### Description

zlib_decode(string `$data`, int `$max_length` = 0): string|false

Uncompress any raw/gzip/zlib encoded data.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`data`

`max_length`

### Return Values

Returns the uncompressed data, or `false` on failure.

### See Also

- zlib_encode() - Compress data with the specified encoding

# zlib_encode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

zlib_encode — Compress data with the specified encoding

### Description

zlib_encode(string `$data`, int `$encoding`, int `$level` = -1): string|false

Compress data with the specified encoding.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`data`

  The data to compress.

`encoding`

  The compression algorithm. Either `ZLIB_ENCODING_RAW`, `ZLIB_ENCODING_DEFLATE` or `ZLIB_ENCODING_GZIP`.

`level`

### Return Values

### Examples

Example #1 zlib_encode() example

`<?php
$str = 'hello world';
$enc = zlib_encode($str, ZLIB_ENCODING_DEFLATE);
echo bin2hex($enc);
?>`

The above example will output:

    789ccb48cdc9c95728cf2fca4901001a0b045d

### See Also

- zlib_decode() - Uncompress any raw/gzip/zlib encoded data

# zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

zlib_get_coding_type — Returns the coding type used for output compression

### Description

zlib_get_coding_type(): string|false

Returns the coding type used for output compression.

### Parameters

This function has no parameters.

### Return Values

Possible return values are `gzip`, `deflate`, or `false`.

### See Also

- The zlib.output_compression directive

## Table of Contents

- deflate_add — Incrementally deflate data
- deflate_init — Initialize an incremental deflate context
- gzclose — Close an open gz-file pointer
- gzcompress — Compress a string
- gzdecode — Decodes a gzip compressed string
- gzdeflate — Deflate a string
- gzencode — Create a gzip compressed string
- gzeof — Test for EOF on a gz-file pointer
- gzfile — Read entire gz-file into an array
- gzgetc — Get character from gz-file pointer
- gzgets — Get line from file pointer
- gzgetss — Get line from gz-file pointer and strip HTML tags
- gzinflate — Inflate a deflated string
- gzopen — Open gz-file
- gzpassthru — Output all remaining data on a gz-file pointer
- gzputs — Alias of gzwrite
- gzread — Binary-safe gz-file read
- gzrewind — Rewind the position of a gz-file pointer
- gzseek — Seek on a gz-file pointer
- gztell — Tell gz-file pointer read/write position
- gzuncompress — Uncompress a compressed string
- gzwrite — Binary-safe gz-file write
- inflate_add — Incrementally inflate encoded data
- inflate_get_read_len — Get number of bytes read so far
- inflate_get_status — Get decompression status
- inflate_init — Initialize an incremental inflate context
- ob_gzhandler — ob_start callback function to gzip output buffer
- readgzfile — Output a gz-file
- zlib_decode — Uncompress any raw/gzip/zlib encoded data
- zlib_encode — Compress data with the specified encoding
- zlib_get_coding_type — Returns the coding type used for output compression

# The DeflateContext class

(PHP 8)

## Introduction

A fully opaque class which replaces `zlib.deflate` resources as of PHP 8.0.0.

## Class synopsis

final class DeflateContext {
}

# The InflateContext class

(PHP 8)

## Introduction

A fully opaque class which replaces `zlib.inflate` resources as of PHP 8.0.0.

## Class synopsis

final class InflateContext {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
- Zlib Functions
  - deflate_add — Incrementally deflate data
  - deflate_init — Initialize an incremental deflate context
  - gzclose — Close an open gz-file pointer
  - gzcompress — Compress a string
  - gzdecode — Decodes a gzip compressed string
  - gzdeflate — Deflate a string
  - gzencode — Create a gzip compressed string
  - gzeof — Test for EOF on a gz-file pointer
  - gzfile — Read entire gz-file into an array
  - gzgetc — Get character from gz-file pointer
  - gzgets — Get line from file pointer
  - gzgetss — Get line from gz-file pointer and strip HTML tags
  - gzinflate — Inflate a deflated string
  - gzopen — Open gz-file
  - gzpassthru — Output all remaining data on a gz-file pointer
  - gzputs — Alias of gzwrite
  - gzread — Binary-safe gz-file read
  - gzrewind — Rewind the position of a gz-file pointer
  - gzseek — Seek on a gz-file pointer
  - gztell — Tell gz-file pointer read/write position
  - gzuncompress — Uncompress a compressed string
  - gzwrite — Binary-safe gz-file write
  - inflate_add — Incrementally inflate encoded data
  - inflate_get_read_len — Get number of bytes read so far
  - inflate_get_status — Get decompression status
  - inflate_init — Initialize an incremental inflate context
  - ob_gzhandler — ob_start callback function to gzip output buffer
  - readgzfile — Output a gz-file
  - zlib_decode — Uncompress any raw/gzip/zlib encoded data
  - zlib_encode — Compress data with the specified encoding
  - zlib_get_coding_type — Returns the coding type used for output compression
- DeflateContext — The DeflateContext class
- InflateContext — The InflateContext class

- Bzip2
  - Installing/Configuring
  - Examples
  - Bzip2 Functions
- LZF
  - Installing/Configuring
  - LZF Functions
- Phar
  - Installing/Configuring
  - Predefined Constants
  - Using Phar Archives
  - Creating Phar Archives
  - What makes a phar a phar and not a tar or a zip?
  - Phar — The Phar class
  - PharData — The PharData class
  - PharFileInfo — The PharFileInfo class
  - PharException — The PharException class
- Rar — Rar Archiving
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Rar Functions
  - RarArchive — The RarArchive class
  - RarEntry — The RarEntry class
  - RarException — The RarException class
- Zip
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - ZipArchive — The ZipArchive class
  - Zip Functions
- Zlib — Zlib Compression
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Zlib Functions
  - DeflateContext — The DeflateContext class
  - InflateContext — The InflateContext class

# Cryptography Extensions

# HASH Message Digest Framework

# Introduction

This extension provides functions that can be used for direct or incremental processing of arbitrary length messages using a variety of hashing algorithms, including the generation of HMAC values and key derivations including HKDF and PBKDF2.

There are roughly three categories of hashing algorithms, and a complete list of algorithms can be found in the documentation for hash_algos().

- Checksum algorithms (such as `"crc32b"` or `"adler32"`): These are used to calculate checksums, useful in situations such as when transmission errors are to be detected. They are often very fast. These algorithms often generate values that are easily "guessable" or can be manipulated to create collisions, so they are entirely unsuitable for cryptographic use.
- Non-cryptographic algorithms (such as the xxHash family): These are often used to calculate hash values for hash tables, as they are designed to yield a good distribution over arbitrary string inputs. They are also generally fast, but also not suitable for cryptographic use.
- Cryptographic algorithms (such as the SHA-2 family): These are designed to yield hash values that are representative of their inputs but are not guessable nor prone to collisions. Performance is often a secondary concern, but modern hardware often supports special handling for these algorithms that PHP tries to use when available. The Computer Security Resource Center of the NIST has » explanation of the algorithms currently approved by United States Federal Information Processing Standards.
  Caution

  Some of the early cryptographic algorithms, such as `"md4"`, `"md5"`, and `"sha1"`, have been proven to be prone to collision attacks and it is generally recommended to no longer use these for cryptographic applications.

See also the FAQ on Safe Password Hashing for information on best practices for using hash functions in handling passwords.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

The Hash extension is a core PHP extension, so it is always enabled.

Prior to PHP 7.4.0, the Hash extension was bundled and compiled into PHP by default, but could be explicitly disabled using --disable-hash.

Prior to 5.1.2, the Hash extension was installed as a » PECL module.

## Resource Types

This extension defines a Hashing Context resource returned by hash_init().

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

`HASH_HMAC` (int)
  Optional flag for hash_init(). Indicates that the HMAC digest-keying algorithm should be applied to the current hashing context.

# The HashContext class

(PHP 7 >= 7.2.0, PHP 8)

## Introduction

## Class synopsis

final class HashContext {
/* Methods */
private __construct()
public __serialize(): array
public __unserialize(array `$data`): void
}

# HashContext::__construct

(PHP 7 >= 7.2.0, PHP 8)

HashContext::__construct — Private constructor to disallow direct instantiation

### Description

private HashContext::__construct()

### Parameters

This function has no parameters.

# HashContext::__serialize

(PHP 8)

HashContext::__serialize — Serializes the HashContext object

### Description

public HashContext::__serialize(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# HashContext::__unserialize

(PHP 8)

HashContext::__unserialize — Deserializes the `data` parameter into a HashContext object

### Description

public HashContext::__unserialize(array `$data`): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`data`

  The value being deserialized.

### Return Values

No value is returned.

## Table of Contents

- HashContext::__construct — Private constructor to disallow direct instantiation
- HashContext::__serialize — Serializes the HashContext object
- HashContext::__unserialize — Deserializes the data parameter into a HashContext object

# Hash Functions

# hash

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

### Description

hash(
string `$algo`,
string `$data`,
bool `$binary` = `false`,
array `$options` = []
): string

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_algos().

`data`

  Message to be hashed.

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

`options`

  An array of options for the various hashing algorithms. Currently, only the `"seed"` parameter is supported by the MurmurHash variants.

### Return Values

Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned.

### Changelog

Version | Description
--- | ---
8.1.0 | The `options` parameter has been added.
8.0.0 | hash() now throws a ValueError exception if `algo` is unknown; previously, `false` was returned instead.

### Examples

Example #1 A hash() example

`<?php
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
?>`

The above example will output:

    68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_file() - Generate a hash value using the contents of a given file
- hash_hmac() - Generate a keyed hash value using the HMAC method

# hash_algos

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_algos — Return a list of registered hashing algorithms

### Description

hash_algos(): array

### Parameters

This function has no parameters.

### Return Values

Returns a numerically indexed array containing the list of supported hashing algorithms.

### Changelog

Version | Description
--- | ---
8.1.0 | Support for MurmurHash3 and xxHash algorithms has been added.
7.4.0 | Support for crc32c has been added.
7.1.0 | Support for sha512/224, sha512/256, sha3-224, sha3-256, sha3-384 and sha3-512 has been added.

### Examples

Example #1 hash_algos() example

As of PHP 8.1.0, hash_algos() will return the following list of algorithm names.

`<?php
print_r(hash_algos());
?>`

The above example will output something similar to:

    Array
    (
        [0] => md2
        [1] => md4
        [2] => md5
        [3] => sha1
        [4] => sha224
        [5] => sha256
        [6] => sha384
        [7] => sha512/224
        [8] => sha512/256
        [9] => sha512
        [10] => sha3-224
        [11] => sha3-256
        [12] => sha3-384
        [13] => sha3-512
        [14] => ripemd128
        [15] => ripemd160
        [16] => ripemd256
        [17] => ripemd320
        [18] => whirlpool
        [19] => tiger128,3
        [20] => tiger160,3
        [21] => tiger192,3
        [22] => tiger128,4
        [23] => tiger160,4
        [24] => tiger192,4
        [25] => snefru
        [26] => snefru256
        [27] => gost
        [28] => gost-crypto
        [29] => adler32
        [30] => crc32
        [31] => crc32b
        [32] => crc32c
        [33] => fnv132
        [34] => fnv1a32
        [35] => fnv164
        [36] => fnv1a64
        [37] => joaat
        [38] => murmur3a
        [39] => murmur3c
        [40] => murmur3f
        [41] => xxh32
        [42] => xxh64
        [43] => xxh3
        [44] => xxh128
        [45] => haval128,3
        [46] => haval160,3
        [47] => haval192,3
        [48] => haval224,3
        [49] => haval256,3
        [50] => haval128,4
        [51] => haval160,4
        [52] => haval192,4
        [53] => haval224,4
        [54] => haval256,4
        [55] => haval128,5
        [56] => haval160,5
        [57] => haval192,5
        [58] => haval224,5
        [59] => haval256,5
    )

### See Also

- hash() - Generate a hash value (message digest)
- hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac

# hash_copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

hash_copy — Copy hashing context

### Description

hash_copy(HashContext `$context`): HashContext

### Parameters

`context`

  Hashing context returned by hash_init().

### Return Values

Returns a copy of Hashing Context.

### Changelog

Version | Description
--- | ---
7.2.0 | Accept and return HashContext instead of resource.

### Examples

Example #1 hash_copy() example

`<?php
$context = hash_init("sha256");
hash_update($context, "The quick brown fox ");
/* copy context to be able to continue using it */
$copy_context = hash_copy($context);
echo hash_final($context), "\n";
hash_update($copy_context, "jumped over the lazy dog.");
echo hash_final($copy_context), "\n";
?>`

The above example will output:

    b29d66e56ed90cce9b0165c43fedec612b60a071974d8be4513e18580d55b5bd
    68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

# hash_equals

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

hash_equals — Timing attack safe string comparison

### Description

hash_equals(#[\SensitiveParameter] string `$known_string`, #[\SensitiveParameter] string `$user_string`): bool

Checks whether two strings are equal without leaking information about the contents of `known_string` via the execution time.

This function can be used to mitigate timing attacks. Performing a regular comparison with `===` will take more or less time to execute depending on whether the two values are different or not and at which position the first difference can be found, thus leaking information about the contents of the secret `known_string`.

Caution

It is important to provide the user-supplied string as the second parameter, rather than the first.

### Parameters

`known_string`

  The known string that must be kept secret.

`user_string`

  The user-supplied string to compare against.

### Return Values

Returns `true` when the two strings are equal, `false` otherwise.

### Examples

Example #1 hash_equals() example

`<?php
$secretKey = '8uRhAeH89naXfFXKGOEj';
// Value and signature are provided by the user, e.g. within the URL
// and retrieved using $_GET.
$value = 'username=rasmuslerdorf';
$signature = '8c35009d3b50caf7f5d2c1e031842e6b7823a1bb781d33c5237cd27b57b5f327';
if (hash_equals(hash_hmac('sha256', $value, $secretKey), $signature)) {
echo "The value is correctly signed.", PHP_EOL;
} else {
echo "The value was tampered with.", PHP_EOL;
}
?>`

The above example will output:

    The value is correctly signed.

### Notes

> Note:

> Both arguments must be of the same length to be compared successfully. When arguments of differing length are supplied, `false` is returned immediately and the length of the known string may be leaked in case of a timing attack.

### See Also

- hash_hmac() - Generate a keyed hash value using the HMAC method

# hash_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_file — Generate a hash value using the contents of a given file

### Description

hash_file(
string `$algo`,
string `$filename`,
bool `$binary` = `false`,
array `$options` = []
): string|false

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_algos().

`filename`

  URL describing location of file to be hashed; Supports fopen() wrappers.

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

`options`

  An array of options for the various hashing algorithms. Currently, only the `"seed"` parameter is supported by the MurmurHash variants.

### Return Values

Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `options` parameter has been added.

### Examples

Example #1 Using hash_file()

`<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');
echo hash_file('sha256', 'example.txt');
?>`

The above example will output:

    68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

# hash_final

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

### Description

hash_final(HashContext `$context`, bool `$binary` = `false`): string

### Parameters

`context`

  Hashing context returned by hash_init().

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

### Return Values

Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned.

### Changelog

Version | Description
--- | ---
7.2.0 | Accept HashContext instead of resource.

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_update() - Pump data into an active hashing context
- hash_update_stream() - Pump data into an active hashing context from an open stream
- hash_update_file() - Pump data into an active hashing context from a file

# hash_hkdf

(PHP 7 >= 7.1.2, PHP 8)

hash_hkdf — Generate a HKDF key derivation of a supplied key input

### Description

hash_hkdf(
string `$algo`,
#[\SensitiveParameter] string `$key`,
int `$length` = 0,
string `$info` = "",
string `$salt` = ""
): string

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_hmac_algos().

  > Note:

  > Non-cryptographic hash functions are not allowed.

`key`

  Input keying material (raw binary). Cannot be empty.

`length`

  Desired output length in bytes. Cannot be greater than 255 times the chosen hash function size.

  If `length` is `0`, the output length will default to the chosen hash function size.

`info`

  Application/context-specific info string.

`salt`

  Salt to use during derivation.

  While optional, adding random salt significantly improves the strength of HKDF.

### Return Values

Returns a string containing a raw binary representation of the derived key (also known as output keying material - OKM).

### Errors/Exceptions

Throws a ValueError exception if `key` is empty, `algo` is unknown/non-cryptographic, `length` is less than `0` or too large (greater than 255 times the size of the hash function).

### Changelog

Version | Description
--- | ---
8.0.0 | Now throws a ValueError exception on error. Previously, `false` was returned and an `E_WARNING` message was emitted.

### Examples

The example below produces a pair of separate keys, suitable for creation of an encrypt-then-HMAC construct, using AES-256 and SHA-256 for encryption and authentication respectively.

Example #1 hash_hkdf() example

`<?php
// Generate a random key, and salt to strengthen it during derivation.
$inputKey = random_bytes(32);
$salt = random_bytes(16);
// Derive a pair of separate keys, using the same input created above.
$encryptionKey = hash_hkdf('sha256', $inputKey, 32, 'aes-256-encryption', $salt);
$authenticationKey = hash_hkdf('sha256', $inputKey, 32, 'sha-256-authentication', $salt);
var_dump($encryptionKey !== $authenticationKey); // bool(true)
?>`

### See Also

- hash_pbkdf2() - Generate a PBKDF2 key derivation of a supplied password
- » RFC 5869
- » userland implementation

# hash_hmac

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

### Description

hash_hmac(
string `$algo`,
string `$data`,
#[\SensitiveParameter] string `$key`,
bool `$binary` = `false`
): string

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_hmac_algos().

  > Note:

  > Non-cryptographic hash functions are not allowed.

`data`

  Message to be hashed.

`key`

  Shared secret key used for generating the HMAC variant of the message digest.

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

### Return Values

Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned.

### Errors/Exceptions

Throws a ValueError exception if `algo` is unknown or is a non-cryptographic hash function.

### Changelog

Version | Description
--- | ---
8.0.0 | Now throws a ValueError exception if `algo` is unknown or is a non-cryptographic hash function; previously, `false` was returned instead.
7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.

### Examples

Example #1 hash_hmac() example

`<?php
echo hash_hmac('sha256', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>`

The above example will output:

    9c5c42422b03f0ee32949920649445e417b2c634050833c5165704b825c2a53b

### See Also

- hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac
- hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
- hash_equals() - Timing attack safe string comparison

# hash_hmac_algos

(PHP 7 >= 7.2.0, PHP 8)

hash_hmac_algos — Return a list of registered hashing algorithms suitable for hash_hmac

### Description

hash_hmac_algos(): array

### Parameters

This function has no parameters.

### Return Values

Returns a numerically indexed array containing the list of supported hashing algorithms suitable for hash_hmac().

### Examples

Example #1 hash_hmac_algos() example

`<?php
print_r(hash_hmac_algos());`

The above example will output something similar to:

    Array
    (
        [0] => md2
        [1] => md4
        [2] => md5
        [3] => sha1
        [4] => sha224
        [5] => sha256
        [6] => sha384
        [7] => sha512/224
        [8] => sha512/256
        [9] => sha512
        [10] => sha3-224
        [11] => sha3-256
        [12] => sha3-384
        [13] => sha3-512
        [14] => ripemd128
        [15] => ripemd160
        [16] => ripemd256
        [17] => ripemd320
        [18] => whirlpool
        [19] => tiger128,3
        [20] => tiger160,3
        [21] => tiger192,3
        [22] => tiger128,4
        [23] => tiger160,4
        [24] => tiger192,4
        [25] => snefru
        [26] => snefru256
        [27] => gost
        [28] => gost-crypto
        [29] => haval128,3
        [30] => haval160,3
        [31] => haval192,3
        [32] => haval224,3
        [33] => haval256,3
        [34] => haval128,4
        [35] => haval160,4
        [36] => haval192,4
        [37] => haval224,4
        [38] => haval256,4
        [39] => haval128,5
        [40] => haval160,5
        [41] => haval192,5
        [42] => haval224,5
        [43] => haval256,5
    )

### Notes

> Note:

> Before PHP 7.2.0 the only means to get a list of supported hash algorithms has been to call hash_algos() which also returns hash algorithms that are not suitable for hash_hmac().

### See Also

- hash_hmac() - Generate a keyed hash value using the HMAC method
- hash_algos() - Return a list of registered hashing algorithms

# hash_hmac_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file

### Description

hash_hmac_file(
string `$algo`,
string `$filename`,
#[\SensitiveParameter] string `$key`,
bool `$binary` = `false`
): string|false

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_hmac_algos().

  > Note:

  > Non-cryptographic hash functions are not allowed.

`filename`

  URL describing location of file to be hashed; Supports fopen wrappers.

`key`

  Shared secret key used for generating the HMAC variant of the message digest.

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

### Return Values

Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned. Returns `false` if the file `filename` cannot be read.

### Errors/Exceptions

Throws a ValueError exception if `algo` is unknown or is a non-cryptographic hash function.

### Changelog

Version | Description
--- | ---
8.0.0 | Now throws a ValueError exception if `algo` is unknown or is a non-cryptographic hash function; previously, `false` was returned instead.
7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.

### Examples

Example #1 hash_hmac_file() example

`<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');
echo hash_hmac_file('sha256', 'example.txt', 'secret');
?>`

The above example will output:

    9c5c42422b03f0ee32949920649445e417b2c634050833c5165704b825c2a53b

### See Also

- hash_hmac() - Generate a keyed hash value using the HMAC method
- hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac
- hash_init() - Initialize an incremental hashing context
- hash_equals() - Timing attack safe string comparison

# hash_init

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

### Description

hash_init(
string `$algo`,
int `$flags` = 0,
#[\SensitiveParameter] string `$key` = "",
array `$options` = []
): HashContext

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_algos().

  > Note:

  > Non-cryptographic hash functions are not allowed if the `HASH_HMAC` flag is specified.

`flags`

  Optional settings for hash generation, currently supports only one option: `HASH_HMAC`. When specified, the `key` must be specified.

`key`

  When `HASH_HMAC` is specified for `flags`, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

`options`

  An array of options for the various hashing algorithms. Currently, only the `"seed"` parameter is supported by the MurmurHash variants.

### Return Values

Returns a Hashing Context for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

### Errors/Exceptions

- Throws a ValueError exception if `algo` is unknown or is a non-cryptographic hash function, or if `key` is empty.
- Passing configurations options of the wrong type in `options` will now emit an `E_DEPRECATED` error because they can be interpreted incorrectly. This will become a ValueError in the future.

### Changelog

Version | Description
--- | ---
8.4.0 | Passing options of a wrong type is now deprecated.
8.1.0 | The `options` parameter has been added.
8.0.0 | Now throws an ValueError exception if the `algo` is unknown or is a non-cryptographic hash function, or if `key` is empty. Previously, `false` was returned and an `E_WARNING` message was emitted.
7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) with `HASH_HMAC` was disabled.
7.2.0 | Return HashContext instead of resource.

### Examples

Example #1 Incremental hashing example

`<?php
$hash = hash('sha256', 'The quick brown fox jumped over the lazy dog.');
$ctx = hash_init('sha256');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
$incremental_hash = hash_final($ctx);
echo $incremental_hash, PHP_EOL;
var_dump($hash === $incremental_hash);
?>`

The above example will output:

    68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483
    bool(true)

### See Also

- hash_algos() - Return a list of registered hashing algorithms
- hash_update() - Pump data into an active hashing context
- hash_update_file() - Pump data into an active hashing context from a file
- hash_update_stream() - Pump data into an active hashing context from an open stream
- hash_final() - Finalize an incremental hash and return resulting digest

# hash_pbkdf2

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password

### Description

hash_pbkdf2(
string `$algo`,
#[\SensitiveParameter] string `$password`,
string `$salt`,
int `$iterations`,
int `$length` = 0,
bool `$binary` = `false`,
array `$options` = []
): string

### Parameters

`algo`

  Name of selected hashing algorithm (e.g. `"sha256"`). For a list of supported algorithms see hash_hmac_algos().

  > Note:

  > Non-cryptographic hash functions are not allowed.

`password`

  The password to use for the derivation.

`salt`

  The salt to use for the derivation. This value should be generated randomly.

`iterations`

  The number of internal iterations to perform for the derivation.

`length`

  The length of the output string. If `binary` is `true` this corresponds to the byte-length of the derived key, if `binary` is `false` this corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits).

  If `0` is passed, the entire output of the supplied algorithm is used.

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

`options`

  An array of options for the various hashing algorithms. Currently, only the `"seed"` key is supported by the MurmurHash variants.

### Return Values

Returns a string containing the derived key as lowercase hexits unless `binary` is set to `true` in which case the raw binary representation of the derived key is returned.

### Errors/Exceptions

Throws a ValueError exception if the algorithm is unknown, the `iterations` parameter is less than or equal to `0`, the `length` is less than `0` or the `salt` is too long (greater than `INT_MAX``- 4`).

### Changelog

Version | Description
--- | ---
8.0.0 | Now throws a ValueError exception on error. Previously, `false` was returned and an `E_WARNING` message was emitted.
7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.

### Examples

Example #1 hash_pbkdf2() example, basic usage

`<?php
$password = "password";
$iterations = 600000;
// Generate a cryptographically secure random salt using random_bytes()
$salt = random_bytes(16);
$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20);
var_dump($hash);
// for raw binary, the $length needs to be halved for equivalent results
$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 10, true);
var_dump(bin2hex($hash));?>`

The above example will output something similar to:

    string(20) "120fb6cffcf8b32c43e7"
    string(20) "120fb6cffcf8b32c43e7"

### Notes

Caution

The PBKDF2 method can be used for hashing passwords for storage. However, it should be noted that password_hash() or crypt() with `CRYPT_BLOWFISH` are better suited for password storage.

### See Also

- password_hash() - Creates a password hash
- hash_hkdf() - Generate a HKDF key derivation of a supplied key input
- sodium_crypto_pwhash() - Derive a key from a password, using Argon2

# hash_update

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update — Pump data into an active hashing context

### Description

hash_update(HashContext `$context`, string `$data`): true

### Parameters

`context`

  Hashing context returned by hash_init().

`data`

  Message to be included in the hash digest.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.4.0 | Now has a return type of true instead of bool.
7.2.0 | Accept HashContext instead of resource.

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_update_file() - Pump data into an active hashing context from a file
- hash_update_stream() - Pump data into an active hashing context from an open stream
- hash_final() - Finalize an incremental hash and return resulting digest

# hash_update_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

### Description

hash_update_file(HashContext `$context`, string `$filename`, ?resource `$stream_context` = `null`): bool

### Parameters

`context`

  Hashing context returned by hash_init().

`filename`

  URL describing location of file to be hashed; Supports fopen() wrappers.

`stream_context`

  Stream context as returned by stream_context_create().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `stream_context` is now nullable.
7.2.0 | Accept HashContext instead of resource.

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_update() - Pump data into an active hashing context
- hash_update_stream() - Pump data into an active hashing context from an open stream
- hash_final() - Finalize an incremental hash and return resulting digest
- hash_file() - Generate a hash value using the contents of a given file

# hash_update_stream

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update_stream — Pump data into an active hashing context from an open stream

### Description

hash_update_stream(HashContext `$context`, resource `$stream`, int `$length` = -1): int

### Parameters

`context`

  Hashing context returned by hash_init().

`stream`

  Open file handle as returned by any stream creation function.

`length`

  Maximum number of characters to copy from `stream` into the hashing context.

### Return Values

Actual number of bytes added to the hashing context from `stream`.

### Changelog

Version | Description
--- | ---
7.2.0 | Accept HashContext instead of resource.

### Examples

Example #1 hash_update_stream() example

`<?php
$fp = tmpfile();
fwrite($fp, 'jumped over the lazy dog.');
rewind($fp);
$ctx = hash_init('sha256');
hash_update($ctx, 'The quick brown fox ');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>`

The above example will output:

    68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

### See Also

- hash_init() - Initialize an incremental hashing context
- hash_update() - Pump data into an active hashing context
- hash_final() - Finalize an incremental hash and return resulting digest

## Table of Contents

- hash — Generate a hash value (message digest)
- hash_algos — Return a list of registered hashing algorithms
- hash_copy — Copy hashing context
- hash_equals — Timing attack safe string comparison
- hash_file — Generate a hash value using the contents of a given file
- hash_final — Finalize an incremental hash and return resulting digest
- hash_hkdf — Generate a HKDF key derivation of a supplied key input
- hash_hmac — Generate a keyed hash value using the HMAC method
- hash_hmac_algos — Return a list of registered hashing algorithms suitable for hash_hmac
- hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
- hash_init — Initialize an incremental hashing context
- hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
- hash_update — Pump data into an active hashing context
- hash_update_file — Pump data into an active hashing context from a file
- hash_update_stream — Pump data into an active hashing context from an open stream

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- HashContext — The HashContext class
  - HashContext::__construct — Private constructor to disallow direct instantiation
  - HashContext::__serialize — Serializes the HashContext object
  - HashContext::__unserialize — Deserializes the data parameter into a HashContext object
- Hash Functions
  - hash — Generate a hash value (message digest)
  - hash_algos — Return a list of registered hashing algorithms
  - hash_copy — Copy hashing context
  - hash_equals — Timing attack safe string comparison
  - hash_file — Generate a hash value using the contents of a given file
  - hash_final — Finalize an incremental hash and return resulting digest
  - hash_hkdf — Generate a HKDF key derivation of a supplied key input
  - hash_hmac — Generate a keyed hash value using the HMAC method
  - hash_hmac_algos — Return a list of registered hashing algorithms suitable for hash_hmac
  - hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
  - hash_init — Initialize an incremental hashing context
  - hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
  - hash_update — Pump data into an active hashing context
  - hash_update_file — Pump data into an active hashing context from a file
  - hash_update_stream — Pump data into an active hashing context from an open stream

# Mcrypt

# Introduction

Warning

This feature was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0.

Alternatives to this feature include:

- Sodium (available as of PHP 7.2.0)
- OpenSSL

> Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.2.0.

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free". CFB/OFB are 8bit by default.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

These functions work using » mcrypt. To use it, download libmcrypt-x.x.tar.gz from » http://mcrypt.sourceforge.net/ and follow the included installation instructions.

libmcrypt Version 2.5.6 or greater is required.

Windows users will find the library is the PHP 5.2 Windows binaries release. PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

## Installation

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.2.0

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: » https://pecl.php.net/package/mcrypt.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mcrypt configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mcrypt.algorithms_dir | `null` | `INI_ALL` |
mcrypt.modes_dir | `null` | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mcrypt.algorithms_dir` string
  The directory that contains the algorithms. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_algorithms() for additional details.
`mcrypt.modes_dir` string
  The directory that contains the modes. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_modes() for additional details.

## Resource Types

mcrypt_module_open() returns an encryption descriptor.

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

Mcrypt can operate in four block cipher modes (`CBC`, `OFB`, `CFB`, and `ECB`). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode `nOFB` and in `STREAM` mode. Below you find a list with all supported encryption modes together with the constants that are defined for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

- `MCRYPT_MODE_ECB` (`electronic codebook`) is a block cipher mode that is generally unsuitable for most purposes. The use of this mode is not recommended.
- `MCRYPT_MODE_CBC` (`cipher block chaining`) is a block cipher mode that is significantly more secure than `ECB` mode.
- `MCRYPT_MODE_CFB` (`cipher feedback, in 8-bit mode`) is a stream cipher mode. It is recommended to use `NCFB` mode rather than `CFB` mode.
- `MCRYPT_MODE_OFB` (`output feedback, in 8-bit mode`) is a stream cipher mode comparable to `CFB`, but can be used in applications where error propagation cannot be tolerated. It is recommended to use `NOFB` mode rather than `OFB` mode.
- `MCRYPT_MODE_NOFB` (`output feedback, in n-bit mode`) is comparable to `OFB` mode, but operates on the full block size of the algorithm.
- `MCRYPT_MODE_STREAM` is an extra mode to include some stream algorithms like `"WAKE"` or `"RC4"`.

Mcrypt supports some other modes of operation for which there are no predefined constants. They can be utilised by passing a string in place of the missing constants.

- `"ctr"` (`counter mode`) is a stream cipher mode.
- `"ncfb"` (`cipher feedback, in n-bit mode`) is comparable to `CFB` mode, but operates on the full block size of the algorithm.

Some other mode and random device constants:

`MCRYPT_ENCRYPT` (int)
`MCRYPT_DECRYPT` (int)
`MCRYPT_DEV_RANDOM` (int)
`MCRYPT_DEV_URANDOM` (int)
`MCRYPT_RAND` (int)

# Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

- MCRYPT_3DES
- MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
- MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
- MCRYPT_BLOWFISH
- MCRYPT_CAST_128
- MCRYPT_CAST_256
- MCRYPT_CRYPT
- MCRYPT_DES
- MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
- MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
- MCRYPT_GOST
- MCRYPT_IDEA (non-free)
- MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
- MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
- MCRYPT_PANAMA (libmcrypt > 2.4.x only)
- MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
- MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
- MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
- MCRYPT_RC2
- MCRYPT_RC4 (libmcrypt 2.2.x only)
- MCRYPT_RC6 (libmcrypt > 2.4.x only)
- MCRYPT_RC6_128 (libmcrypt 2.2.x only)
- MCRYPT_RC6_192 (libmcrypt 2.2.x only)
- MCRYPT_RC6_256 (libmcrypt 2.2.x only)
- MCRYPT_SAFER64
- MCRYPT_SAFER128
- MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
- MCRYPT_SERPENT(libmcrypt > 2.4.x only)
- MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
- MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
- MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
- MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
- MCRYPT_TEAN (libmcrypt 2.2.x only)
- MCRYPT_THREEWAY
- MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
- MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
- MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
- MCRYPT_TWOFISH192
- MCRYPT_TWOFISH256
- MCRYPT_WAKE (libmcrypt > 2.4.x only)
- MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in `CFB` and `OFB` mode) or can (in `CBC` mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

# Mcrypt Functions

# mcrypt_create_iv

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_create_iv — Creates an initialization vector (IV) from a random source

Warning

This function was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0.

Alternatives to this function include:

- random_bytes()

### Description

mcrypt_create_iv(int `$size`, int `$source` = MCRYPT_DEV_URANDOM): string

Creates an initialization vector (IV) from a random source.

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.

### Parameters

`size`
  The size of the IV.
`source`
  The source of the IV. The source can be `MCRYPT_RAND` (system random number generator), `MCRYPT_DEV_RANDOM` (read data from /dev/random) and `MCRYPT_DEV_URANDOM` (read data from /dev/urandom). Prior to 5.3.0, `MCRYPT_RAND` was the only one supported on Windows. Note that the default value of this parameter was `MCRYPT_DEV_RANDOM` prior to PHP 5.6.0.

  > Note: Note that `MCRYPT_DEV_RANDOM` may block until more entropy is available.

### Return Values

Returns the initialization vector, or `false` on error.

### Examples

Example #1 mcrypt_create_iv() Example

`<?php
$size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>`

### See Also

- » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
- » http://www.quadibloc.com/crypto/co0409.htm
- Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)
- random_bytes() - Get cryptographically secure random bytes

# mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_decrypt — Decrypts crypttext with given parameters

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_decrypt(
string `$cipher`,
string `$key`,
string `$data`,
string `$mode`,
string `$iv` = ?
): string|false

Decrypts the `data` and returns the unencrypted data.

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`key`
  The key with which the data was encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return `false`
`data`
  The data that will be decrypted with the given `cipher` and `mode`. If the size of the data is not n * blocksize, the data will be padded with '`\0`'.
`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

`iv`

  Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return `false`.

### Return Values

Returns the decrypted data as a string or `false` on failure.

### See Also

- mcrypt_encrypt() - Encrypts plaintext with given parameters

# mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_algorithms_name(resource `$td`): string

This function returns the name of the algorithm.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns the name of the opened algorithm as a string.

### Examples

Example #1 mcrypt_enc_get_algorithms_name() example

`<?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?>`

The above example will output:

    CAST-256
    CAST-256

# mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_block_size(resource `$td`): int

Gets the blocksize of the opened algorithm.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns the block size of the specified algorithm in bytes.

# mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_iv_size(resource `$td`): int

This function returns the size of the IV of the algorithm specified by the encryption descriptor in bytes. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns the size of the IV, or 0 if the IV is ignored by the algorithm.

# mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_key_size(resource `$td`): int

Gets the maximum supported key size of the algorithm in bytes.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns the maximum supported key size of the algorithm in bytes.

# mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_modes_name — Returns the name of the opened mode

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_modes_name(resource `$td`): string

This function returns the name of the mode.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns the name as a string.

### Examples

Example #1 mcrypt_enc_get_modes_name() example

`<?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_modes_name($td). "\n";
$td = mcrypt_module_open ('cast-256', '', 'ecb', '');
echo mcrypt_enc_get_modes_name($td). "\n";
?>`

The above example will output:

    CFB
    ECB

# mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_get_supported_key_sizes(resource `$td`): array

Gets the supported key sizes of the opened algorithm.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

### Examples

Example #1 mcrypt_enc_get_supported_key_sizes() example

`<?php
$td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>`

The above example will output:

    array(3) {
      [0]=>
      int(16)
      [1]=>
      int(24)
      [2]=>
      int(32)
    }

# mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_is_block_algorithm(resource `$td`): bool

Tells whether the algorithm of the opened mode is a block algorithm.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `true` if the algorithm is a block algorithm or `false` if it is a stream one.

# mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_is_block_algorithm_mode(resource `$td`): bool

Tells whether the algorithm of the opened mode works on blocks (e.g. `false` for stream, and `true` for cbc, cfb, ofb)..

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `true` if the mode is for use with block algorithms, otherwise it returns `false`.

# mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_is_block_mode(resource `$td`): bool

Tells whether the opened mode outputs blocks (e.g. `true` for cbc and ecb, and `false` for cfb and stream).

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `true` if the mode outputs blocks of bytes, or `false` if it outputs just bytes.

# mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_self_test — Runs a self test on the opened module

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_enc_self_test(resource `$td`): int

This function runs the self test on the algorithm specified by the descriptor `td`.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `0` on success and a negative int on failure.

# mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_encrypt — Encrypts plaintext with given parameters

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_encrypt(
string `$cipher`,
string `$key`,
string `$data`,
string `$mode`,
string `$iv` = ?
): string|false

Encrypts the data and returns it.

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`key`
  The key with which the data will be encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return `false`
`data`
  The data that will be encrypted with the given `cipher` and `mode`. If the size of the data is not n * blocksize, the data will be padded with '`\0`'. The returned crypttext can be larger than the size of the data that was given by `data`.
`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

`iv`

  Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return `false`.

### Return Values

Returns the encrypted data as a string or `false` on failure.

### Examples

Example #1 mcrypt_encrypt() Example

`<?php
# --- ENCRYPTION ---
# the key should be random binary, use scrypt, bcrypt or PBKDF2 to
# convert a string into a key
# key is specified using hexadecimal
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size = strlen($key);
echo "Key size: " . $key_size . "\n";
$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";
# create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);
# prepend the IV for it to be available for decryption
$ciphertext = $iv . $ciphertext;
# encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);
echo $ciphertext_base64 . "\n";
# === WARNING ===
# Resulting cipher text has no integrity or authenticity added
# and is not protected against padding oracle attacks.
# --- DECRYPTION ---
$ciphertext_dec = base64_decode($ciphertext_base64);
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
echo $plaintext_dec . "\n";
?>`

The above example will output:

    Key size: 32
    ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
    This string was AES-256 / CBC / ZeroBytePadding encrypted.

### See Also

- mcrypt_decrypt() - Decrypts crypttext with given parameters
- mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

# mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic — This function encrypts data

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_generic(resource `$td`, string `$data`): string

This function encrypts data. The data is padded with "`\0`" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer than the input, due to the padding of the data.

If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim($str, "\0") to remove the padding.

If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.

### Parameters

`td`
  The encryption descriptor. The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
`data`
  The data to encrypt.

### Return Values

Returns the encrypted data.

### See Also

- mdecrypt_generic() - Decrypts data
- mcrypt_generic_init() - This function initializes all buffers needed for encryption
- mcrypt_generic_deinit() - This function deinitializes an encryption module

# mcrypt_generic_deinit

(PHP 4 >= 4.0.7, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic_deinit — This function deinitializes an encryption module

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_generic_deinit(resource `$td`): bool

This function terminates encryption specified by the encryption descriptor (`td`). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.)

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mcrypt_module_open() - Opens the module of the algorithm and the mode to be used
- mcrypt_generic_init() - This function initializes all buffers needed for encryption

# mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic_init — This function initializes all buffers needed for encryption

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_generic_init(resource `$td`, string `$key`, string `$iv`): int

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

### Parameters

`td`
  The encryption descriptor.
`key`
  The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal.
`iv`
  The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.

### Return Values

The function returns a negative value on error: -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. `false` is returned if incorrect parameters were passed.

### See Also

- mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

# mcrypt_get_block_size

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_block_size — Gets the block size of the specified cipher

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_get_block_size(int `$cipher`): int|false
mcrypt_get_block_size(string `$cipher`, string `$mode`): int|false

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified `cipher` (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

### Return Values

Returns the algorithm block size in bytes or `false` on failure.

### Examples

Example #1 mcrypt_get_block_size() example

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

`<?php
echo mcrypt_get_block_size('tripledes', 'ecb'); // 8
?>`

### See Also

- mcrypt_get_key_size() - Gets the key size of the specified cipher
- mcrypt_enc_get_block_size() - Returns the blocksize of the opened algorithm
- mcrypt_encrypt() - Encrypts plaintext with given parameters

# mcrypt_get_cipher_name

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_cipher_name — Gets the name of the specified cipher

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_get_cipher_name(int `$cipher`): string
mcrypt_get_cipher_name(string `$cipher`): string

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or `false`, if the cipher does not exist.

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

### Return Values

This function returns the name of the cipher or `false` if the cipher does not exist.

### Examples

Example #1 mcrypt_get_cipher_name() Example

`<?php
$cipher = MCRYPT_TripleDES;
echo mcrypt_get_cipher_name($cipher);
?>`

The above example will output:

    3DES

# mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_get_iv_size(string `$cipher`, string `$mode`): int

Gets the size of the IV belonging to a specific `cipher`/`mode` combination.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

  The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

### Return Values

Returns the size of the Initialization Vector (IV) in bytes. On error the function returns `false`. If the IV is ignored in the specified cipher/mode combination zero is returned.

### Examples

Example #1 mcrypt_get_iv_size() Example

`<?php
echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";
echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>`

### See Also

- mcrypt_get_block_size() - Gets the block size of the specified cipher
- mcrypt_enc_get_iv_size() - Returns the size of the IV of the opened algorithm
- mcrypt_create_iv() - Creates an initialization vector (IV) from a random source

# mcrypt_get_key_size

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_key_size — Gets the key size of the specified cipher

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_get_key_size(int `$cipher`): int|false
mcrypt_get_key_size(string `$cipher`, string `$mode`): int|false

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified `cipher` (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

### Parameters

`cipher`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

### Return Values

Returns the maximum supported key size of the algorithm in bytes or `false` on failure.

### Examples

Example #1 mcrypt_get_key_size() Example

`<?php
echo mcrypt_get_key_size('tripledes', 'ecb');
?>`

The example above shows how to use this function when linked against libmcrypt 2.4.x or 2.5.x.

The above example will output:

    24

### See Also

- mcrypt_get_block_size() - Gets the block size of the specified cipher
- mcrypt_enc_get_key_size() - Returns the maximum supported keysize of the opened mode
- mcrypt_encrypt() - Encrypts plaintext with given parameters

# mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_list_algorithms — Gets an array of all supported ciphers

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_list_algorithms(string `$lib_dir` = ini_get("mcrypt.algorithms_dir")): array

Gets the list of all supported algorithms in the `lib_dir` parameter.

### Parameters

`lib_dir`
  Specifies the directory where all algorithms are located. If not specified, the value of the `mcrypt.algorithms_dir` php.ini directive is used.

### Return Values

Returns an array with all the supported algorithms.

### Examples

Example #1 mcrypt_list_algorithms() Example

`<?php
$algorithms = mcrypt_list_algorithms();
print_r($algorithms);
?>`

The above example will output something similar to:

    Array
    (
        [0] => cast-128
        [1] => gost
        [2] => rijndael-128
        [3] => twofish
        [4] => arcfour
        [5] => cast-256
        [6] => loki97
        [7] => rijndael-192
        [8] => saferplus
        [9] => wake
        [10] => blowfish-compat
        [11] => des
        [12] => rijndael-256
        [13] => serpent
        [14] => xtea
        [15] => blowfish
        [16] => enigma
        [17] => rc2
        [18] => tripledes
    )

# mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_list_modes — Gets an array of all supported modes

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_list_modes(string `$lib_dir` = ini_get("mcrypt.modes_dir")): array

Gets the list of all supported modes in the `lib_dir` parameter.

### Parameters

`lib_dir`
  Specifies the directory where all modes are located. If not specified, the value of the `mcrypt.modes_dir` php.ini directive is used.

### Return Values

Returns an array with all the supported modes.

### Examples

Example #1 mcrypt_list_modes() Example

`<?php
$modes = mcrypt_list_modes();
foreach ($modes as $mode) {
echo "$mode <br />\n";
}
?>`

The example above will produce a list with all supported algorithms in the default mode directory. If it is not set with the `mcrypt.modes_dir` php.ini directive, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

# mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_close — Closes the mcrypt module

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_close(resource `$td`): bool

Closes the specified encryption handle.

### Parameters

`td`
  The encryption descriptor.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

# mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_get_algo_block_size(string `$algorithm`, string `$lib_dir` = ?): int

Gets the blocksize of the specified algorithm.

### Parameters

`algorithm`
  The algorithm name.
`lib_dir`
  This optional parameter can contain the location where the mode module is on the system.

### Return Values

Returns the block size of the algorithm specified in bytes.

# mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_get_algo_key_size(string `$algorithm`, string `$lib_dir` = ?): int

Gets the maximum supported keysize of the opened mode.

### Parameters

`algorithm`
  The algorithm name.
`lib_dir`
  This optional parameter can contain the location where the mode module is on the system.

### Return Values

This function returns the maximum supported key size of the algorithm specified in bytes.

# mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_get_supported_key_sizes(string `$algorithm`, string `$lib_dir` = ?): array

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

### Parameters

`algorithm`
  The algorithm to be used.
`lib_dir`
  The optional `lib_dir` parameter can contain the location where the algorithm module is on the system.

### Return Values

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

### See Also

- mcrypt_enc_get_supported_key_sizes() - Returns an array with the supported keysizes of the opened algorithm

# mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_is_block_algorithm(string `$algorithm`, string `$lib_dir` = ?): bool

This function returns `true` if the specified algorithm is a block algorithm, or `false` if it is a stream one.

### Parameters

`algorithm`
  The algorithm to check.
`lib_dir`
  The optional `lib_dir` parameter can contain the location where the algorithm module is on the system.

### Return Values

This function returns `true` if the specified algorithm is a block algorithm, or `false` if it is a stream one.

# mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_is_block_algorithm_mode(string `$mode`, string `$lib_dir` = ?): bool

This function returns `true` if the mode is for use with block algorithms, otherwise it returns `false`. (e.g. `false` for stream, and `true` for cbc, cfb, ofb).

### Parameters

`mode`
  The mode to check.
`lib_dir`
  The optional `lib_dir` parameter can contain the location where the algorithm module is on the system.

### Return Values

This function returns `true` if the mode is for use with block algorithms, otherwise it returns `false`. (e.g. `false` for stream, and `true` for cbc, cfb, ofb).

# mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_is_block_mode(string `$mode`, string `$lib_dir` = ?): bool

This function returns `true` if the mode outputs blocks of bytes or `false` if it outputs just bytes. (e.g. `true` for cbc and ecb, and `false` for cfb and stream).

### Parameters

`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

`lib_dir`
  The optional `lib_dir` parameter can contain the location where the algorithm module is on the system.

### Return Values

This function returns `true` if the mode outputs blocks of bytes or `false` if it outputs just bytes. (e.g. `true` for cbc and ecb, and `false` for cfb and stream).

# mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_open — Opens the module of the algorithm and the mode to be used

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_open(
string `$algorithm`,
string `$algorithm_directory`,
string `$mode`,
string `$mode_directory`
): resource

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. `"twofish"` or is one of the `MCRYPT_ciphername` constants. The module is closed by calling mcrypt_module_close().

### Parameters

`algorithm`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`algorithm_directory`
  The `algorithm_directory` parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (`""`), the value set by the `mcrypt.algorithms_dir` php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled into libmcrypt (usually /usr/local/lib/libmcrypt).
`mode`

  One of the `MCRYPT_MODE_modename` constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

`mode_directory`
  The `mode_directory` parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (`""`), the value set by the `mcrypt.modes_dir` php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled-in into libmcrypt (usually /usr/local/lib/libmcrypt).

### Return Values

Normally it returns an encryption descriptor, or `false` on error.

### Examples

Example #1 mcrypt_module_open() Examples

`<?php
$td = mcrypt_module_open(MCRYPT_DES, '',
MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>`

The first line in the example above will try to open the `DES` cipher from the default directory and the `ECB` mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Example #2 Using mcrypt_module_open() in encryption

`<?php
/* Open the cipher */
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);
/* Create key (example only: MD5 is not a good hash algorithm for this) */
$key = substr(hash('md5', 'very secret key'), 0, $ks);
/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);
/* Encrypt data */
$encrypted = mcrypt_generic($td, 'This is very important data');
/* Terminate encryption handler */
mcrypt_generic_deinit($td);
/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
/* Show string */
echo trim($decrypted) . "\n";
?>`

### See Also

- mcrypt_module_close() - Closes the mcrypt module
- mcrypt_generic() - This function encrypts data
- mdecrypt_generic() - Decrypts data
- mcrypt_generic_init() - This function initializes all buffers needed for encryption
- mcrypt_generic_deinit() - This function deinitializes an encryption module

# mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_self_test — This function runs a self test on the specified module

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mcrypt_module_self_test(string `$algorithm`, string `$lib_dir` = ?): bool

This function runs the self test on the algorithm specified.

### Parameters

`algorithm`

  One of the `MCRYPT_ciphername` constants, or the name of the algorithm as string.

`lib_dir`
  The optional `lib_dir` parameter can contain the location where the algorithm module is on the system.

### Return Values

The function returns `true` if the self test succeeds, or `false` when it fails.

### Examples

Example #1 mcrypt_module_self_test() example

`<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>`

The above example will output:

    bool(true)
    bool(false)

# mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mdecrypt_generic — Decrypts data

Warning

This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

### Description

mdecrypt_generic(resource `$td`, string `$data`): string

This function decrypts data. Note that the length of the returned string can in fact be longer than the unencrypted string, due to the padding of the data.

### Parameters

`td`
  An encryption descriptor returned by mcrypt_module_open()
`data`
  Encrypted data.

### Return Values

Returns decrypted string.

### Examples

Example #1 mdecrypt_generic() Example

`<?php
/* Data */
$key = 'this is a very long key, even too long for the cipher';
$plain_text = 'very important data';
/* Open module, and create IV */
$td = mcrypt_module_open('des', '', 'ecb', '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
$iv_size = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
/* Initialize encryption handle */
if (mcrypt_generic_init($td, $key, $iv) != -1) {
/* Encrypt data */
$c_t = mcrypt_generic($td, $plain_text);
mcrypt_generic_deinit($td);
/* Reinitialize buffers for decryption */
mcrypt_generic_init($td, $key, $iv);
$p_t = mdecrypt_generic($td, $c_t);
/* Clean up */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
}
if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
echo "ok\n";
} else {
echo "error\n";
}
?>`

The example above shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

### See Also

- mcrypt_generic() - This function encrypts data
- mcrypt_generic_init() - This function initializes all buffers needed for encryption
- mcrypt_generic_deinit() - This function deinitializes an encryption module

## Table of Contents

- mcrypt_create_iv — Creates an initialization vector (IV) from a random source
- mcrypt_decrypt — Decrypts crypttext with given parameters
- mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
- mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
- mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
- mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
- mcrypt_enc_get_modes_name — Returns the name of the opened mode
- mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
- mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
- mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
- mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
- mcrypt_enc_self_test — Runs a self test on the opened module
- mcrypt_encrypt — Encrypts plaintext with given parameters
- mcrypt_generic — This function encrypts data
- mcrypt_generic_deinit — This function deinitializes an encryption module
- mcrypt_generic_init — This function initializes all buffers needed for encryption
- mcrypt_get_block_size — Gets the block size of the specified cipher
- mcrypt_get_cipher_name — Gets the name of the specified cipher
- mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
- mcrypt_get_key_size — Gets the key size of the specified cipher
- mcrypt_list_algorithms — Gets an array of all supported ciphers
- mcrypt_list_modes — Gets an array of all supported modes
- mcrypt_module_close — Closes the mcrypt module
- mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
- mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
- mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
- mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
- mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
- mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
- mcrypt_module_open — Opens the module of the algorithm and the mode to be used
- mcrypt_module_self_test — This function runs a self test on the specified module
- mdecrypt_generic — Decrypts data

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Mcrypt ciphers
- Mcrypt Functions
  - mcrypt_create_iv — Creates an initialization vector (IV) from a random source
  - mcrypt_decrypt — Decrypts crypttext with given parameters
  - mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
  - mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
  - mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
  - mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
  - mcrypt_enc_get_modes_name — Returns the name of the opened mode
  - mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  - mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
  - mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
  - mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
  - mcrypt_enc_self_test — Runs a self test on the opened module
  - mcrypt_encrypt — Encrypts plaintext with given parameters
  - mcrypt_generic — This function encrypts data
  - mcrypt_generic_deinit — This function deinitializes an encryption module
  - mcrypt_generic_init — This function initializes all buffers needed for encryption
  - mcrypt_get_block_size — Gets the block size of the specified cipher
  - mcrypt_get_cipher_name — Gets the name of the specified cipher
  - mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
  - mcrypt_get_key_size — Gets the key size of the specified cipher
  - mcrypt_list_algorithms — Gets an array of all supported ciphers
  - mcrypt_list_modes — Gets an array of all supported modes
  - mcrypt_module_close — Closes the mcrypt module
  - mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
  - mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
  - mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  - mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
  - mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
  - mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
  - mcrypt_module_open — Opens the module of the algorithm and the mode to be used
  - mcrypt_module_self_test — This function runs a self test on the specified module
  - mdecrypt_generic — Decrypts data

# Mhash

# Introduction

These functions are intended to work with » mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.

This is an interface to the mhash library. Mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the constants page. The general rule is that you can access the hash algorithm from PHP with `MHASH_hashname`. For example, to access TIGER you use the PHP constant `MHASH_TIGER`.

> Note:

> This extension is obsoleted by Hash.

> Note:

> As of PHP 7.0.0 the Mhash extension has been fully integrated into the Hash extension. Therefore, it is no longer possible to detect Mhash support with extension_loaded(); use function_exists() instead. Furthermore, Mhash is no longer reported by get_loaded_extensions() and related features.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

## Installation

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash installation directory.

As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension. This makes the mhash installation directory have no effect, and requires the hash extension enabled to make the mhash support available.

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

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but it is listed in the mhash documentation as supported, you can safely assume that this documentation is outdated.

`MHASH_ADLER32` (int)
`MHASH_CRC32` (int)
`MHASH_CRC32B` (int)
`MHASH_CRC32C` (int)
  Available as of PHP 7.4.0.
`MHASH_FNV132` (int)
`MHASH_FNV1A32` (int)
`MHASH_FNV164` (int)
`MHASH_FNV1A64` (int)
`MHASH_GOST` (int)
`MHASH_HAVAL128` (int)
`MHASH_HAVAL160` (int)
`MHASH_HAVAL192` (int)
`MHASH_HAVAL224` (int)
`MHASH_HAVAL256` (int)
`MHASH_JOAAT` (int)
`MHASH_MD2` (int)
`MHASH_MD4` (int)
`MHASH_MD5` (int)
`MHASH_MURMUR3A` (int)
  Available as of PHP 8.1.0.
`MHASH_MURMUR3C` (int)
  Available as of PHP 8.1.0.
`MHASH_MURMUR3F` (int)
  Available as of PHP 8.1.0.
`MHASH_RIPEMD128` (int)
`MHASH_RIPEMD160` (int)
`MHASH_RIPEMD256` (int)
`MHASH_RIPEMD320` (int)
`MHASH_SHA1` (int)
`MHASH_SHA224` (int)
`MHASH_SHA256` (int)
`MHASH_SHA384` (int)
`MHASH_SHA512` (int)
`MHASH_SNEFRU256` (int)
`MHASH_TIGER` (int)
`MHASH_TIGER128` (int)
`MHASH_TIGER160` (int)
`MHASH_WHIRLPOOL` (int)
`MHASH_XXH32` (int)
`MHASH_XXH64` (int)
`MHASH_XXH3` (int)
`MHASH_XXH128` (int)

# Examples

Example #1 Computes the MD5 digest and hmac and print it out as hex

`<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>`

The above example will output:

    The hash is d03cb659cbf9192dcd066272249f8412
    The hmac is 750c783e6ab0b503eaa86e310a5db738

# Mhash Functions

# mhash

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash — Computes hash

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
mhash(int `$algo`, string `$data`, ?string `$key` = `null`): string|false

mhash() applies a hash function specified by `algo` to the `data`.

### Parameters

`algo`

  The hash ID. One of the `MHASH_hashname` constants.

`data`

  The user input, as a string.

`key`

  If specified, the function will return the resulting HMAC instead. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode.

### Return Values

Returns the resulting hash (also called digest) or HMAC as a string, or `false` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use the `hash_*()` functions instead.
8.0.0 | `key` is now nullable.

# mhash_count

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_count — Gets the highest available hash ID

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
mhash_count(): int

Gets the highest available hash ID.

### Parameters

This function has no parameters.

### Return Values

Returns the highest available hash ID. Hashes are numbered from 0 to this hash ID.

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use the `hash_*()` functions instead.

### Examples

Example #1 Traversing all hashes

`<?php
$nr = mhash_count();
for ($i = 0; $i <= $nr; $i++) {
echo sprintf("The blocksize of %s is %d\n",
mhash_get_hash_name($i),
mhash_get_block_size($i));
}
?>`

# mhash_get_block_size

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_get_block_size — Gets the block size of the specified hash

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
mhash_get_block_size(int `$algo`): int|false

Gets the size of a block of the specified `algo`.

### Parameters

`algo`

  The hash ID. One of the `MHASH_hashname` constants.

### Return Values

Returns the size in bytes or `false`, if the `algo` does not exist.

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use the `hash_*()` functions instead.

### Examples

Example #1 mhash_get_block_size() Example

`<?php
echo mhash_get_block_size(MHASH_MD5); // 16
?>`

# mhash_get_hash_name

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_get_hash_name — Gets the name of the specified hash

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
mhash_get_hash_name(int `$algo`): string|false

Gets the name of the specified `algo`.

### Parameters

`algo`

  The hash ID. One of the `MHASH_hashname` constants.

### Return Values

Returns the name of the hash or `false`, if the hash does not exist.

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use the `hash_*()` functions instead.

### Examples

Example #1 mhash_get_hash_name() Example

`<?php
echo mhash_get_hash_name(MHASH_MD5); // MD5
?>`

# mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

mhash_keygen_s2k — Generates a key

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
mhash_keygen_s2k(
int `$algo`,
string `$password`,
string `$salt`,
int `$length`
): string|false

Generates a key according to the given `algo`, using an user provided `password`.

This is the Salted S2K algorithm as specified in the OpenPGP document (» RFC 2440).

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.

### Parameters

`algo`

  The hash ID used to create the key. One of the `MHASH_hashname` constants.

`password`

  An user supplied password.

`salt`

  Must be different and random enough for every key you generate in order to create different keys. Because `salt` must be known when you check the keys, it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

`length`

  The key length, in bytes.

### Return Values

Returns the generated key as a string, or `false` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use the `hash_*()` functions instead.

## Table of Contents

- mhash — Computes hash
- mhash_count — Gets the highest available hash ID
- mhash_get_block_size — Gets the block size of the specified hash
- mhash_get_hash_name — Gets the name of the specified hash
- mhash_keygen_s2k — Generates a key

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Examples
- Mhash Functions
  - mhash — Computes hash
  - mhash_count — Gets the highest available hash ID
  - mhash_get_block_size — Gets the block size of the specified hash
  - mhash_get_hash_name — Gets the name of the specified hash
  - mhash_keygen_s2k — Generates a key

# OpenSSL

# Introduction

This extension binds functions of » OpenSSL library for symmetric and asymmetric encryption and decryption, PBKDF2, PKCS7, PKCS12, X509 and other crypto operations. In addition to that it provides implementation of TLS streams.

OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

In order to use the OpenSSL functions you need to install the » OpenSSL library. PHP 7.0 requires OpenSSL >= 0.9.8, < 1.2. PHP 7.1-8.0 requires OpenSSL >= 1.0.1, < 3.0. PHP >= 8.1 requires OpenSSL >= 1.0.2, < 4.0. PHP >= 8.4 requires OpenSSL >= 1.1.1, < 4.0.

Warning

You are strongly encouraged to use a maintained OpenSSL version, otherwise your web server could be vulnerable to attack.

## Installation

To use PHP's OpenSSL support you must also compile PHP --with-openssl.

The OpenSSL library also has additional requirements for normal operation at run-time. Most notably, OpenSSL requires access to a random or pseudo-random number generator; on most Unix and Unix-like platforms (including Linux), this means that it must have access to a `/dev/urandom` or `/dev/random` device.

The configure option --with-system-ciphers is available which causes PHP to use the system cipher list instead of a hard-coded default.

> Note: Note to Win32 Users

> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll, or, as of OpenSSL 1.1, libcrypto-*.dll

> Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf file on your system. We include a sample configuration file in our win32 binary distributions, in the extras/ssl directory.

> PHP will search for the openssl.cnf using the following logic:

> - the `OPENSSL_CONF` environmental variable, if set, will be used as the path (including filename) of the configuration file.
> - the `SSLEAY_CONF` environmental variable, if set, will be used as the path (including filename) of the configuration file.
> - The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is C:\Program Files\Common Files\SSL\openssl.cnf (x64) or C:\Program Files (x86)\Common Files\SSL\openssl.cnf (x86), or, prior to PHP 7.4.0, C:\usr\local\ssl\openssl.cnf.
> In your installation, you need to decide whether to install the configuration file in the default path or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the `options` of the functions that require a configuration file.
> Caution

> Ensure that non-privileged users are not allowed to modify openssl.cnf.

> As of OpenSSL 3.0.0, which is used on Windows by default as of PHP 8.2.0, several algorithms have been deemed legacy. Such algorithms have commonly fallen out of use, have been deemed insecure by the cryptography community, or something similar. These algorithms are still available via the legacy provider (extras/ssl/legacy.dll); its usage is described in the » provider configuration section of the OpenSSL manual.

### Changelog

Version | Description
--- | ---
7.4.0 | The --with-openssl[=DIR] doesn't accept a directory argument anymore in favor of setting the pkg-config variable PKG_CONFIG_PATH to OpenSSL location, or by specifying the OPENSSL_LIBS and OPENSSL_CFLAGS variables.
7.4.0 | The OpenSSL default config path has been changed from C:\usr\local\ssl to C:\Program Files\Common Files\SSL and C:\Program Files (x86)\Common Files\SSL, respectively.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

openssl Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
openssl.cafile | "" | `INI_PERDIR` |
openssl.capath | "" | `INI_PERDIR` |
openssl.libctx | "custom" | `INI_PERDIR` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`openssl.cafile` string

  Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.

`openssl.capath` string

  If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.

`openssl.libctx` string
  Specifies the type of OpenSSL library context to use. The default value, `custom`, creates a separate library context for each worker or thread. This improves isolation from other libraries using OpenSSL and, in ZTS builds, increases separation between threads. It is also possible to use the `default` value, which causes PHP to use OpenSSL's global default library context.

See also the SSL stream context options.

## Resource Types

Prior to PHP 8.0.0, there were 3 resource types defined in the OpenSSL module:

- `OpenSSL key`
- `OpenSSL X.509`
- `OpenSSL X.509 CSR`

# Predefined Constants

## Table of Contents

- Purpose checking flags
- Padding flags for asymmetric encryption
- Key types
- PKCS7 Flags/Constants
- CMS Flags/Constants
- Signature Algorithms
- Ciphers
- Version constants
- Server Name Indication constants
- Other 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.

## Purpose checking flags

`X509_PURPOSE_SSL_CLIENT` (int)
`X509_PURPOSE_SSL_SERVER` (int)
`X509_PURPOSE_NS_SSL_SERVER` (int)
`X509_PURPOSE_SMIME_SIGN` (int)
`X509_PURPOSE_SMIME_ENCRYPT` (int)
`X509_PURPOSE_CRL_SIGN` (int)
`X509_PURPOSE_ANY` (int)

## Padding flags for asymmetric encryption

`OPENSSL_PKCS1_PADDING` (int)
`OPENSSL_SSLV23_PADDING` (int)
`OPENSSL_NO_PADDING` (int)
`OPENSSL_PKCS1_OAEP_PADDING` (int)

## Key types

`OPENSSL_KEYTYPE_RSA` (int)
  RSA key type.
`OPENSSL_KEYTYPE_DSA` (int)
  DSA key type.
`OPENSSL_KEYTYPE_DH` (int)
  DH (Diffie-Hellman) key type.
`OPENSSL_KEYTYPE_EC` (int)
  Elliptic curve key type.
`OPENSSL_KEYTYPE_X25519` (int)
  X25519 curve key type. This constant is only available when PHP is compiled with OpenSSL 3.0+.
`OPENSSL_KEYTYPE_ED25519` (int)
  Ed25519 curve key type. This constant is only available when PHP is compiled with OpenSSL 3.0+.
`OPENSSL_KEYTYPE_X448` (int)
  X448 curve key type. This constant is only available when PHP is compiled with OpenSSL 3.0+.
`OPENSSL_KEYTYPE_ED448` (int)
  Ed448 curve key type. This constant is only available when PHP is compiled with OpenSSL 3.0+.

## PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

PKCS7 CONSTANTS
Constant | Description
--- | ---
`PKCS7_TEXT` (int) | Adds `text/plain` content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type `text/plain` then an error will occur.
`PKCS7_BINARY` (int) | Normally the input message is converted to "canonical" format which is effectively using `CR` and `LF` as end of line: as required by the S/MIME specification. When this option is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
`PKCS7_NOINTERN` (int) | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the `untrusted_certificates_filename` parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
`PKCS7_NOVERIFY` (int) | Do not verify the signers certificate of a signed message.
`PKCS7_NOCHAIN` (int) | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
`PKCS7_NOCERTS` (int) | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the `untrusted_certificates_filename` to openssl_pkcs7_verify() for example).
`PKCS7_NOATTR` (int) | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
`PKCS7_DETACHED` (int) | When signing a message, use cleartext signing with the MIME type `"multipart/signed"`. This is the default if you do not specify any `flags` to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
`PKCS7_NOSIGS` (int) | Don't try and verify the signatures on a message
`PKCS7_NOOLDMIMETYPE` (int) | Available as of PHP 8.3.0. Sets the content-type to `application/pkcs7-mime` instead of `application/x-pkcs7-mime` to encrypt a message.

## CMS Flags/Constants

The CMS functions make use of flags which are specified using a bitfield which can include one or more of the following values:

CMS CONSTANTS
Constant | Description
--- | ---
`OPENSSL_CMS_TEXT` (int) | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
`OPENSSL_CMS_BINARY` (int) | Normally the input message is converted to "canonical" format which is effectively using `CR` and `LF` as end of line: as required by the CMS specification. When this option is present, no translation occurs. This is useful when handling binary data which may not be in CMS format.
`OPENSSL_CMS_NOINTERN` (int) | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the `untrusted_certificates_filename` parameter of openssl_cms_verify() are used. The supplied certificates can still be used as untrusted CAs however.
`OPENSSL_CMS_NOVERIFY` (int) | Do not verify the signers certificate of a signed message.
`OPENSSL_CMS_NOCERTS` (int) | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the `untrusted_certificates_filename` to openssl_cms_verify() for example).
`OPENSSL_CMS_NOATTR` (int) | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
`OPENSSL_CMS_DETACHED` (int) | When signing a message, use cleartext signing with the MIME type `"multipart/signed"`. This is the default if you do not specify any `flags` to openssl_cms_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
`OPENSSL_CMS_NOSIGS` (int) | Don't try and verify the signatures on a message
`OPENSSL_CMS_OLDMIMETYPE` (int) | Available as of PHP 8.3.0. Sets the content-type to `application/x-pkcs7-mime` instead of `application/pkcs7-mime` to encrypt a message.

## Signature Algorithms

`OPENSSL_ALGO_DSS1` (int)
`OPENSSL_ALGO_SHA1` (int)
  Used as default algorithm by openssl_sign() and openssl_verify().
`OPENSSL_ALGO_SHA224` (int)
`OPENSSL_ALGO_SHA256` (int)
`OPENSSL_ALGO_SHA384` (int)
`OPENSSL_ALGO_SHA512` (int)
`OPENSSL_ALGO_RMD160` (int)
`OPENSSL_ALGO_MD5` (int)
`OPENSSL_ALGO_MD4` (int)
`OPENSSL_ALGO_MD2` (int)
  This constant is only available if PHP is compiled with MD2 support. This requires passing in the `-DHAVE_OPENSSL_MD2_H` CFLAG when compiling PHP, and `enable-md2` when compiling OpenSSL 1.0.0+.

## Ciphers

`OPENSSL_DEFAULT_STREAM_CIPHERS` (string)
  List of default ciphers.
`OPENSSL_CIPHER_RC2_40` (int)
`OPENSSL_CIPHER_RC2_128` (int)
`OPENSSL_CIPHER_RC2_64` (int)
`OPENSSL_CIPHER_DES` (int)
`OPENSSL_CIPHER_3DES` (int)

`OPENSSL_CIPHER_AES_128_CBC` (int)
`OPENSSL_CIPHER_AES_192_CBC` (int)
`OPENSSL_CIPHER_AES_256_CBC` (int)

## Version constants

`OPENSSL_VERSION_TEXT` (string)
`OPENSSL_VERSION_NUMBER` (int)

## Server Name Indication constants

`OPENSSL_TLSEXT_SERVER_NAME` (int)
  Whether SNI support is available or not.

> Note:

> This constant requires PHP to be built with OpenSSL 0.9.8j or greater.

## Other Constants

`OPENSSL_RAW_DATA` (int)
  If `OPENSSL_RAW_DATA` is set in the openssl_encrypt() or openssl_decrypt(), the returned data is returned as-is. When it is not specified, Base64 encoded data is returned to the caller.
`OPENSSL_DONT_ZERO_PAD_KEY` (int)
  Prevents openssl_encrypt() from padding keys that are shorter than the default key length.
`OPENSSL_ZERO_PADDING` (int)
  By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If `OPENSSL_ZERO_PADDING` is set in the openssl_encrypt() or openssl_decrypt() `options` then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
`OPENSSL_ENCODING_SMIME` (int)
  Indicates that encoding is S/MIME.
`OPENSSL_ENCODING_DER` (int)
  Indicates that encoding is DER.
`OPENSSL_ENCODING_PEM` (int)
  Indicates that encoding is PEM.

# Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. Following methods may be used to get them:

- Certificates

  1. An OpenSSLCertificate instance (or prior to PHP 8.0.0, a resource of type `OpenSSL X.509`) returned from openssl_x509_read()
  2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
  3. A string containing the content of a certificate, PEM encoded, may start with `-----BEGIN CERTIFICATE-----`

- Certificate Signing Requests (CSRs)

  1. An OpenSSLCertificateSigningRequest instance (or prior to PHP 8.0.0, a resource of type `OpenSSL X.509 CSR`) returned from openssl_csr_new()
  2. A string having the format file://path/to/csr.pem; the named file must contain a PEM encoded CSR
  3. A string containing the content of a CSR, PEM encoded, may start with `-----BEGIN CERTIFICATE REQUEST-----`

- Public/Private Keys

  1. An OpenSSLAsymmetricKey instance (or prior to PHP 8.0.0, a resource of type `OpenSSL key`) returned from openssl_get_publickey() or openssl_get_privatekey()
  2. For public keys only: an OpenSSLCertificate instance (or prior to PHP 8.0.0, a resource of type `OpenSSL X.509`)
  3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
  4. A string containing the content of a certificate/key, PEM encoded, may start with `-----BEGIN PUBLIC KEY-----`
  5. For private keys, you may also use the syntax `array($key, $passphrase)` where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

# Certificate Verification

When calling a function that will verify a signature/certificate, the `ca_info` parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

# OpenSSL Functions

# openssl_cipher_iv_length

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

openssl_cipher_iv_length — Gets the cipher iv length

### Description

openssl_cipher_iv_length(string `$cipher_algo`): int|false

Gets the cipher initialization vector (iv) length.

### Parameters

`cipher_algo`

  The cipher method, see openssl_get_cipher_methods() for a list of potential values.

### Return Values

Returns the cipher length on success, or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error when the cipher algorithm is unknown.

### Examples

Example #1 openssl_cipher_iv_length() example

`<?php
$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);
echo $ivlen;
?>`

The above example will output something similar to:

    16

# openssl_cipher_key_length

(PHP 8 >= 8.2.0)

openssl_cipher_key_length — Gets the cipher key length

### Description

openssl_cipher_key_length(string `$cipher_algo`): int|false

Gets the cipher key length.

### Parameters

`cipher_algo`

  The cipher method, see openssl_get_cipher_methods() for a list of potential values.

### Return Values

Returns the cipher length on success, or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error when the cipher algorithm is unknown.

### Examples

Example #1 openssl_cipher_key_length() example

`<?php
$method = 'AES-128-CBC';
var_dump(openssl_cipher_key_length($method));
?>`

The above example will output something similar to:

    int(16)

# openssl_cms_decrypt

(PHP 8)

openssl_cms_decrypt — Decrypt a CMS message

### Description

openssl_cms_decrypt(
string `$input_filename`,
string `$output_filename`,
#[\SensitiveParameter] OpenSSLCertificate|string `$certificate`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null `$private_key` = `null`,
int `$encoding` = `OPENSSL_ENCODING_SMIME`
): bool

Decrypts a CMS message.

### Parameters

`input_filename`

  The name of a file containing encrypted content.

`output_filename`

  The name of the file to deposit the decrypted content.

`certificate`

  The name of the file containing a certificate of the recipient.

`private_key`

  The name of the file containing a PKCS#8 key.

`encoding`

  The encoding of the input file. One of `OPENSSL_ENCODING_SMIME`, `OPENSSL_ENCODING_DER` or `OPENSSL_ENCODING_PEM`.

### Return Values

Returns `true` on success or `false` on failure.

# openssl_cms_encrypt

(PHP 8)

openssl_cms_encrypt — Encrypt a CMS message

### Description

openssl_cms_encrypt(
string `$input_filename`,
string `$output_filename`,
OpenSSLCertificate|array|string `$certificate`,
?array `$headers`,
int `$flags` = 0,
int `$encoding` = `OPENSSL_ENCODING_SMIME`,
string|int `$cipher_algo` = `OPENSSL_CIPHER_AES_128_CBC`
): bool

This function encrypts content to one or more recipients, based on the certificates that are passed to it.

### Parameters

`input_filename`

  The file to be encrypted.

`output_filename`

  The output file.

`certificate`

  Recipients to encrypt to.

`headers`

  Headers to include when S/MIME is used.

`flags`

  Flags to be passed to CMS_sign.

`encoding`

  An encoding to output. One of `OPENSSL_ENCODING_SMIME`, `OPENSSL_ENCODING_DER` or `OPENSSL_ENCODING_PEM`.

`cipher_algo`

  A cipher to use.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | `cipher_algo` is now of type int or string. Previously, it was of type int.
8.1.0 | The default cipher algorithm (`cipher_algo`) is now AES-128-CBC (`OPENSSL_CIPHER_AES_128_CBC`). Previously, PKCS7/CMS was used (`OPENSSL_CIPHER_RC2_40`).

# openssl_cms_read

(PHP 8)

openssl_cms_read — Export the CMS file to an array of PEM certificates

### Description

openssl_cms_read(string `$input_filename`, array `&$certificates`): bool

Performs the exact analog to openssl_pkcs7_read().

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`input_filename`

`certificates`

### Return Values

Returns `true` on success or `false` on failure.

# openssl_cms_sign

(PHP 8)

openssl_cms_sign — Sign a file

### Description

openssl_cms_sign(
string `$input_filename`,
string `$output_filename`,
OpenSSLCertificate|string `$certificate`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
?array `$headers`,
int `$flags` = 0,
int `$encoding` = `OPENSSL_ENCODING_SMIME`,
?string `$untrusted_certificates_filename` = `null`
): bool

This function signs a file with an X.509 certificate and key.

### Parameters

`input_filename`

  The name of the file to be signed.

`output_filename`

  The name of the file to deposit the results.

`certificate`

  The signing certificate. See Key/Certificate parameters for a list of valid values.

`private_key`

  The key associated with `certificate`. See Key/Certificate parameters for a list of valid values.

`headers`

  An array of headers to be included in S/MIME output.

`flags`

  Flags to be passed to cms_sign().

`encoding`

  The encoding of the output file. One of `OPENSSL_ENCODING_SMIME`, `OPENSSL_ENCODING_DER` or `OPENSSL_ENCODING_PEM`.

`untrusted_certificates_filename`

  Intermediate certificates to be included in the signature.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 openssl_cms_sign() example

`<?php
openssl_cms_sign('input.txt', 'output.txt', 'file://cert.pem', 'file://privkey.pem', null, OPENSSL_CMS_BINARY, OPENSSL_ENCODING_DER, 'chain.pem');
?>`

# openssl_cms_verify

(PHP 8)

openssl_cms_verify — Verify a CMS signature

### Description

openssl_cms_verify(
string `$input_filename`,
int `$flags` = 0,
?string `$certificates` = `null`,
array `$ca_info` = [],
?string `$untrusted_certificates_filename` = `null`,
?string `$content` = `null`,
?string `$pk7` = `null`,
?string `$sigfile` = `null`,
int `$encoding` = `OPENSSL_ENCODING_SMIME`
): bool

This function verifies a CMS signature, either attached or detached, with the specified encoding.

### Parameters

`input_filename`

  The input file.

`flags`

  Flags to pass to cms_verify().

`certificates`

  A file with the signer certificate and optionally intermediate certificates.

`ca_info`

  An array containing self-signed certificate authority certificates.

`untrusted_certificates_filename`

  A file containing additional intermediate certificates.

`content`

  A file pointing to the content when signatures are detached.

`pk7`

`sigfile`

  A file to save the signature to.

`encoding`

  The encoding of the input file. One of `OPENSSL_ENCODING_SMIME`, `OPENSSL_ENCODING_DER` or `OPENSSL_ENCODING_PEM`.

### Return Values

Returns `true` on success or `false` on failure.

# openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_export — Exports a CSR as a string

### Description

openssl_csr_export(OpenSSLCertificateSigningRequest|string `$csr`, string `&$output`, bool `$no_text` = `true`): bool

openssl_csr_export() takes the Certificate Signing Request represented by `csr` and stores it in PEM format in `output`, which is passed by reference.

### Parameters

`csr`

  See CSR parameters for a list of valid values.

`output`

  on success, this string will contain the PEM encoded CSR

`no_text`

  The optional parameter `notext` affects the verbosity of the output; if it is `false`, then additional human-readable information is included in the output. The default value of `notext` is `true`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `csr` accepts an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_csr_export() example

`<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$configargs = array(
'digest_alg' => 'sha256WithRSAEncryption'
);
$csr = openssl_csr_new($subject, $private_key, $configargs);
openssl_csr_export($csr, $csr_string);
echo $csr_string;
?>`

### See Also

- openssl_csr_export_to_file() - Exports a CSR to a file
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_export_to_file — Exports a CSR to a file

### Description

openssl_csr_export_to_file(OpenSSLCertificateSigningRequest|string `$csr`, string `$output_filename`, bool `$no_text` = `true`): bool

openssl_csr_export_to_file() takes the Certificate Signing Request represented by `csr` and saves it in PEM format into the file named by `output_filename`.

### Parameters

`csr`

  See CSR parameters for a list of valid values.

`output_filename`

  Path to the output file.

`no_text`

  The optional parameter `notext` affects the verbosity of the output; if it is `false`, then additional human-readable information is included in the output. The default value of `notext` is `true`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `csr` accepts an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_csr_export_to_file() example

`<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384') );
openssl_pkey_export_to_file($private_key, 'example-priv.key');
// Along with the subject, the CSR contains the public key corresponding to the private key
openssl_csr_export_to_file($csr, 'example-csr.pem');
?>`

### See Also

- openssl_csr_export() - Exports a CSR as a string
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_csr_get_public_key

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_csr_get_public_key — Returns the public key of a CSR

### Description

openssl_csr_get_public_key(OpenSSLCertificateSigningRequest|string `$csr`, bool `$short_names` = `true`): OpenSSLAsymmetricKey|false

openssl_csr_get_public_key() extracts the public key from `csr` and prepares it for use by other functions.

### Parameters

`csr`

  See CSR parameters for a list of valid values.

`short_names`
  Warning

  This parameter is ignored

### Return Values

Returns an OpenSSLAsymmetricKey on success, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was returned.
8.0.0 | `csr` accepts an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_csr_get_public_key() example

`<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha256') );
$public_key = openssl_csr_get_public_key($csr);
$info = openssl_pkey_get_details($public_key);
echo $info['key'];
?>`

### See Also

- openssl_csr_get_subject() - Returns the subject of a CSR
- openssl_csr_new() - Generates a CSR
- openssl_pkey_get_details() - Returns an array with the key details
- openssl_pkey_export_to_file() - Gets an exportable representation of a key into a file
- openssl_pkey_export() - Gets an exportable representation of a key into a string

# openssl_csr_get_subject

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_csr_get_subject — Returns the subject of a CSR

### Description

openssl_csr_get_subject(OpenSSLCertificateSigningRequest|string `$csr`, bool `$short_names` = `true`): array|false

openssl_csr_get_subject() returns subject distinguished name information encoded in the `csr` including fields commonName (CN), organizationName (O), countryName (C) etc.

### Parameters

`csr`

  See CSR parameters for a list of valid values.

`short_names`

  `short_names` controls how the data is indexed in the array - if `short_names` is `true` (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

### Return Values

Returns an associative array with subject description, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `csr` accepts an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_csr_get_subject() example

`<?php
$subject = array(
"countryName" => "CA",
"stateOrProvinceName" => "Alberta",
"localityName" => "Calgary",
"organizationName" => "XYZ Widgets Inc",
"organizationalUnitName" => "PHP Documentation Team",
"commonName" => "Wez Furlong",
"emailAddress" => "wez@example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$configargs = array(
'digest_alg' => 'sha512WithRSAEncryption'
);
$csr = openssl_csr_new($subject, $privkey, $configargs);
print_r(openssl_csr_get_subject($csr));
?>`

The above example will output something similar to:

    Array
    (
        [C] => CA
        [ST] => Alberta
        [L] => Calgary
        [O] => XYZ Widgets Inc
        [OU] => PHP Documentation Team
        [CN] => Wez Furlong
        [emailAddress] => wez@example.com
    )

### See Also

- openssl_csr_new() - Generates a CSR
- openssl_csr_get_public_key() - Returns the public key of a CSR
- openssl_x509_parse() - Parse an X509 certificate and return the information as an array

# openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_new — Generates a CSR

### Description

openssl_csr_new(
array `$distinguished_names`,
#[\SensitiveParameter] ?OpenSSLAsymmetricKey `&$private_key`,
?array `$options` = `null`,
?array `$extra_attributes` = `null`
): OpenSSLCertificateSigningRequest|bool

openssl_csr_new() generates a new CSR based on the information provided by `distinguished_names`.

> Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

### Parameters

`distinguished_names`

  The Distinguished Name or subject fields to be included in the certificate. The `distinguished_names` is an associative array where the keys represent the attribute names of Distinguished Names and the values can either be strings (for single value) or arrays (if multiple values need to be set).

`private_key`

  `private_key` should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions), or `null` variable. If its value is `null` variable, a new private key is generated based on the supplied `options` and assigned to supplied variable. The corresponding public portion of the key will be used to sign the CSR.

`options`

  By default, the information in your system `openssl.conf` is used to initialize the request; you can specify a configuration file section by setting the `config_section_section` key in `options`. You can also specify an alternative OpenSSL configuration file by setting the value of the `config` key to the path of the file you want to use. The following keys, if present in `options` behave as their equivalents in the `openssl.conf`, as listed in the table below.

  Configuration overrides
  `options` key | type | `openssl.conf` equivalent | description
  --- | --- | --- | ---
  digest_alg | string | default_md | Digest method or signature hash, usually one of openssl_get_md_methods()
  x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate
  req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR
  private_key_bits | int | default_bits | Specifies how many bits should be used to generate a private key
  private_key_type | int | none | Specifies the type of private key to create. This can be one of `OPENSSL_KEYTYPE_DSA`, `OPENSSL_KEYTYPE_DH`, `OPENSSL_KEYTYPE_RSA` or `OPENSSL_KEYTYPE_EC`. The default value is `OPENSSL_KEYTYPE_RSA`.
  encrypt_key | bool | encrypt_key | Should an exported key (with passphrase) be encrypted?
  encrypt_key_cipher | int | none | One of cipher constants.
  curve_name | string | none | One of openssl_get_curve_names().
  config | string | N/A | Path to your own alternative openssl.conf file.

`extra_attributes`

  `extra_attributes` is used to specify additional attributes for the CSR. It is an associative arrays where the keys are converted to OIDs and applied as CSR attributes.

### Return Values

Returns the CSR on success, `true` if CSR creation is successful but signing fails or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `distinguished_names` associative array now supports arrays as values, allowing multiple values to be specified for a single attribute.
8.4.0 | The `extra_attributes` parameter now correctly sets the CSR attributes, rather than modifying the subject's Distinguished Name as it previously did incorrectly.
8.0.0 | On success, this function returns an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was returned.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was accepted.
7.1.0 | `options` now also supports `curve_name`.

### Examples

Example #1 Creating a self-signed certificate

`<?php
// for SSL server certificates the commonName is the domain name to be secured
// for S/MIME email certificates the commonName is the owner of the email address
// location and identification fields refer to the owner of domain or email subject to be secured
$dn = array(
"countryName" => "GB",
"stateOrProvinceName" => "Somerset",
"localityName" => "Glastonbury",
"organizationName" => "The Brain Room Limited",
"organizationalUnitName" => "PHP Documentation Team",
"commonName" => "Wez Furlong",
"emailAddress" => "wez@example.com"
);
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha256'));
// Generate a self-signed cert, valid for 365 days
$x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array('digest_alg' => 'sha256'));
// Save your private key, CSR and self-signed cert for later use
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($x509, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);
// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
echo $e . "\n";
}
?>`

Example #2 Creating a self-signed ECC certificate (as of PHP 7.1.0)

`<?php
$subject = array(
"commonName" => "docs.php.net",
);
// Generate a new private (and public) key pair
$private_key = openssl_pkey_new(array(
"private_key_type" => OPENSSL_KEYTYPE_EC,
"curve_name" => 'prime256v1',
));
// Generate a certificate signing request
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384'));
// Generate self-signed EC cert
$x509 = openssl_csr_sign($csr, null, $private_key, $days=365, array('digest_alg' => 'sha384'));
openssl_x509_export_to_file($x509, 'ecc-cert.pem');
openssl_pkey_export_to_file($private_key, 'ecc-private.key');
?>`

### See Also

- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate

### Description

openssl_csr_sign(
OpenSSLCertificateSigningRequest|string `$csr`,
OpenSSLCertificate|string|null `$ca_certificate`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
int `$days`,
?array `$options` = `null`,
int `$serial` = 0,
?string `$serial_hex` = `null`
): OpenSSLCertificate|false

openssl_csr_sign() generates an x509 certificate from the given CSR.

> Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

### Parameters

`csr`

  A CSR previously generated by openssl_csr_new(). It can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export().

`ca_certificate`

  The generated certificate will be signed by `ca_certificate`. If `ca_certificate` is `null`, the generated certificate will be a self-signed certificate.

`private_key`

  `private_key` is the private key that corresponds to `ca_certificate`.

`days`

  `days` specifies the length of time for which the generated certificate will be valid, in days.

`options`

  You can finetune the CSR signing by `options`. See openssl_csr_new() for more information about `options`.

`serial`

  An optional the serial number of issued certificate. If not specified it will default to 0.

`serial_hex`

  An optional hexadecimal string representing the serial number of the issued certificate. If set, it takes precedence over the `serial` parameter value. If not specified or set to `null`, the `serial` parameter value is used instead.

### Return Values

Returns an OpenSSLCertificate on success, `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `serial_hex` parameter is added.
8.0.0 | On success, this function returns an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was returned.
8.0.0 | `csr` accepts an OpenSSLCertificateSigningRequest instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.
8.0.0 | `ca_certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### Examples

Example #1 openssl_csr_sign() example - signing a CSR (how to implement your own CA)

`<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];
// We will sign the request using our own "certificate authority"
// certificate. You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate
// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");
$usercert = openssl_csr_sign($csrdata, $cacert, $privkey, 365, array('digest_alg'=>'sha256') );
// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;
// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
echo $e . "\n";
}
?>`

# openssl_decrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_decrypt — Decrypts data

### Description

openssl_decrypt(
string `$data`,
string `$cipher_algo`,
#[\SensitiveParameter] string `$passphrase`,
int `$options` = 0,
string `$iv` = "",
?string `$tag` = `null`,
string `$aad` = ""
): string|false

Takes a raw or base64 encoded string and decrypts it using a given method and passphrase.

### Parameters

`data`

  The encrypted message to be decrypted.

`cipher_algo`

  The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods().

`passphrase`

  The passphrase. If the passphrase is shorter than expected, it is silently padded with `NUL` characters; if the passphrase is longer than expected, it is silently truncated.

  Caution

  There is no key derivation function used for `passphrase` as its name might suggest. The only operation used is padding with `NUL` characters or truncation if the length is different than expected.

`options`

  `options` can be one of `OPENSSL_RAW_DATA`, `OPENSSL_ZERO_PADDING` or `OPENSSL_DONT_ZERO_PAD_KEY`.

`iv`

  A non-`null` Initialization Vector. If the IV is shorter than expected, it is padded with `NUL` characters and warning is emitted; if the passphrase is longer than expected, it is truncated and warning is emitted.

`tag`

  The authentication tag in AEAD cipher mode. If it is incorrect, the authentication fails and the function returns `false`.

  Caution

  The length of the `tag` is not checked by the function. It is the caller's responsibility to ensure that the length of the tag matches the length of the tag retrieved when openssl_encrypt() has been called. Otherwise the decryption may succeed if the given tag only matches the start of the proper tag.

`aad`

  Additional authenticated data.

### Return Values

The decrypted string on success or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an unknown cipher algorithm is passed via the `cipher_algo` parameter.

Emits an `E_WARNING` level error if an empty value is passed in via the `iv` parameter.

### Changelog

Version | Description
--- | ---
8.1.0 | `tag` is now nullable.
7.1.0 | The `tag` and `aad` parameters were added.

### See Also

- openssl_encrypt() - Encrypts data

# openssl_dh_compute_key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_dh_compute_key — Computes shared secret for public value of remote DH public key and local DH key

### Description

openssl_dh_compute_key(string `$public_key`, #[\SensitiveParameter] OpenSSLAsymmetricKey `$private_key`): string|false

The shared secret returned by openssl_dh_compute_key() is often used as an encryption key to secretly communicate with a remote party. This is known as the Diffie-Hellman key exchange.

Caution

It is important to use the same DH parameters for remote and local key pairs; otherwise, the generated secret between the two parties will not match.

> Note: ECDH is only supported as of PHP 8.1.0 and OpenSSL 3.0.0.

### Parameters

`public_key`

  DH Public key of the remote party.

`private_key`

  A local DH private key, corresponding to the public key to be shared with the remote party.

### Return Values

Returns shared secret on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey now; previously, a resource of type `OpenSSL key` was accepted.

### Examples

Example #1 Compute a shared secret

First generate a public/private DH keypair locally, and have the remote party do the same. We need to use the `openssl` command-line utility.

    # generate private/public key keypair
    openssl dhparam -out dhparam.pem 2048
    openssl genpkey -paramfile dhparam.pem -out privatekey.pem

    # extract public key only
    openssl pkey -in privatekey.pem -pubout -out publickey.pem

Next, send your public key to the remote party. Use the `openssl pkey` command to view the public key you will be sent from the remote party.

    openssl pkey -pubin -in remotepublickey.pem -text -noout

The above example will output something similar to:

    PKCS#3 DH Public-Key: (2048 bit)
        public-key:
            67:e5:e5:fa:e0:7b:0f:96:2c:dc:96:44:5f:50:02:
            9e:8d:c2:6c:04:68:b0:d1:1d:75:66:fc:63:f5:e3:
            42:30:b8:96:c1:45:cc:08:60:b4:21:3b:dd:ee:66:
            88:db:77:d9:1e:11:89:d4:5c:f2:7a:f2:f1:fe:1c:
            77:9d:6f:13:b8:b2:56:00:ef:cb:3b:60:79:74:02:
            98:f5:f9:8e:3e:b5:62:08:de:ca:8c:c3:40:4a:80:
            79:d5:43:06:17:a8:19:56:af:cc:95:5e:e2:32:2d:
            d2:14:7b:76:5a:9a:f1:3c:76:76:35:cc:7b:c1:a5:
            f4:39:e5:b6:ca:71:3f:7c:3f:97:e5:ab:86:c1:cd:
            0e:e6:ee:04:c9:e6:2d:80:7e:59:c0:49:eb:b6:64:
            4f:a8:f9:bb:a3:87:b3:3d:76:01:9e:2b:16:94:a4:
            37:30:fb:35:e2:63:be:23:90:b9:ef:3f:46:46:04:
            94:8f:60:79:7a:51:55:d6:1a:1d:f5:d9:7f:4a:3e:
            aa:ac:b0:d0:82:cc:c2:e0:94:e0:54:c1:17:83:0b:
            74:08:4d:5a:79:ae:ff:7f:1c:04:ab:23:39:4a:ae:
            87:83:55:43:ab:7a:7c:04:9d:20:80:bb:af:5f:16:
            a3:e3:20:b9:21:47:8c:f8:7f:a8:60:80:9e:61:77:
            36
     [...abbreviated...]

Use this public key as a parameter to openssl_dh_compute_key() in order to compute the shared secret.

`<?php
$remote_public_key = '67e5e5fae07b0f962cdc96445f50029e8dc26c0468b0d11d7566fc63f5e34230b896c145cc0860b4213bddee6688db77d91e1189d45cf27af2f1fe1c779d6f13b8b25600efcb3b6079740298f5f98e3eb56208deca8cc3404a8079d5430617a81956afcc955ee2322dd2147b765a9af13c767635cc7bc1a5f439e5b6ca713f7c3f97e5ab86c1cd0ee6ee04c9e62d807e59c049ebb6644fa8f9bba387b33d76019e2b1694a43730fb35e263be2390b9ef3f464604948f60797a5155d61a1df5d97f4a3eaaacb0d082ccc2e094e054c117830b74084d5a79aeff7f1c04ab23394aae87835543ab7a7c049d2080bbaf5f16a3e320b921478cf87fa860809e617736';
$local_priv_key = openssl_pkey_get_private('file://privatekey.pem');
$shared_secret = openssl_dh_compute_key(hex2bin($remote_public_key), $local_priv_key);
echo bin2hex($shared_secret)."\n";
?>`

Example #2 Generate a DH public/private keypair in php

First, generate the DH prime number

    openssl dhparam -out dhparam.pem 2048
    openssl dh -in dhparam.pem -noout  -text

The above example will output something similar to:

    PKCS#3 DH Parameters: (2048 bit)
            prime:
                00:a3:25:1e:73:3f:44:b9:2b:ee:f4:9d:9f:37:6a:
                4b:fd:1d:bd:f4:af:da:c8:10:77:59:41:c6:5f:73:
                d2:88:29:39:cd:1c:5f:c3:9f:0f:22:d2:9c:20:c1:
                e4:c0:18:03:b8:b6:d8:da:ad:3b:39:a6:da:8e:fe:
                12:30:e9:03:5d:22:ba:ef:18:d2:7b:69:f9:5b:cb:
                78:c6:0c:8c:6b:f2:49:92:c2:49:e0:45:77:72:b3:
                55:36:30:f2:40:17:89:18:50:03:fa:2d:54:7a:7f:
                34:4c:73:32:b6:88:14:51:14:be:80:57:95:e6:a3:
                f6:51:ff:17:47:4f:15:d6:0e:6c:47:53:72:2c:2a:
                4c:21:cb:7d:f3:49:97:c9:47:5e:40:33:7b:99:52:
                7e:7a:f3:52:27:80:de:1b:26:6b:40:bb:14:11:0b:
                fb:e6:d8:2f:cf:a0:06:2f:96:b9:1c:0b:b4:cb:d3:
                a6:62:9c:48:67:f6:81:f2:c6:ff:45:03:0a:9d:67:
                9d:ce:27:d9:6b:48:5d:ca:fb:c2:5d:84:9b:8b:cb:
                40:c7:a4:0c:8a:6e:f4:ab:ba:b6:10:c3:b8:25:4d:
                cf:60:96:f4:db:e8:00:1c:58:47:7a:fb:51:86:d1:
                22:d7:4e:94:31:7a:d5:da:3d:53:de:da:bb:64:8d:
                62:6b
            generator: 2 (0x2)

Prime and generator values ares passed as p and g into openssl_pkey_new()

`<?php
$configargs = array();
$configargs['p'] = hex2bin('00a3251e733f44b92beef49d9f376a4bfd1dbdf4afdac810775941c65f73d2882939cd1c5fc39f0f22d29c20c1e4c01803b8b6d8daad3b39a6da8efe1230e9035d22baef18d27b69f95bcb78c60c8c6bf24992c249e0457772b3553630f2401789185003fa2d547a7f344c7332b688145114be805795e6a3f651ff17474f15d60e6c4753722c2a4c21cb7df34997c9475e40337b99527e7af3522780de1b266b40bb14110bfbe6d82fcfa0062f96b91c0bb4cbd3a6629c4867f681f2c6ff45030a9d679dce27d96b485dcafbc25d849b8bcb40c7a40c8a6ef4abbab610c3b8254dcf6096f4dbe8001c58477afb5186d122d74e94317ad5da3d53dedabb648d626b');
$configargs['g'] = hex2bin('02');
$private_key = openssl_pkey_new(array('dh' => $configargs));
openssl_pkey_export_to_file($private_key,'privatekey.pem',$passphrase='y0urp@s5phr@se');
$details = openssl_pkey_get_details($private_key);
$local_pub_key = $details['dh']['pub_key'];
echo bin2hex($local_pub_key)."\n";//you can send your public key to the remote party
$details = openssl_pkey_get_details(openssl_pkey_get_public("file://remotepublickey.pem"));
$remote_public_key = $details['dh']['pub_key'];
$shared_secret = openssl_dh_compute_key($remote_public_key, $private_key);
echo bin2hex($shared_secret)."\n";
?>`

### See Also

- openssl_pkey_new() - Generates a new private key
- openssl_pkey_get_details() - Returns an array with the key details
- openssl_pkey_get_private() - Get a private key
- openssl_pkey_get_public() - Extract public key from certificate and prepare it for use

# openssl_digest

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_digest — Computes a digest

### Description

openssl_digest(string `$data`, string `$digest_algo`, bool `$binary` = `false`): string|false

Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string.

### Parameters

`data`

  The data.

`digest_algo`

  The digest method to use, e.g. "sha256", see openssl_get_md_methods() for a list of available digest methods.

`binary`

  Setting to `true` will return as raw output data, otherwise the return value is binhex encoded.

### Return Values

Returns the digested hash value on success or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an unknown signature algorithm is passed via the `digest_algo` parameter.

### See Also

- openssl_get_md_methods() - Gets available digest methods

# openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_encrypt — Encrypts data

### Description

openssl_encrypt(
#[\SensitiveParameter] string `$data`,
string `$cipher_algo`,
#[\SensitiveParameter] string `$passphrase`,
int `$options` = 0,
string `$iv` = "",
string `&$tag` = `null`,
string `$aad` = "",
int `$tag_length` = 16
): string|false

Encrypts given data with given method and passphrase, returns a raw or base64 encoded string

### Parameters

`data`

  The plaintext message data to be encrypted.

`cipher_algo`

  The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods().

`passphrase`

  The passphrase. If the passphrase is shorter than expected, it is silently padded with `NUL` characters; if the passphrase is longer than expected, it is silently truncated.

  Caution

  There is no key derivation function used for `passphrase` as its name might suggest. The only operation used is padding with `NUL` characters or truncation if the length is different than expected.

`options`

  `options` is a bitwise disjunction of the flags `OPENSSL_RAW_DATA`, and `OPENSSL_ZERO_PADDING` or `OPENSSL_DONT_ZERO_PAD_KEY`.

`iv`

  A non-`null` Initialization Vector. If the IV is shorter than expected, it is padded with `NUL` characters and warning is emitted; if the passphrase is longer than expected, it is truncated and warning is emitted.

`tag`

  The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).

`aad`

  Additional authenticated data.

`tag_length`

  The length of the authentication `tag`. Its value can be between 4 and 16 for GCM mode.

### Return Values

Returns the encrypted string on success or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an unknown cipher algorithm is passed in via the `cipher_algo` parameter.

Emits an `E_WARNING` level error if an empty value is passed in via the `iv` parameter.

### Changelog

Version | Description
--- | ---
7.1.0 | The `tag`, `aad` and `tag_length` parameters were added.

### Examples

Example #1 AES Authenticated Encryption in GCM mode example for PHP 7.1+

`<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo $original_plaintext."\n";
}
?>`

Example #2 AES Authenticated Encryption example prior to PHP 7.1

`<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))// timing attack safe comparison
{
echo $original_plaintext."\n";
}
?>`

### See Also

- openssl_decrypt() - Decrypts data

# openssl_error_string

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_error_string — Return openSSL error message

### Description

openssl_error_string(): string|false

openssl_error_string() returns the last error from the openSSL library. Error messages are queued, so this function should be called multiple times to collect all of the information. The last error will be the most recent one.

### Parameters

This function has no parameters.

### Return Values

Returns an error message string, or `false` if there are no more error messages to return.

### Examples

Example #1 openssl_error_string() example

`<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
echo $msg . "<br />\n";
?>`

# openssl_free_key

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_free_key — Free key resource

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
openssl_free_key(OpenSSLAsymmetricKey `$key`): void

openssl_free_key() frees the key associated with the specified `key` from memory.

### Parameters

`key`

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is now deprecated as it doesn't have an effect anymore.
8.0.0 | `key` accepts an OpenSSLAsymmetricKey now; previously, a resource of type `OpenSSL key` was accepted.

# openssl_get_cert_locations

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_get_cert_locations — Retrieve the available certificate locations

### Description

openssl_get_cert_locations(): array

openssl_get_cert_locations() returns an array with information about the available certificate locations that will be searched for SSL certificates.

### Parameters

This function has no parameters.

### Return Values

Returns an array with the available certificate locations.

### Examples

Example #1 openssl_get_cert_locations() example

`<?php
var_dump(openssl_get_cert_locations());
?>`

The above example will output:

    array(8) {
      ["default_cert_file"]=>
      string(21) "/usr/lib/ssl/cert.pem"
      ["default_cert_file_env"]=>
      string(13) "SSL_CERT_FILE"
      ["default_cert_dir"]=>
      string(18) "/usr/lib/ssl/certs"
      ["default_cert_dir_env"]=>
      string(12) "SSL_CERT_DIR"
      ["default_private_dir"]=>
      string(20) "/usr/lib/ssl/private"
      ["default_default_cert_area"]=>
      string(12) "/usr/lib/ssl"
      ["ini_cafile"]=>
      string(0) ""
      ["ini_capath"]=>
      string(0) ""
    }

# openssl_get_cipher_methods

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_get_cipher_methods — Gets available cipher methods

### Description

openssl_get_cipher_methods(bool `$aliases` = `false`): array

Gets a list of available cipher methods.

### Parameters

`aliases`

  Set to `true` if cipher aliases should be included within the returned array.

### Return Values

An array of available cipher methods. Note that prior to OpenSSL 1.1.1, the cipher methods have been returned in upper case and lower case spelling; as of OpenSSL 1.1.1 only the lower case variants are returned.

### Examples

Example #1 openssl_get_cipher_methods() example

Shows how the available ciphers might look, and also which aliases might be available.

`<?php
$ciphers = openssl_get_cipher_methods();
$ciphers_and_aliases = openssl_get_cipher_methods(true);
$cipher_aliases = array_diff($ciphers_and_aliases, $ciphers);
//ECB mode should be avoided
$ciphers = array_filter( $ciphers, function($n) { return stripos($n,"ecb")===FALSE; } );
//At least as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"des")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc2")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc4")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"md5")===FALSE; } );
$cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"des")===FALSE; } );
$cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"rc2")===FALSE; } );
print_r($ciphers);
print_r($cipher_aliases);
?>`

The above example will output something similar to:

    Array
    (
        [0] => aes-128-cbc
        [1] => aes-128-cbc-hmac-sha1
        [2] => aes-128-cbc-hmac-sha256
        [3] => aes-128-ccm
        [4] => aes-128-cfb
        [5] => aes-128-cfb1
        [6] => aes-128-cfb8
        [7] => aes-128-ctr
        [9] => aes-128-gcm
        [10] => aes-128-ocb
        [11] => aes-128-ofb
        [12] => aes-128-xts
        [13] => aes-192-cbc
        [14] => aes-192-ccm
        [15] => aes-192-cfb
        [16] => aes-192-cfb1
        [17] => aes-192-cfb8
        [18] => aes-192-ctr
        [20] => aes-192-gcm
        [21] => aes-192-ocb
        [22] => aes-192-ofb
        [23] => aes-256-cbc
        [24] => aes-256-cbc-hmac-sha1
        [25] => aes-256-cbc-hmac-sha256
        [26] => aes-256-ccm
        [27] => aes-256-cfb
        [28] => aes-256-cfb1
        [29] => aes-256-cfb8
        [30] => aes-256-ctr
        [32] => aes-256-gcm
        [33] => aes-256-ocb
        [34] => aes-256-ofb
        [35] => aes-256-xts
        [36] => aria-128-cbc
        [37] => aria-128-ccm
        [38] => aria-128-cfb
        [39] => aria-128-cfb1
        [40] => aria-128-cfb8
        [41] => aria-128-ctr
        [43] => aria-128-gcm
        [44] => aria-128-ofb
        [45] => aria-192-cbc
        [46] => aria-192-ccm
        [47] => aria-192-cfb
        [48] => aria-192-cfb1
        [49] => aria-192-cfb8
        [50] => aria-192-ctr
        [52] => aria-192-gcm
        [53] => aria-192-ofb
        [54] => aria-256-cbc
        [55] => aria-256-ccm
        [56] => aria-256-cfb
        [57] => aria-256-cfb1
        [58] => aria-256-cfb8
        [59] => aria-256-ctr
        [61] => aria-256-gcm
        [62] => aria-256-ofb
        [63] => bf-cbc
        [64] => bf-cfb
        [66] => bf-ofb
        [67] => camellia-128-cbc
        [68] => camellia-128-cfb
        [69] => camellia-128-cfb1
        [70] => camellia-128-cfb8
        [71] => camellia-128-ctr
        [73] => camellia-128-ofb
        [74] => camellia-192-cbc
        [75] => camellia-192-cfb
        [76] => camellia-192-cfb1
        [77] => camellia-192-cfb8
        [78] => camellia-192-ctr
        [80] => camellia-192-ofb
        [81] => camellia-256-cbc
        [82] => camellia-256-cfb
        [83] => camellia-256-cfb1
        [84] => camellia-256-cfb8
        [85] => camellia-256-ctr
        [87] => camellia-256-ofb
        [88] => cast5-cbc
        [89] => cast5-cfb
        [91] => cast5-ofb
        [92] => chacha20
        [93] => chacha20-poly1305
        [111] => id-aes128-CCM
        [112] => id-aes128-GCM
        [113] => id-aes128-wrap
        [114] => id-aes128-wrap-pad
        [115] => id-aes192-CCM
        [116] => id-aes192-GCM
        [117] => id-aes192-wrap
        [118] => id-aes192-wrap-pad
        [119] => id-aes256-CCM
        [120] => id-aes256-GCM
        [121] => id-aes256-wrap
        [122] => id-aes256-wrap-pad
        [124] => idea-cbc
        [125] => idea-cfb
        [127] => idea-ofb
        [137] => seed-cbc
        [138] => seed-cfb
        [140] => seed-ofb
        [141] => sm4-cbc
        [142] => sm4-cfb
        [143] => sm4-ctr
        [145] => sm4-ofb
    )
    Array
    (
        [36] => aes128
        [37] => aes128-wrap
        [38] => aes192
        [39] => aes192-wrap
        [40] => aes256
        [41] => aes256-wrap
        [69] => aria128
        [70] => aria192
        [71] => aria256
        [72] => bf
        [77] => blowfish
        [99] => camellia128
        [100] => camellia192
        [101] => camellia256
        [102] => cast
        [103] => cast-cbc
        [146] => idea
        [164] => seed
        [169] => sm4
    )

### See Also

- openssl_get_md_methods() - Gets available digest methods

# openssl_get_curve_names

(PHP 7 >= 7.1.0, PHP 8)

openssl_get_curve_names — Gets list of available curve names for ECC

### Description

openssl_get_curve_names(): array|false

Gets the list of available curve names for use in Elliptic curve cryptography (ECC) for public/private key operations. The two most widely standardized/supported curves are prime256v1 (NIST P-256) and secp384r1 (NIST P-384).

Approximate Equivalancies of AES, RSA, DSA and ECC Keysizes
AES Symmetric Keysize (Bits) | RSA and DSA Keysize (Bits) | ECC Keysize (Bits)
--- | --- | ---
80 | 1024 | 160
112 | 2048 | 224
128 | 3072 | 256
192 | 7680 | 384
256 | 15360 | 512

» NIST recommends using ECC curves with at least 256 bits.

### Parameters

This function has no parameters.

### Return Values

An array of available curve names, or `false` on failure.

### Examples

Example #1 openssl_get_curve_names() example

`<?php
$curve_names = openssl_get_curve_names();
print_r($curve_names);
?>`

The above example will output something similar to:

    Array
    (
        [0] => secp112r1
        [1] => secp112r2
        [2] => secp128r1
        [3] => secp128r2
        [4] => secp160k1
        [5] => secp160r1
        [6] => secp160r2
        [7] => secp192k1
        [8] => secp224k1
        [9] => secp224r1
        [10] => secp256k1
        [11] => secp384r1
        [12] => secp521r1
        [13] => prime192v1
        [14] => prime192v2
        [15] => prime192v3
        [16] => prime239v1
        [17] => prime239v2
        [18] => prime239v3
        [19] => prime256v1
        [20] => sect113r1
        [21] => sect113r2
        [22] => sect131r1
        [23] => sect131r2
        [24] => sect163k1
        [25] => sect163r1
        [26] => sect163r2
        [27] => sect193r1
        [28] => sect193r2
        [29] => sect233k1
        [30] => sect233r1
        [31] => sect239k1
        [32] => sect283k1
        [33] => sect283r1
        [34] => sect409k1
        [35] => sect409r1
        [36] => sect571k1
        [37] => sect571r1
        [38] => c2pnb163v1
        [39] => c2pnb163v2
        [40] => c2pnb163v3
        [41] => c2pnb176v1
        [42] => c2tnb191v1
        [43] => c2tnb191v2
        [44] => c2tnb191v3
        [45] => c2pnb208w1
        [46] => c2tnb239v1
        [47] => c2tnb239v2
        [48] => c2tnb239v3
        [49] => c2pnb272w1
        [50] => c2pnb304w1
        [51] => c2tnb359v1
        [52] => c2pnb368w1
        [53] => c2tnb431r1
        [54] => wap-wsg-idm-ecid-wtls1
        [55] => wap-wsg-idm-ecid-wtls3
        [56] => wap-wsg-idm-ecid-wtls4
        [57] => wap-wsg-idm-ecid-wtls5
        [58] => wap-wsg-idm-ecid-wtls6
        [59] => wap-wsg-idm-ecid-wtls7
        [60] => wap-wsg-idm-ecid-wtls8
        [61] => wap-wsg-idm-ecid-wtls9
        [62] => wap-wsg-idm-ecid-wtls10
        [63] => wap-wsg-idm-ecid-wtls11
        [64] => wap-wsg-idm-ecid-wtls12
        [65] => Oakley-EC2N-3
        [66] => Oakley-EC2N-4
        [67] => brainpoolP160r1
        [68] => brainpoolP160t1
        [69] => brainpoolP192r1
        [70] => brainpoolP192t1
        [71] => brainpoolP224r1
        [72] => brainpoolP224t1
        [73] => brainpoolP256r1
        [74] => brainpoolP256t1
        [75] => brainpoolP320r1
        [76] => brainpoolP320t1
        [77] => brainpoolP384r1
        [78] => brainpoolP384t1
        [79] => brainpoolP512r1
        [80] => brainpoolP512t1
    )

# openssl_get_md_methods

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_get_md_methods — Gets available digest methods

### Description

openssl_get_md_methods(bool `$aliases` = `false`): array

Gets a list of available digest methods.

### Parameters

`aliases`

  Set to `true` if digest aliases should be included within the returned array.

### Return Values

An array of available digest methods.

### Examples

Example #1 openssl_get_md_methods() example

Shows how the available digests might look, and also which aliases might be available.

`<?php
$digests = openssl_get_md_methods();
$digests_and_aliases = openssl_get_md_methods(true);
$digest_aliases = array_diff($digests_and_aliases, $digests);
print_r($digests);
print_r($digest_aliases);
?>`

The above example will output something similar to:

    Array
    (
        [0] => DSA
        [1] => DSA-SHA
        [2] => MD2
        [3] => MD4
        [4] => MD5
        [5] => RIPEMD160
        [6] => SHA
        [7] => SHA1
        [8] => SHA224
        [9] => SHA256
        [10] => SHA384
        [11] => SHA512
        [12] => dsaEncryption
        [13] => dsaWithSHA
        [14] => ecdsa-with-SHA1
        [15] => md2
        [16] => md4
        [17] => md5
        [18] => ripemd160
        [19] => sha
        [20] => sha1
        [21] => sha224
        [22] => sha256
        [23] => sha384
        [24] => sha512
    )
    Array
    (
        [2] => DSA-SHA1
        [3] => DSA-SHA1-old
        [4] => DSS1
        [9] => RSA-MD2
        [10] => RSA-MD4
        [11] => RSA-MD5
        [12] => RSA-RIPEMD160
        [13] => RSA-SHA
        [14] => RSA-SHA1
        [15] => RSA-SHA1-2
        [16] => RSA-SHA224
        [17] => RSA-SHA256
        [18] => RSA-SHA384
        [19] => RSA-SHA512
        [28] => dsaWithSHA1
        [29] => dss1
        [32] => md2WithRSAEncryption
        [34] => md4WithRSAEncryption
        [36] => md5WithRSAEncryption
        [37] => ripemd
        [39] => ripemd160WithRSA
        [40] => rmd160
        [43] => sha1WithRSAEncryption
        [45] => sha224WithRSAEncryption
        [47] => sha256WithRSAEncryption
        [49] => sha384WithRSAEncryption
        [51] => sha512WithRSAEncryption
        [52] => shaWithRSAEncryption
        [53] => ssl2-md5
        [54] => ssl3-md5
        [55] => ssl3-sha1
    )

### See Also

- openssl_digest() - Computes a digest
- openssl_get_cipher_methods() - Gets available cipher methods

# openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_get_privatekey — Alias of openssl_pkey_get_private()

### Description

This function is an alias of: openssl_pkey_get_private().

# openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_get_publickey — Alias of openssl_pkey_get_public()

### Description

This function is an alias of: openssl_pkey_get_public().

# openssl_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_open — Open sealed data

### Description

openssl_open(
string `$data`,
#[\SensitiveParameter] string `&$output`,
string `$encrypted_key`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
string `$cipher_algo`,
?string `$iv` = `null`
): bool

openssl_open() opens (decrypts) `data` using an envelope key that is decrypted from `encrypted_key` using `private_key`. The decryption is done using `cipher_algo` and `iv`. The IV is required only if the cipher method requires it. The function fills `output` with the decrypted data. The envelope key is usually generated when the data are sealed using a public key that is associated with the private key. See openssl_seal() for more information.

### Parameters

`data`

  The sealed data.

`output`

  If the call is successful the opened data is returned in this parameter.

`encrypted_key`

  The encrypted symmetric key that can be decrypted using `private_key`.

`private_key`

  The private key used for decrypting `encrypted_key`.

`cipher_algo`

  The cipher method used for decryption of `data`.

  Caution

  The default value for PHP versions prior to 8.0 is (`'RC4'`) which is considered insecure. It is strongly recommended to explicitly specify a secure cipher method.

`iv`

  The initialization vector used for decryption of `data`. It is required if the cipher method requires IV. This can be found out by calling openssl_cipher_iv_length() with `cipher_algo`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509 CSR` was accepted.
8.0.0 | `cipher_algo` is no longer an optional parameter.

### Examples

Example #1 openssl_open() example

`<?php
// $sealed, $env_key and $iv are assumed to contain the sealed data, our
// envelope key and IV. All given to us by the sealer.
// Fetch private key from file located in private_key.pem
$pkey = openssl_get_privatekey("file://private_key.pem");
// Decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkey, 'AES256', $iv)) {
echo "Here is the opened data: ", $open;
} else {
echo "Failed to open data";
}
?>`

### See Also

- openssl_seal() - Seal (encrypt) data

# openssl_password_hash

(No version information available, might only be in Git)

openssl_password_hash — Create a password hash using OpenSSL's Argon2 implementation

### Description

openssl_password_hash(string `$algo`, string `$password`, array `$options` = []): string

Creates a password hash using OpenSSL's Argon2 implementation. This is an alternative to password_hash() that uses OpenSSL as the backend, which may offer hardware acceleration on some platforms.

This function is only available when PHP is compiled with OpenSSL support that includes Argon2 (`HAVE_OPENSSL_ARGON2`).

### Parameters

`algo`

  The password hashing algorithm. Supported values: `"argon2id"` and `"argon2i"`.

`password`

  The user's password.

`options`

  An associative array of options. Supported keys:

  - `memory_cost` - Maximum memory (in KiB) that may be used to compute the hash
  - `time_cost` - Maximum amount of time it may take to compute the hash
  - `threads` - Number of threads to use for computing the hash

### Return Values

Returns the password hash as a string.

### Errors/Exceptions

Throws a ValueError if `algo` is not one of the supported values (`"argon2i"` or `"argon2id"`).

Throws an Error if the hashing operation fails for an unknown reason.

### Changelog

Version | Description
--- | ---
8.4.0 | Function added.

### Examples

Example #1 openssl_password_hash() example

`<?php
$hash = openssl_password_hash('argon2id', 'my-secret-password');
echo $hash;
?>`

The above example will output something similar to:

    $argon2id$v=19$m=65536,t=4,p=1$c29tZXNhbHR2YWx1ZQ$hashvalue...

Example #2 openssl_password_hash() with custom options

`<?php
$hash = openssl_password_hash('argon2id', 'my-secret-password', [
'memory_cost' => 65536,
'time_cost' => 4,
'threads' => 1,
]);
?>`

### See Also

- openssl_password_verify() - Verify a password against a hash using OpenSSL's Argon2 implementation
- password_hash() - Creates a password hash

# openssl_password_verify

(No version information available, might only be in Git)

openssl_password_verify — Verify a password against a hash using OpenSSL's Argon2 implementation

### Description

openssl_password_verify(string `$algo`, string `$password`, string `$hash`): bool

Verifies that a password matches a hash created by openssl_password_hash().

This function is only available when PHP is compiled with OpenSSL support that includes Argon2 (`HAVE_OPENSSL_ARGON2`).

### Parameters

`algo`

  The password hashing algorithm. Supported values: `"argon2id"` and `"argon2i"`.

`password`

  The user's password.

`hash`

  A hash created by openssl_password_hash().

### Return Values

Returns `true` if the password and hash match, or `false` otherwise.

### Errors/Exceptions

Throws a ValueError if `algo` is not one of the supported values (`"argon2i"` or `"argon2id"`).

### Changelog

Version | Description
--- | ---
8.4.0 | Function added.

### Examples

Example #1 openssl_password_verify() example

`<?php
$hash = openssl_password_hash('argon2id', 'my-secret-password');
if (openssl_password_verify('argon2id', 'my-secret-password', $hash)) {
echo 'Password matches.';
} else {
echo 'Password does not match.';
}
?>`

### See Also

- openssl_password_hash() - Create a password hash using OpenSSL's Argon2 implementation
- password_verify() - Verifies that a password matches a hash

# openssl_pbkdf2

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string

### Description

openssl_pbkdf2(
#[\SensitiveParameter] string `$password`,
string `$salt`,
int `$key_length`,
int `$iterations`,
string `$digest_algo` = "sha1"
): string|false

openssl_pbkdf2() computes PBKDF2 (Password-Based Key Derivation Function 2), a key derivation function defined in PKCS5 v2.

### Parameters

`password`

  Password from which the derived key is generated.

`salt`

  PBKDF2 recommends a crytographic salt of at least 128 bits (16 bytes).

`key_length`

  Length of desired output key.

`iterations`

  The number of iterations desired. » NIST recommends at least 1,000. As of 2023, OWASP recommends 600,000 iterations for PBKDF2-HMAC-SHA256 and 210,000 for PBKDF2-HMAC-SHA512.

`digest_algo`

  Optional hash or digest algorithm from openssl_get_md_methods(). Defaults to SHA-1. It is recommended to set it to SHA-256 or SHA-512.

### Return Values

Returns raw binary string or `false` on failure.

### Examples

Example #1 openssl_pbkdf2() example

`<?php
$password = 'password';
$salt = openssl_random_pseudo_bytes(16);
$keyLength = 20;
$iterations = 600000;
$generated_key = openssl_pbkdf2($password, $salt, $keyLength, $iterations, 'sha256');
echo bin2hex($generated_key)."\n";
echo base64_encode($generated_key)."\n";
?>`

### See Also

- hash_pbkdf2() - Generate a PBKDF2 key derivation of a supplied password
- openssl_get_md_methods() - Gets available digest methods

# openssl_pkcs12_export

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable

### Description

openssl_pkcs12_export(
OpenSSLCertificate|string `$certificate`,
string `&$output`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
#[\SensitiveParameter] string `$passphrase`,
array `$options` = []
): bool

openssl_pkcs12_export() stores `certificate` into a string named by `output` in a PKCS#12 file format.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`output`

  On success, this will hold the PKCS#12.

`private_key`

  Private key component of PKCS#12 file. See Public/Private Key parameters for a list of valid values.

`passphrase`

  Encryption password for unlocking the PKCS#12 file.

`options`

  Optional array, other keys will be ignored.

  Key | Description
  --- | ---
  `"extracerts"` | array of extra certificates or a single certificate to be included in the PKCS#12 file.
  `"friendly_name"` | string to be used for the supplied certificate and key

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

### Description

openssl_pkcs12_export_to_file(
OpenSSLCertificate|string `$certificate`,
string `$output_filename`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
#[\SensitiveParameter] string `$passphrase`,
array `$options` = []
): bool

openssl_pkcs12_export_to_file() stores `certificate` into a file named by `output_filename` in a PKCS#12 file format.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`output_filename`

  Path to the output file.

`private_key`

  Private key component of PKCS#12 file. See Public/Private Key parameters for a list of valid values.

`passphrase`

  Encryption password for unlocking the PKCS#12 file.

`options`

  Optional array, other keys will be ignored.

  Key | Description
  --- | ---
  `"extracerts"` | array of extra certificates or a single certificate to be included in the PKCS#12 file.
  `"friendly_name"` | string to be used for the supplied certificate and key

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_pkcs12_read

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

### Description

openssl_pkcs12_read(string `$pkcs12`, array `&$certificates`, #[\SensitiveParameter] string `$passphrase`): bool

openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by `pkcs12` into an array named `certificates`.

### Parameters

`pkcs12`

  The certificate store contents, not its file name.

`certificates`

  On success, this will hold the Certificate Store Data.

`passphrase`

  Encryption password for unlocking the PKCS#12 file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 openssl_pkcs12_read() example

`<?php
if (!$cert_store = file_get_contents("/certs/file.p12")) {
echo "Error: Unable to read the cert file\n";
exit;
}
if (openssl_pkcs12_read($cert_store, $cert_info, "my_secret_pass")) {
echo "Certificate Information\n";
print_r($cert_info);
} else {
echo "Error: Unable to read the cert store.\n";
exit;
}
?>`

# openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message

### Description

openssl_pkcs7_decrypt(
string `$input_filename`,
string `$output_filename`,
#[\SensitiveParameter] OpenSSLCertificate|string `$certificate`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null `$private_key` = `null`
): bool

Decrypts the S/MIME encrypted message contained in the file specified by `input_filename` using the certificate and its associated private key specified by `certificate` and `private_key`.

### Parameters

`input_filename`

`output_filename`

  The decrypted message is written to the file specified by `output_filename`.

`certificate`

`private_key`

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_pkcs7_decrypt() example

`<?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg"; // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file
if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
echo "decrypted!";
} else {
echo "failed to decrypt!";
}
?>`

# openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_encrypt — Encrypt an S/MIME message

### Description

openssl_pkcs7_encrypt(
string `$input_filename`,
string `$output_filename`,
OpenSSLCertificate|array|string `$certificate`,
?array `$headers`,
int `$flags` = 0,
int `$cipher_algo` = `OPENSSL_CIPHER_AES_128_CBC`
): bool

openssl_pkcs7_encrypt() takes the contents of the file named `input_filename` and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by `certificate`.

### Parameters

`input_filename`

`output_filename`

`certificate`

  Either a lone X.509 certificate, or an array of X.509 certificates.

`headers`

  `headers` is an array of headers that will be prepended to the data after it has been encrypted.

  `headers` can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

`flags`

  `flags` can be used to specify options that affect the encoding process - see PKCS7 constants.

`cipher_algo`

  One of cipher constants.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The default cipher algorithm (`cipher_algo`) is now AES-128-CBC (`OPENSSL_CIPHER_AES_128_CBC`). Previously, PKCS7/CMS was used (`OPENSSL_CIPHER_RC2_40`).
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_pkcs7_encrypt() example

`<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk. You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,
Top secret, for your eyes only!
The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!
HQ
EOD;
// load key
$key = file_get_contents("nighthawk.pem");
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
array("To" => "nighthawk@example.com", // keyed syntax
"From: HQ <hq@example.com>", // indexed syntax
"Subject" => "Eyes only"))) {
// message encrypted - send it!
exec(ini_get("sendmail_path") . " < enc.txt");
}
?>`

# openssl_pkcs7_read

(PHP 7 >= 7.2.0, PHP 8)

openssl_pkcs7_read — Export the PKCS7 file to an array of PEM certificates

### Description

openssl_pkcs7_read(string `$data`, array `&$certificates`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`data`

  The string of data you wish to parse (p7b format).

`certificates`

  The array of PEM certificates from the p7b input data.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Get a PEM array from a P7B file

`<?php
$file = 'certs.p7b';
$f = file_get_contents($file);
$p7 = array();
$r = openssl_pkcs7_read($f, $p7);
if ($r === false) {
printf("ERROR: %s is not a proper p7b file".PHP_EOL, $file);
for($e = openssl_error_string(), $i = 0; $e; $e = openssl_error_string(), $i++)
printf("SSL l%d: %s".PHP_EOL, $i, $e);
exit(1);
}
print_r($p7);
?>`

### See Also

- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_sign — Sign an S/MIME message

### Description

openssl_pkcs7_sign(
string `$input_filename`,
string `$output_filename`,
OpenSSLCertificate|string `$certificate`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
?array `$headers`,
int `$flags` = `PKCS7_DETACHED`,
?string `$untrusted_certificates_filename` = `null`
): bool

openssl_pkcs7_sign() takes the contents of the file named `input_filename` and signs them using the certificate and its matching private key specified by `certificate` and `private_key` parameters.

### Parameters

`input_filename`

  The input file you are intending to digitally sign.

`output_filename`

  The file which the digital signature will be written to.

`certificate`

  The X.509 certificate used to digitally sign `input_filename`. See Key/Certificate parameters for a list of valid values.

`private_key`

  `private_key` is the private key corresponding to `certificate`. See Public/Private Key parameters for a list of valid values.

`headers`

  `headers` is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter).

`flags`

  `flags` can be used to alter the output - see PKCS7 constants.

`untrusted_certificates_filename`

  `untrusted_certificates_filename` specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509 CSR` was accepted.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509 CSR` was accepted.

### Examples

Example #1 openssl_pkcs7_sign() example

`<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD
You have my authorization to spend $10,000 on dinner expenses.
The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "file://mycert.pem",
array("file://mycert.pem", "mypassphrase"),
array("To" => "joes@example.com", // keyed syntax
"From: HQ <ceo@example.com>", // indexed syntax
"Subject" => "Eyes only")
)) {
// message signed - send it!
exec(ini_get("sendmail_path") . " < signed.txt");
}
?>`

# openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message

### Description

openssl_pkcs7_verify(
string `$input_filename`,
int `$flags`,
?string `$signers_certificates_filename` = `null`,
array `$ca_info` = [],
?string `$untrusted_certificates_filename` = `null`,
?string `$content` = `null`,
?string `$output_filename` = `null`
): bool|int

openssl_pkcs7_verify() reads the S/MIME message contained in the given file and examines the digital signature.

### Parameters

`input_filename`

  Path to the message.

`flags`

  `flags` can be used to affect how the signature is verified - see PKCS7 constants for more information.

`signers_certificates_filename`

  If the `signers_certificates_filename` is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

`ca_info`

  If the `ca_info` is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

`untrusted_certificates_filename`

  If the `untrusted_certificates_filename` is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

`content`

  You can specify a filename with `content` that will be filled with the verified data, but with the signature information stripped.

`output_filename`

### Return Values

Returns `true` if the signature is verified, `false` if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `signers_certificates_filename`, `untrusted_certificates_filename`, `content` and `output_filename` are nullable now.
7.2.0 | The `output_filename` parameter was added.

### Notes

> Note: As specified in RFC 2045, lines may not be longer than 76 characters in the `input_filename` parameter.

# openssl_pkey_derive

(PHP 7 >= 7.3.0, PHP 8)

openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key

### Description

openssl_pkey_derive(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`, #[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`, int `$key_length` = 0): string|false

openssl_pkey_derive() takes a set of a `public_key` and `private_key` and derives a shared secret, for either DH or EC keys.

### Parameters

`public_key`

  `public_key` is the public key for the derivation. See Public/Private Key parameters for a list of valid values.

`private_key`

  `private_key` is the private key for the derivation. See Public/Private Key parameters for a list of valid values.

`key_length`

  If not zero, will attempt to set the desired length of the derived secret.

  Caution

  This parameter is deprecated and should not be used, as it does not work as expected. It never returns a secret longer than the size of the prime. If the desired length is smaller than the size of the prime, it truncates the length only for ECDH keys but fails for DH keys.

### Return Values

The derived secret on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | The parameter `key_length` is now deprecated.

### Examples

Example #1 openssl_pkey_derive() example

`<?php
// Load in private key
$priv = openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----
MIICJgIBADCCARcGCSqGSIb3DQEDATCCAQgCggEBAJLxRCaZ933uW+AXmabHFDDy
upojBIRlbmQLJZfigDaSA1f9YOTsIv+WwVFTX/J1mtCyx9uBcz0Nt2kmVwxWuc2f
VtCEMPsmLsVXX7xRUFLpyX1Y1IYGBVXQOoOvLWYQjpZgnx47Pkh1Ok1+smffztfC
0DCNt4KorWrbsPcmqBejXHN79KvWFjZmXOksRiNu/Bn76RiqvofC4z8Ri3kHXQG2
197JGZzzFXHadGC3xbkg8UxsNbYhVMKbm0iANfafUH7/hoS9UjAVQYtvwe7YNiW/
HnyfVCrKwcc7sadd8Iphh+3lf5P1AhaQEAMytanrzq9RDXKBxuvpSJifRYasZYsC
AQIEggEEAoIBAGwAYC2E81Y1U2Aox0U7u1+vBcbht/OO87tutMvc4NTLf6NLPHsW
cPqBixs+3rSn4fADzAIvdLBmogjtiIZoB6qyHrllF/2xwTVGEeYaZIupQH3bMK2b
6eUvnpuu4Ytksiz6VpXBBRMrIsj3frM+zUtnq8vKUr+TbjV2qyKR8l3eNDwzqz30
dlbKh9kIhZafclHfRVfyp+fVSKPfgrRAcLUgAbsVjOjPeJ90xQ4DTMZ6vjiv6tHM
hkSjJIcGhRtSBzVF/cT38GyCeTmiIA/dRz2d70lWrqDQCdp9ArijgnpjNKAAulSY
CirnMsGZTDGmLOHg4xOZ5FEAzZI2sFNLlcw=
-----END PRIVATE KEY-----
");
// Load in public key
$pub = openssl_pkey_get_public("-----BEGIN PUBLIC KEY-----
MIICJDCCARcGCSqGSIb3DQEDATCCAQgCggEBAJLxRCaZ933uW+AXmabHFDDyupoj
BIRlbmQLJZfigDaSA1f9YOTsIv+WwVFTX/J1mtCyx9uBcz0Nt2kmVwxWuc2fVtCE
MPsmLsVXX7xRUFLpyX1Y1IYGBVXQOoOvLWYQjpZgnx47Pkh1Ok1+smffztfC0DCN
t4KorWrbsPcmqBejXHN79KvWFjZmXOksRiNu/Bn76RiqvofC4z8Ri3kHXQG2197J
GZzzFXHadGC3xbkg8UxsNbYhVMKbm0iANfafUH7/hoS9UjAVQYtvwe7YNiW/Hnyf
VCrKwcc7sadd8Iphh+3lf5P1AhaQEAMytanrzq9RDXKBxuvpSJifRYasZYsCAQID
ggEFAAKCAQAiCSBpxvGgsTorxAWtcAlSmzAJnJxFgSPef0g7OjhESytnc8G2QYmx
ovMt5KVergcitztWh08hZQUdAYm4rI+zMlAFDdN8LWwBT/mGKSzRkWeprd8E7mvy
ucqC1YXCMqmIwPySvLQUB/Dl8kgau7BLAnIJm8VP+MVrn8g9gghD0qRCgPgtEaDV
vocfgnOU43rhKnIgO0cHOKtw2qybSFB8QuZrYugq4j8Bwkrzh6rdMMeyMl/ej5Aj
c0wamOzuBDtXt0T9+Fx3khHaowjCc7xJZRgZCxg43SbqMWJ9lUg94I7+LTX61Gyv
dtlkbGbtoDOnxeNnN93gwQZngGYZYciu
-----END PUBLIC KEY-----
");
// Outputs the hex version of the derived key
echo bin2hex(openssl_pkey_derive($pub,$priv));`

# openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_export — Gets an exportable representation of a key into a string

### Description

openssl_pkey_export(
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$key`,
string `&$output`,
#[\SensitiveParameter] ?string `$passphrase` = `null`,
?array `$options` = `null`
): bool

openssl_pkey_export() exports `key` as a PEM encoded string and stores it into `output` (which is passed by reference).

> Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

### Parameters

`key`

`output`

`passphrase`

  The key is optionally protected by `passphrase`.

`options`

  `options` can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about `options`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_export_to_file — Gets an exportable representation of a key into a file

### Description

openssl_pkey_export_to_file(
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$key`,
string `$output_filename`,
#[\SensitiveParameter] ?string `$passphrase` = `null`,
?array `$options` = `null`
): bool

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of `key` into the file named by `output_filename`.

> Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

### Parameters

`key`

`output_filename`

  Path to the output file.

`passphrase`

  The key can be optionally protected by a `passphrase`.

`options`

  `options` can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about `options`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_free — Frees a private key

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
openssl_pkey_free(OpenSSLAsymmetricKey `$key`): void

> Note:

> This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.

This function frees a private key created by openssl_pkey_new().

### Parameters

`key`

  Resource holding the key.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is now deprecated as it doesn't have an effect anymore.
8.0.0 | `key` accepts an OpenSSLAsymmetricKey now; previously, a resource of type `OpenSSL key` was accepted.

# openssl_pkey_get_details

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_pkey_get_details — Returns an array with the key details

### Description

openssl_pkey_get_details(OpenSSLAsymmetricKey `$key`): array|false

This function returns the key details (bits, key, type).

### Parameters

`key`

  Resource holding the key.

### Return Values

Returns an array with the key details on success or `false` on failure. Returned array has indexes `bits` (number of bits), `key` (string representation of the public key) and `type` (type of the key which is one of `OPENSSL_KEYTYPE_RSA`, `OPENSSL_KEYTYPE_DSA`, `OPENSSL_KEYTYPE_DH`, `OPENSSL_KEYTYPE_EC`, `OPENSSL_KEYTYPE_X25519`, `OPENSSL_KEYTYPE_ED25519`, `OPENSSL_KEYTYPE_X448`, `OPENSSL_KEYTYPE_ED448`, or `-1` meaning unknown).

Depending on the key type used, additional details may be returned. Note that some elements may not always be available.

- `OPENSSL_KEYTYPE_RSA`, an additional array key named `"rsa"`, containing the key data is returned.

  Key | Description
  --- | ---
  `"n"` | modulus
  `"e"` | public exponent
  `"d"` | private exponent
  `"p"` | prime 1
  `"q"` | prime 2
  `"dmp1"` | exponent1, d mod (p-1)
  `"dmq1"` | exponent2, d mod (q-1)
  `"iqmp"` | coefficient, (inverse of q) mod p

- `OPENSSL_KEYTYPE_DSA`, an additional array key named `"dsa"`, containing the key data is returned.

  Key | Description
  --- | ---
  `"p"` | prime number (public)
  `"q"` | 160-bit subprime, q | p-1 (public)
  `"g"` | generator of subgroup (public)
  `"priv_key"` | private key x
  `"pub_key"` | public key y = g^x

- `OPENSSL_KEYTYPE_DH`, an additional array key named `"dh"`, containing the key data is returned.

  Key | Description
  --- | ---
  `"p"` | prime number (shared)
  `"g"` | generator of Z_p (shared)
  `"priv_key"` | private DH value x
  `"pub_key"` | public DH value g^x

- `OPENSSL_KEYTYPE_X25519`, `OPENSSL_KEYTYPE_ED25519`, `OPENSSL_KEYTYPE_X448`, or `OPENSSL_KEYTYPE_ED448` an additional array key named `"x25519"`, `"ed25519"`, `"x448"`, or `"ed448"` respectively, is returned, containing the key data.

  Key | Description
  --- | ---
  `"priv_key"` | private key
  `"pub_key"` | public key

### Changelog

Version | Description
--- | ---
8.4.0 | Added support for Curve25519 and Curve448 based keys. Specifically the `x25519`, `ed25519`, `x448` and `ed448` fields have been introduced.
8.0.0 | `key` accepts an OpenSSLAsymmetricKey now; previously, a resource of type `OpenSSL key` was accepted.

# openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_get_private — Get a private key

### Description

openssl_pkey_get_private(#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`, #[\SensitiveParameter] ?string `$passphrase` = `null`): OpenSSLAsymmetricKey|false

openssl_pkey_get_private() parses `private_key` and prepares it for use by other functions.

### Parameters

`private_key`

  `private_key` can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
  2. A PEM formatted private key.
`passphrase`

  The optional parameter `passphrase` must be used if the specified key is encrypted (protected by a passphrase).

### Return Values

Returns an OpenSSLAsymmetricKey instance on success, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was returned.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.
8.0.0 | `passphrase` is nullable now.

# openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_get_public — Extract public key from certificate and prepare it for use

### Description

openssl_pkey_get_public(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`): OpenSSLAsymmetricKey|false

openssl_pkey_get_public() extracts the public key from `public_key` and prepares it for use by other functions.

### Parameters

`public_key`

  `public_key` can be one of the following:

  1. an OpenSSLAsymmetricKey instance
  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/public key (it may contain both).
  3. A PEM formatted public key.

### Return Values

Returns an OpenSSLAsymmetricKey instance on success, or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was returned.
8.0.0 | `public_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_new — Generates a new private key

### Description

openssl_pkey_new(?array `$options` = `null`): OpenSSLAsymmetricKey|false

openssl_pkey_new() generates a new private key. How to obtain the public component of the key is shown in an example below.

> Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

### Parameters

`options`

  It is possible to fine-tune the key generation (e.g. specifying the number of bits or parameters) using the `options` parameter. These options can either be algorithm-specific parameters used for key generation, or generic options used also in CSRgeneration if not specified. See openssl_csr_new() for more information about how to use `options` for a CSR. Among those options only `private_key_bits`, `private_key_type`, `curve_name`, and `config` are used for key generation. Algorithm-specific options are used if the associative array includes one of the specific keys.

  - `"rsa"` key for setting RSA parameters.

    options | type | format | required | description
    --- | --- | --- | --- | ---
    `"n"` | string | binary number | yes | modulus
    `"e"` | string | binary number | no | public exponent
    `"d"` | string | binary number | yes | private exponent
    `"p"` | string | binary number | no | prime 1
    `"q"` | string | binary number | no | prime 2
    `"dmp1"` | string | binary number | no | exponent1, d mod (p-1)
    `"dmq1"` | string | binary number | no | exponent2, d mod (q-1)
    `"iqmp"` | string | binary number | no | coefficient, (inverse of q) mod p

  - `"dsa"` key for setting DSA parameters.

    options | type | format | required | description
    --- | --- | --- | --- | ---
    `"p"` | string | binary number | no | prime number (public)
    `"q"` | string | binary number | no | 160-bit subprime, q | p-1 (public)
    `"g"` | string | binary number | no | generator of subgroup (public)
    `"priv_key"` | string | PEM key | no | private key x
    `"pub_key"` | string | PEM key | no | public key y = g^x

  - `"dh"` key for DH (Diffie–Hellman key exchange) parameters.

    Options | Type | Format | Required | Description
    --- | --- | --- | --- | ---
    `"p"` | string | binary number | no | prime number (shared)
    `"g"` | string | binary number | no | generator of Z_p (shared)
    `"priv_key"` | string | PEM key | no | private DH value x
    `"pub_key"` | string | PEM key | no | public DH value g^x

  - `"ec"` key for Elliptic curve parameters

    Options | Type | Format | Required | Description
    --- | --- | --- | --- | ---
    `"curve_name"` | string | name | no | name of curve, see openssl_get_curve_names()
    `"p"` | string | binary number | no | prime of the field for curve over Fp
    `"a"` | string | binary number | no | coofecient a of the curve for Fp: y^2 mod p = x^3 + ax + b mod p
    `"b"` | string | binary number | no | coofecient b of the curve for Fp: y^2 mod p = x^3 + ax + b mod p
    `"seed"` | string | binary number | no | optional random number seed used to generate coefficient b
    `"generator"` | string | binary encoded point | no | curve generator point
    `"g_x"` | string | binary number | no | curver generator point x coordinat
    `"g_y"` | string | binary number | no | curver generator point y coordinat
    `"cofactor"` | string | binary number | no | curve cofactor
    `"order"` | string | binary number | no | curve order
    `"x"` | string | binary number | no | x coordinate (public)
    `"y"` | string | binary number | no | y coordinate (public)
    `"d"` | string | binary number | no | private key

  - `"x25519"`, `"x448"`, `"ed25519"`, `"ed448"` keys for Curve25519 and Curve448 parameters.

    Options | Type | Format | Required | Description
    --- | --- | --- | --- | ---
    `"priv_key"` | string | PEM key | no | private key
    `"pub_key"` | string | PEM key | no | public key

### Return Values

Returns an OpenSSLAsymmetricKey instance for the pkey on success, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | Added support for Curve25519 and Curve448 based keys with the introduction of the `x25519`, `ed25519`, `x448`, and `ed448` fields.
8.3.0 | Added support for generation EC keys with custom EC parameters. Specifically with the introduction of the EC options: `p`, `a`, `b`, `seed`, `generator`, `g_x`, `g_y`, `cofactor`, and `order`.
8.0.0 | On success, this function returns an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was returned.
7.1.0 | The `curve_name` key of the `options` parameter was added to make it possible to create EC keys based on Elliptic Curve algorithms.

### Examples

Example #1 Obtain the public key from a private key

`<?php
$private_key = openssl_pkey_new();
$public_key_pem = openssl_pkey_get_details($private_key)['key'];
echo $public_key_pem, PHP_EOL;
$public_key = openssl_pkey_get_public($public_key_pem);
var_dump($public_key);
?>`

The above example will output something similar to:

    // Output prior to PHP 8.0.0; note, the function returns a resource
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwknBFEherZe74BiRjTFA
    hqwZ1SK7brwq7C/afnLXKhRR7jnrpfM0ypC46q8xz5UZswenZakJ7kd5fls+r4Bv
    3P8XsKYLTh2m1GiWQhV1g77cNIN4qNWh70PiDO3fB2446o1LBgToQYuRZS5YQRfJ
    rVD0ysgtVcCU9tjaey28HlgApOpYFTaaKPj2MBmEYpMC+kG2HhL12GfpHUi2eiXI
    dXT2WskWHWvUrmQ7fJIfI92JlDokV62DH/q1oiedLs9OPNb0rL1aAmYdzaVN6XNH
    x/o4Lh125v2vAPV9E3fZCDc/HDEUaahpjanMiCQEgEDp5Hr+CRkvERT5/ydN+p08
    5wIDAQAB
    -----END PUBLIC KEY-----

    resource(6) of type (OpenSSL key)

    // Output as of PHP 8.0.0; note, the function returns an object
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwknBFEherZe74BiRjTFA
    hqwZ1SK7brwq7C/afnLXKhRR7jnrpfM0ypC46q8xz5UZswenZakJ7kd5fls+r4Bv
    3P8XsKYLTh2m1GiWQhV1g77cNIN4qNWh70PiDO3fB2446o1LBgToQYuRZS5YQRfJ
    rVD0ysgtVcCU9tjaey28HlgApOpYFTaaKPj2MBmEYpMC+kG2HhL12GfpHUi2eiXI
    dXT2WskWHWvUrmQ7fJIfI92JlDokV62DH/q1oiedLs9OPNb0rL1aAmYdzaVN6XNH
    x/o4Lh125v2vAPV9E3fZCDc/HDEUaahpjanMiCQEgEDp5Hr+CRkvERT5/ydN+p08
    5wIDAQAB
    -----END PUBLIC KEY-----

    object(OpenSSLAsymmetricKey)#2 (0) {
    }

Example #2 Generating RSA key from parameters

`<?php
$nhex = "BBF82F090682CE9C2338AC2B9DA871F7368D07EED41043A440D6B6F07454F51F" .
"B8DFBAAF035C02AB61EA48CEEB6FCD4876ED520D60E1EC4619719D8A5B8B807F" .
"AFB8E0A3DFC737723EE6B4B7D93A2584EE6A649D060953748834B2454598394E" .
"E0AAB12D7B61A51F527A9A41F6C1687FE2537298CA2A8F5946F8E5FD091DBDCB";
$ehex = "11";
$dhex = "A5DAFC5341FAF289C4B988DB30C1CDF83F31251E0668B42784813801579641B2" .
"9410B3C7998D6BC465745E5C392669D6870DA2C082A939E37FDCB82EC93EDAC9" .
"7FF3AD5950ACCFBC111C76F1A9529444E56AAF68C56C092CD38DC3BEF5D20A93" .
"9926ED4F74A13EDDFBE1A1CECC4894AF9428C2B7B8883FE4463A4BC85B1CB3C1";
$phex = "EECFAE81B1B9B3C908810B10A1B5600199EB9F44AEF4FDA493B81A9E3D84F632" .
"124EF0236E5D1E3B7E28FAE7AA040A2D5B252176459D1F397541BA2A58FB6599";
$qhex = "C97FB1F027F453F6341233EAAAD1D9353F6C42D08866B1D05A0F2035028B9D86" .
"9840B41666B42E92EA0DA3B43204B5CFCE3352524D0416A5A441E700AF461503";
$dphex = "11";
$dqhex = "11";
$qinvhex = "b06c4fdabb6301198d265bdbae9423b380f271f73453885093077fcd39e2119f" .
"c98632154f5883b167a967bf402b4e9e2e0f9656e698ea3666edfb25798039f7";
$rsa= openssl_pkey_new([
'rsa' => [
'n' => hex2bin($nhex),
'e' => hex2bin($ehex),
'd' => hex2bin($dhex),
'p' => hex2bin($phex),
'q' => hex2bin($qhex),
'dmp1' => hex2bin($dphex),
'dmq1' => hex2bin($dqhex),
'iqmp' => hex2bin($qinvhex),
],
]);
$details = openssl_pkey_get_details($rsa);
var_dump($details);
?>`

# openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_private_decrypt — Decrypts data with private key

### Description

openssl_private_decrypt(
string `$data`,
#[\SensitiveParameter] string `&$decrypted_data`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
int `$padding` = `OPENSSL_PKCS1_PADDING`,
?string `$digest_algo` = `null`
): bool

openssl_private_decrypt() decrypts `data` that was previously encrypted via openssl_public_encrypt() and stores the result into `decrypted_data`.

You can use this function e.g. to decrypt data which is supposed to only be available to you.

### Parameters

`data`

`decrypted_data`

`private_key`

  `private_key` must be the private key that corresponds to the public key that was used to encrypt the data.

`padding`

  `padding` can be one of `OPENSSL_PKCS1_PADDING`, `OPENSSL_SSLV23_PADDING`, `OPENSSL_PKCS1_OAEP_PADDING`, `OPENSSL_NO_PADDING`.

`digest_algo`
  The digest algorithm for OAEP padding, or `null` to use the default algorithm.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `digest_algo` has been added.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### See Also

- openssl_public_encrypt() - Encrypts data with public key
- openssl_public_decrypt() - Decrypts data with public key

# openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_private_encrypt — Encrypts data with private key

### Description

openssl_private_encrypt(
#[\SensitiveParameter] string `$data`,
string `&$encrypted_data`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
int `$padding` = `OPENSSL_PKCS1_PADDING`
): bool

openssl_private_encrypt() encrypts `data` with private `private_key` and stores the result into `encrypted_data`. Encrypted data can be decrypted via openssl_public_decrypt().

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.

### Parameters

`data`

`encrypted_data`

`private_key`

  `private_key` must be the private key that corresponds to the public key that will be used to decrypt the data.

`padding`

  `padding` can be one of `OPENSSL_PKCS1_PADDING`, `OPENSSL_NO_PADDING`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### See Also

- openssl_public_encrypt() - Encrypts data with public key
- openssl_public_decrypt() - Decrypts data with public key

# openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_decrypt — Decrypts data with public key

### Description

openssl_public_decrypt(
string `$data`,
#[\SensitiveParameter] string `&$decrypted_data`,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`,
int `$padding` = `OPENSSL_PKCS1_PADDING`
): bool

openssl_public_decrypt() decrypts `data` that was previous encrypted via openssl_private_encrypt() and stores the result into `decrypted_data`.

You can use this function e.g. to check if the message was written by the owner of the private key.

### Parameters

`data`

`decrypted_data`

`public_key`

  `public_key` must be the public key that corresponds to the private key that was used to encrypt the data.

`padding`

  `padding` can be one of `OPENSSL_PKCS1_PADDING`, `OPENSSL_NO_PADDING`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `public_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### See Also

- openssl_private_encrypt() - Encrypts data with private key
- openssl_private_decrypt() - Decrypts data with private key

# openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_encrypt — Encrypts data with public key

### Description

openssl_public_encrypt(
#[\SensitiveParameter] string `$data`,
string `&$encrypted_data`,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`,
int `$padding` = `OPENSSL_PKCS1_PADDING`,
?string `$digest_algo` = `null`
): bool

openssl_public_encrypt() encrypts `data` with public `public_key` and stores the result into `encrypted_data`. Encrypted data can be decrypted via openssl_private_decrypt().

This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

### Parameters

`data`

`encrypted_data`

  This will hold the result of the encryption.

`public_key`

  `public_key` must be the public key that corresponds to the private key that will be used to decrypt the data.

`padding`

  `padding` can be one of `OPENSSL_PKCS1_PADDING`, `OPENSSL_SSLV23_PADDING`, `OPENSSL_PKCS1_OAEP_PADDING`, `OPENSSL_NO_PADDING`.

`digest_algo`
  The digest algorithm for OAEP padding, or `null` to use the default algorithm.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `digest_algo` has been added.
8.0.0 | `public_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### See Also

- openssl_private_encrypt() - Encrypts data with private key
- openssl_private_decrypt() - Decrypts data with private key

# openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

### Description

openssl_random_pseudo_bytes(int `$length`, bool `&$strong_result` = `null`): string

Generates a string of pseudo-random bytes, with the number of bytes determined by the `length` parameter.

It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional `strong_result` parameter. It's rare for this to be `false`, but some systems may be broken or old.

### Parameters

`length`

  The length of the desired string of bytes. Must be a positive integer less than or equal to `2147483647`. PHP will try to cast this parameter to a non-null integer to use it.

`strong_result`

  If passed into the function, this will hold a bool value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. `true` if it did, otherwise `false`

### Return Values

Returns the generated string of bytes.

### Errors/Exceptions

openssl_random_pseudo_bytes() throws an Exception on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `strong_result` is nullable now.
7.4.0 | The function no longer returns `false` on failure, but throws an Exception instead.

### Examples

Example #1 openssl_random_pseudo_bytes() example

`<?php
for ($i = 1; $i <= 4; $i++) {
$bytes = openssl_random_pseudo_bytes($i, $cstrong);
$hex = bin2hex($bytes);
echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
var_dump($hex);
var_dump($cstrong);
echo PHP_EOL;
}
?>`

The above example will output something similar to:

    Lengths: Bytes: 1 and Hex: 2
    string(2) "42"
    bool(true)

    Lengths: Bytes: 2 and Hex: 4
    string(4) "dc6e"
    bool(true)

    Lengths: Bytes: 3 and Hex: 6
    string(6) "288591"
    bool(true)

    Lengths: Bytes: 4 and Hex: 8
    string(8) "ab86d144"
    bool(true)

### See Also

- random_bytes() - Get cryptographically secure random bytes
- bin2hex() - Convert binary data into hexadecimal representation
- crypt() - One-way string hashing
- random_int() - Get a cryptographically secure, uniformly selected integer

# openssl_seal

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_seal — Seal (encrypt) data

### Description

openssl_seal(
#[\SensitiveParameter] string `$data`,
string `&$sealed_data`,
array `&$encrypted_keys`,
array `$public_key`,
string `$cipher_algo`,
string `&$iv` = `null`
): int|false

openssl_seal() seals (encrypts) `data` using the specified `cipher_algo` with a randomly generated secret key. The key is then encrypted with each of the public keys in `public_key` array, and each encrypted envelope key is returned in `encrypted_keys`. This allows sealed data to be sent to multiple recipients (provided their public keys are available). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key. The IV (Initialization Vector) is generated, and its value is returned in `iv`.

### Parameters

`data`

  The data to seal.

`sealed_data`

  The sealed data.

`encrypted_keys`

  Array of encrypted keys.

`public_key`

  Array of OpenSSLAsymmetricKey instances containing public keys.

`cipher_algo`

  The cipher method.

  Caution

  The default value for PHP versions prior to 8.0 is (`'RC4'`) which is considered insecure. It is strongly recommended to explicitly specify a secure cipher method.

`iv`

  The initialization vector for decryption of `data`. It is required if the cipher method requires IV. This can be found out by calling openssl_cipher_iv_length() with `cipher_algo`.

  Caution

  The IV cannot be set explicitly. Any value set in it is overwritten by randomly generated value.

### Return Values

Returns the length of the sealed data on success, or `false` on error. If successful the sealed data is returned in `sealed_data`, and the envelope keys in `encrypted_keys`.

### Changelog

Version | Description
--- | ---
8.0.0 | `public_key` accepts an array of OpenSSLAsymmetricKey instances now; previously, an array of resources of type `OpenSSL key` was accepted.
8.0.0 | `cipher_algo` is no longer an optional parameter.
8.0.0 | `iv` is nullable now.

### Examples

Example #1 openssl_seal() example

`<?php
// $data is assumed to contain the data to be sealed
$data = "test";
// fetch public keys
$pk1 = openssl_get_publickey("file://cert1.pem");
$pk2 = openssl_get_publickey("file://cert2.pem");
// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
if (openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2), 'AES256', $iv) > 0) {
// possibly store the $sealed and $iv values and use later in openssl_open
echo "success\n";
}
?>`

### See Also

- openssl_open() - Open sealed data

# openssl_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_sign — Generate signature

### Description

openssl_sign(
string `$data`,
string `&$signature`,
#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`,
string|int `$algorithm` = `OPENSSL_ALGO_SHA1`,
int `$padding` = 0
): bool

openssl_sign() computes a signature for the specified `data` by generating a cryptographic digital signature using the private key associated with `private_key`. Note that the data itself is not encrypted.

### Parameters

`data`

  The string of data you wish to sign

`signature`

  If the call was successful the signature is returned in `signature`.

`private_key`

  OpenSSLAsymmetricKey - a key, returned by openssl_get_privatekey()

  string - a PEM formatted key

`algorithm`

  int - one of these Signature Algorithms.

  string - a valid string returned by openssl_get_md_methods() example, "sha256WithRSAEncryption" or "sha384".

`padding`
  RSA PSS padding to use.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `padding` has been added.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### Examples

Example #1 openssl_sign() example

`<?php
// $data is assumed to contain the data to be signed
// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");
// compute signature
openssl_sign($data, $signature, $pkeyid);
// free the key from memory
openssl_free_key($pkeyid);
?>`

Example #2 openssl_sign() example

`<?php
//data you want to sign
$data = 'my data';
//create new private and public key
$new_key_pair = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);
$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];
//create signature
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);
//save for later
file_put_contents('private_key.pem', $private_key_pem);
file_put_contents('public_key.pem', $public_key_pem);
file_put_contents('signature.dat', $signature);
//verify signature
$r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption");
var_dump($r);
?>`

### See Also

- openssl_verify() - Verify signature

# openssl_spki_export

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge

### Description

openssl_spki_export(string `$spki`): string|false

Exports PEM formatted public key from encoded signed public key and challenge

### Parameters

`spki`

  Expects a valid signed public key and challenge

### Return Values

Returns the associated PEM formatted public key or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an invalid argument is passed via the `spki` parameter.

### Examples

Example #1 openssl_spki_export() example

Extracts the associated PEM formatted public key or `null` on failure.

`<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$pubKey = openssl_spki_export(preg_replace('/SPKAC=/', '', $spkac));
if ($pubKey) {
echo $pubKey;
}
?>`

Example #2 openssl_spki_export() example from <keygen>

Extracts the associated PEM formatted public key issued from the <keygen> element

`<?php
$spkac = openssl_spki_export(preg_replace('/SPKAC=/', '', $_POST['spkac']));
if ($spkac != NULL) {
echo $spkac;
} else {
echo "Extraction of pub key failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">`

### See Also

- openssl_spki_new() - Generate a new signed public key and challenge
- openssl_spki_verify() - Verifies a signed public key and challenge
- openssl_spki_export_challenge() - Exports the challenge associated with a signed public key and challenge
- openssl_get_md_methods() - Gets available digest methods
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_spki_export_challenge

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_export_challenge — Exports the challenge associated with a signed public key and challenge

### Description

openssl_spki_export_challenge(string `$spki`): string|false

Exports challenge from encoded signed public key and challenge

### Parameters

`spki`

  Expects a valid signed public key and challenge

### Return Values

Returns the associated challenge string or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an invalid argument is passed via the `spki` parameter.

### Examples

Example #1 openssl_spki_export_challenge() example

Extracts the associated challenge string or NULL on failure.

`<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $spkac));
?>`

Example #2 openssl_spki_export_challenge() example from <keygen>

Extracts the associated challenge string issued from the <keygen> element

`<?php
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $_POST['spkac']));
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">`

### See Also

- openssl_spki_new() - Generate a new signed public key and challenge
- openssl_spki_verify() - Verifies a signed public key and challenge
- openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
- openssl_get_md_methods() - Gets available digest methods
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_spki_new

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_new — Generate a new signed public key and challenge

### Description

openssl_spki_new(#[\SensitiveParameter] OpenSSLAsymmetricKey `$private_key`, string `$challenge`, int `$digest_algo` = `OPENSSL_ALGO_MD5`): string|false

Generates a signed public key and challenge using specified hashing algorithm

### Parameters

`private_key`

  `private_key` should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

`challenge`

  The challenge associated to associate with the SPKAC

`digest_algo`

  The digest algorithm. See openssl_get_md_method().

### Return Values

Returns a signed public key and challenge string or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an unknown signature algorithm is passed via the `digest_algo` parameter.

### Changelog

Version | Description
--- | ---
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey instance now; previously, a resource of type `OpenSSL key` was accepted.

### Examples

Example #1 openssl_spki_new() example

Generate a new SPKAC with the default digest (MD5)

`<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'testing');
if ($spkac !== NULL) {
echo $spkac;
} else {
echo "SPKAC generation failed";
}
?>`

The above example will output something similar to:

    MIICRzCCAS8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM3V3sS4o4
    mB9dczziRnjGAmSp+JwPrHoYMAFGvDNmZGyiWfU586X4BKs++BAj7e/FsAfno0Hd
    hN9FwpCNFSox30L03nQvLYJE7f/WqigwBeMRT7Op/xvFks4sT70xP2HRYv4KqP9a
    WRcKU6cFH8VxhFhqM2txEIxZKdFLaL28yT7bEDmcglf4JLDdgNMb9rET1dkgtKE6
    dOaJHPGjf1uvnOH4YwkQr7n4sLUR3Kdbh0ZJAFuQVDZulo+LLzxBBkqJJcB6FhF+
    oXCdHTKZnqAhpWDz+NXYytAmevab6IYm5TWPWsJUv1YKJA5lg2mXbbloIZlN9Mgc
    i9fi03bdw+crAgMBAAEWB3Rlc3RpbmcwDQYJKoZIhvcNAQEEBQADggEBALyUvP/o
    pPSoWBlorFyZ2RnGwKf9qMpE0q2IJP7G3oDR4LyK/m933DUiZ+YnqThrH/CWb4Ek
    y5I3OCyl3S4wCuU1ibZZwDVwYShr5ELp0J9PEf7qMQZOhNsizoC7k+Czb2xB6hYW
    sKfsfTKm3cXBtH3fdgc/Z1Z7VSWnAzYo38snqm72NTf5yFRnrQdphNNXi+kn1zHA
    lxXRyFDXHOcYsOnwAWfyXFA4QDHQ0ezz0UoCY8gJXovcZb4GRYqOLUAsF2HcNboy
    29WN8VqE29sL9QxVZFlwMcqyoLcNnyw38GvNvAGqSvzzbnEFP2MAQXJVe0H0hdp/
    MML5G2iNVgNozAo=

### See Also

- openssl_spki_verify() - Verifies a signed public key and challenge
- openssl_spki_export_challenge() - Exports the challenge associated with a signed public key and challenge
- openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
- openssl_get_md_methods() - Gets available digest methods
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_spki_verify

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_verify — Verifies a signed public key and challenge

### Description

openssl_spki_verify(string `$spki`): bool

Validates the supplied signed public key and challenge

### Parameters

`spki`

  Expects a valid signed public key and challenge

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an `E_WARNING` level error if an invalid argument is passed via the `spki` parameter.

### Examples

Example #1 openssl_spki_verify() example

Validates an existing signed public key and challenge

`<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $spkac))) {
echo $spkac;
} else {
echo "SPKAC validation failed";
}
?>`

Example #2 openssl_spki_verify() example from <keygen>

Validates an existing signed public key and challenge issued from the <keygen> element

`<?php
if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $_POST['spkac']))) {
echo $spkac;
} else {
echo "SPKAC validation failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">`

### See Also

- openssl_spki_new() - Generate a new signed public key and challenge
- openssl_spki_export_challenge() - Exports the challenge associated with a signed public key and challenge
- openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
- openssl_get_md_methods() - Gets available digest methods
- openssl_csr_new() - Generates a CSR
- openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

# openssl_verify

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_verify — Verify signature

### Description

openssl_verify(
string `$data`,
string `$signature`,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`,
string|int `$algorithm` = `OPENSSL_ALGO_SHA1`,
int `$padding` = 0
): int|false

openssl_verify() verifies that the `signature` is correct for the specified `data` using the public key associated with `public_key`. This must be the public key corresponding to the private key used for signing.

### Parameters

`data`

  The string of data used to generate the signature previously

`signature`

  A raw binary string, generated by openssl_sign() or similar means

`public_key`

  OpenSSLAsymmetricKey - a key, returned by openssl_get_publickey()

  string - a PEM formatted key (e.g. `-----BEGIN PUBLIC KEY----- MIIBCgK...`)

`algorithm`

  int - one of these Signature Algorithms.

  string - a valid string returned by openssl_get_md_methods() example, "sha1WithRSAEncryption" or "sha512".

`padding`
  RSA PSS padding to use.

### Return Values

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 or `false` on error.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `padding` has been added.
8.0.0 | `public_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### Examples

Example #1 openssl_verify() example

`<?php
// $data and $signature are assumed to contain the data and the signature
// fetch public key from certificate and ready it
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");
// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
echo "good";
} elseif ($ok == 0) {
echo "bad";
} else {
echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>`

Example #2 openssl_verify() example

`<?php
//data you want to sign
$data = 'my data';
//create new private and public key
$private_key_res = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_res);
$public_key_res = openssl_pkey_get_public($details['key']);
//create signature
openssl_sign($data, $signature, $private_key_res, "sha256WithRSAEncryption");
//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA256);
if ($ok == 1) {
echo "valid";
} elseif ($ok == 0) {
echo "invalid";
} else {
echo "error: ".openssl_error_string();
}
?>`

### See Also

- openssl_sign() - Generate signature

# openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_check_private_key — Checks if a private key corresponds to a certificate

### Description

openssl_x509_check_private_key(OpenSSLCertificate|string `$certificate`, #[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$private_key`): bool

Checks whether the given `private_key` is the private key that corresponds to `certificate`.

Warning

The function does not check if `private_key` is indeed a private key or not. It merely compares the public materials (e.g. exponent and modulus of an RSA key) and/or key parameters (e.g. EC params of an EC key) of a key pair.

This means, for example, that a public key could be given for `private_key` and the function may return `true`.

### Parameters

`certificate`

  The certificate.

`private_key`

  The private key.

### Return Values

Returns `true` if `private_key` is the private key that corresponds to `certificate`, or `false` otherwise.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.
8.0.0 | `private_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

# openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose

### Description

openssl_x509_checkpurpose(
OpenSSLCertificate|string `$certificate`,
int `$purpose`,
array `$ca_info` = [],
?string `$untrusted_certificates_file` = `null`
): bool|int

openssl_x509_checkpurpose() examines a certificate to see if it can be used for the specified `purpose`.

### Parameters

`certificate`

  The examined certificate.

`purpose`

  openssl_x509_checkpurpose() purposes
  Constant | Description
  --- | ---
  X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection?
  X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection?
  X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server?
  X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email?
  X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email?
  X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)?
  X509_PURPOSE_ANY | Can the cert be used for Any/All purposes?

  These options are not bitfields - you may specify one only!
`ca_info`

  `ca_info` should be an array of trusted CA files/dirs as described in Certificate Verification.

`untrusted_certificates_file`

  If specified, this should be the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust is placed in the certificates that come from that file.

### Return Values

Returns `true` if the certificate can be used for the intended purpose, `false` if it cannot, or -1 on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.
8.0.0 | `untrusted_certificates_file` is nullable now.

# openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_export — Exports a certificate as a string

### Description

openssl_x509_export(OpenSSLCertificate|string `$certificate`, string `&$output`, bool `$no_text` = `true`): bool

openssl_x509_export() stores `certificate` into a string named by `output` in a PEM encoded format.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`output`

  On success, this will hold the PEM.

`no_text`

  The optional parameter `notext` affects the verbosity of the output; if it is `false`, then additional human-readable information is included in the output. The default value of `notext` is `true`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_export_to_file — Exports a certificate to file

### Description

openssl_x509_export_to_file(OpenSSLCertificate|string `$certificate`, string `$output_filename`, bool `$no_text` = `true`): bool

openssl_x509_export_to_file() stores `certificate` into a file named by `output_filename` in a PEM encoded format.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`output_filename`

  Path to the output file.

`no_text`

  The optional parameter `notext` affects the verbosity of the output; if it is `false`, then additional human-readable information is included in the output. The default value of `notext` is `true`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_fingerprint

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate

### Description

openssl_x509_fingerprint(OpenSSLCertificate|string `$certificate`, string `$digest_algo` = "sha1", bool `$binary` = `false`): string|false

openssl_x509_fingerprint() returns the digest of `certificate` as a string.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`digest_algo`

  The digest method or hash algorithm to use, e.g. "sha256", one of openssl_get_md_methods().

`binary`

  When set to `true`, outputs raw binary data. `false` outputs lowercase hexits.

### Return Values

Returns a string containing the calculated certificate fingerprint as lowercase hexits unless `binary` is set to `true` in which case the raw binary representation of the message digest is returned.

Returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_free — Free certificate resource

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
openssl_x509_free(OpenSSLCertificate `$certificate`): void

> Note:

> This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.

openssl_x509_free() frees the certificate associated with the specified `certificate` resource from memory.

### Parameters

`certificate`

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | This function is now deprecated as it doesn't have an effect anymore.
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_parse — Parse an X509 certificate and return the information as an array

### Description

openssl_x509_parse(OpenSSLCertificate|string `$certificate`, bool `$short_names` = `true`): array|false

openssl_x509_parse() returns information about the supplied `certificate`, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc.

### Parameters

`certificate`

  X509 certificate. See Key/Certificate parameters for a list of valid values.

`short_names`

  `short_names` controls how the data is indexed in the array - if `short_names` is `true` (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

### Return Values

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

### Changelog

Version | Description
--- | ---
8.4.0 | Parsing certificate with no seconds in UTCTime is no longer allowed for any OpenSSL version. It was already disallowed for OpenSSL version 3.3+.
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_read — Parse an X.509 certificate and return an object for it

### Description

openssl_x509_read(OpenSSLCertificate|string `$certificate`): OpenSSLCertificate|false

openssl_x509_read() parses the certificate supplied by `certificate` and returns an OpenSSLCertificate object for it.

### Parameters

`certificate`

  X509 certificate. See Key/Certificate parameters for a list of valid values.

### Return Values

Returns an OpenSSLCertificate on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was returned.
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.

# openssl_x509_verify

(PHP 7 >= 7.4.0, PHP 8)

openssl_x509_verify — Verifies digital signature of x509 certificate against a public key

### Description

openssl_x509_verify(OpenSSLCertificate|string `$certificate`, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string `$public_key`): int

openssl_x509_verify() verifies that the `certificate` certificate was signed by the private key corresponding to public key `public_key`.

### Parameters

`certificate`

  See Key/Certificate parameters for a list of valid values.

`public_key`

  OpenSSLAsymmetricKey - a key, returned by openssl_get_publickey()

  string - a PEM formatted key (e.g. `-----BEGIN PUBLIC KEY----- MIIBCgK...`)

### Return Values

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `certificate` accepts an OpenSSLCertificate instance now; previously, a resource of type `OpenSSL X.509` was accepted.
8.0.0 | `public_key` accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type `OpenSSL key` or `OpenSSL X.509` was accepted.

### Examples

Example #1 openssl_x509_verify() example

`<?php
$hostname = "news.php.net";
$ssloptions = array(
"capture_peer_cert" => true,
"capture_peer_cert_chain" => true,
"allow_self_signed"=> false,
"CN_match" => $hostname,
"verify_peer" => true,
"SNI_enabled" => true,
"SNI_server_name" => $hostname,
);
$ctx = stream_context_create( array("ssl" => $ssloptions) );
$result = stream_socket_client("ssl://$hostname:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);
$cont = stream_context_get_params($result);
$x509 = $cont["options"]["ssl"]["peer_certificate"];
$certparsed = openssl_x509_parse($x509);
foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $chaincert)
{
$chainparsed = openssl_x509_parse($chaincert);
$chain_public_key = openssl_get_publickey($chaincert);
$r = openssl_x509_verify($x509, $chain_public_key);
if ($r==1)
{
echo $certparsed['subject']['CN'];
echo " was digitally signed by ";
echo $chainparsed['subject']['CN']."\n";
}
}
?>`

### See Also

- openssl_verify() - Verify signature
- openssl_get_publickey() - Alias of openssl_pkey_get_public

## Table of Contents

- openssl_cipher_iv_length — Gets the cipher iv length
- openssl_cipher_key_length — Gets the cipher key length
- openssl_cms_decrypt — Decrypt a CMS message
- openssl_cms_encrypt — Encrypt a CMS message
- openssl_cms_read — Export the CMS file to an array of PEM certificates
- openssl_cms_sign — Sign a file
- openssl_cms_verify — Verify a CMS signature
- openssl_csr_export — Exports a CSR as a string
- openssl_csr_export_to_file — Exports a CSR to a file
- openssl_csr_get_public_key — Returns the public key of a CSR
- openssl_csr_get_subject — Returns the subject of a CSR
- openssl_csr_new — Generates a CSR
- openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
- openssl_decrypt — Decrypts data
- openssl_dh_compute_key — Computes shared secret for public value of remote DH public key and local DH key
- openssl_digest — Computes a digest
- openssl_encrypt — Encrypts data
- openssl_error_string — Return openSSL error message
- openssl_free_key — Free key resource
- openssl_get_cert_locations — Retrieve the available certificate locations
- openssl_get_cipher_methods — Gets available cipher methods
- openssl_get_curve_names — Gets list of available curve names for ECC
- openssl_get_md_methods — Gets available digest methods
- openssl_get_privatekey — Alias of openssl_pkey_get_private
- openssl_get_publickey — Alias of openssl_pkey_get_public
- openssl_open — Open sealed data
- openssl_password_hash — Create a password hash using OpenSSL's Argon2 implementation
- openssl_password_verify — Verify a password against a hash using OpenSSL's Argon2 implementation
- openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string
- openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable
- openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
- openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
- openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
- openssl_pkcs7_encrypt — Encrypt an S/MIME message
- openssl_pkcs7_read — Export the PKCS7 file to an array of PEM certificates
- openssl_pkcs7_sign — Sign an S/MIME message
- openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
- openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key
- openssl_pkey_export — Gets an exportable representation of a key into a string
- openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
- openssl_pkey_free — Frees a private key
- openssl_pkey_get_details — Returns an array with the key details
- openssl_pkey_get_private — Get a private key
- openssl_pkey_get_public — Extract public key from certificate and prepare it for use
- openssl_pkey_new — Generates a new private key
- openssl_private_decrypt — Decrypts data with private key
- openssl_private_encrypt — Encrypts data with private key
- openssl_public_decrypt — Decrypts data with public key
- openssl_public_encrypt — Encrypts data with public key
- openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes
- openssl_seal — Seal (encrypt) data
- openssl_sign — Generate signature
- openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
- openssl_spki_export_challenge — Exports the challenge associated with a signed public key and challenge
- openssl_spki_new — Generate a new signed public key and challenge
- openssl_spki_verify — Verifies a signed public key and challenge
- openssl_verify — Verify signature
- openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
- openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
- openssl_x509_export — Exports a certificate as a string
- openssl_x509_export_to_file — Exports a certificate to file
- openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
- openssl_x509_free — Free certificate resource
- openssl_x509_parse — Parse an X509 certificate and return the information as an array
- openssl_x509_read — Parse an X.509 certificate and return an object for it
- openssl_x509_verify — Verifies digital signature of x509 certificate against a public key

# The OpenSSLCertificate class

(PHP 8)

## Introduction

A fully opaque class which replaces `OpenSSL X.509` resources as of PHP 8.0.0.

## Class synopsis

final class OpenSSLCertificate {
}

# The OpenSSLCertificateSigningRequest class

(PHP 8)

## Introduction

A fully opaque class which replaces `OpenSSL X.509 CSR` resources as of PHP 8.0.0.

## Class synopsis

final class OpenSSLCertificateSigningRequest {
}

# The OpenSSLAsymmetricKey class

(PHP 8)

## Introduction

A fully opaque class which replaces `OpenSSL key` resources as of PHP 8.0.0.

## Class synopsis

final class OpenSSLAsymmetricKey {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
  - Purpose checking flags
  - Padding flags for asymmetric encryption
  - Key types
  - PKCS7 Flags/Constants
  - CMS Flags/Constants
  - Signature Algorithms
  - Ciphers
  - Version constants
  - Server Name Indication constants
  - Other Constants
- Key/Certificate parameters
- Certificate Verification
- OpenSSL Functions
  - openssl_cipher_iv_length — Gets the cipher iv length
  - openssl_cipher_key_length — Gets the cipher key length
  - openssl_cms_decrypt — Decrypt a CMS message
  - openssl_cms_encrypt — Encrypt a CMS message
  - openssl_cms_read — Export the CMS file to an array of PEM certificates
  - openssl_cms_sign — Sign a file
  - openssl_cms_verify — Verify a CMS signature
  - openssl_csr_export — Exports a CSR as a string
  - openssl_csr_export_to_file — Exports a CSR to a file
  - openssl_csr_get_public_key — Returns the public key of a CSR
  - openssl_csr_get_subject — Returns the subject of a CSR
  - openssl_csr_new — Generates a CSR
  - openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
  - openssl_decrypt — Decrypts data
  - openssl_dh_compute_key — Computes shared secret for public value of remote DH public key and local DH key
  - openssl_digest — Computes a digest
  - openssl_encrypt — Encrypts data
  - openssl_error_string — Return openSSL error message
  - openssl_free_key — Free key resource
  - openssl_get_cert_locations — Retrieve the available certificate locations
  - openssl_get_cipher_methods — Gets available cipher methods
  - openssl_get_curve_names — Gets list of available curve names for ECC
  - openssl_get_md_methods — Gets available digest methods
  - openssl_get_privatekey — Alias of openssl_pkey_get_private
  - openssl_get_publickey — Alias of openssl_pkey_get_public
  - openssl_open — Open sealed data
  - openssl_password_hash — Create a password hash using OpenSSL's Argon2 implementation
  - openssl_password_verify — Verify a password against a hash using OpenSSL's Argon2 implementation
  - openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string
  - openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable
  - openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
  - openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
  - openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
  - openssl_pkcs7_encrypt — Encrypt an S/MIME message
  - openssl_pkcs7_read — Export the PKCS7 file to an array of PEM certificates
  - openssl_pkcs7_sign — Sign an S/MIME message
  - openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
  - openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key
  - openssl_pkey_export — Gets an exportable representation of a key into a string
  - openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
  - openssl_pkey_free — Frees a private key
  - openssl_pkey_get_details — Returns an array with the key details
  - openssl_pkey_get_private — Get a private key
  - openssl_pkey_get_public — Extract public key from certificate and prepare it for use
  - openssl_pkey_new — Generates a new private key
  - openssl_private_decrypt — Decrypts data with private key
  - openssl_private_encrypt — Encrypts data with private key
  - openssl_public_decrypt — Decrypts data with public key
  - openssl_public_encrypt — Encrypts data with public key
  - openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes
  - openssl_seal — Seal (encrypt) data
  - openssl_sign — Generate signature
  - openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
  - openssl_spki_export_challenge — Exports the challenge associated with a signed public key and challenge
  - openssl_spki_new — Generate a new signed public key and challenge
  - openssl_spki_verify — Verifies a signed public key and challenge
  - openssl_verify — Verify signature
  - openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
  - openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
  - openssl_x509_export — Exports a certificate as a string
  - openssl_x509_export_to_file — Exports a certificate to file
  - openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
  - openssl_x509_free — Free certificate resource
  - openssl_x509_parse — Parse an X509 certificate and return the information as an array
  - openssl_x509_read — Parse an X.509 certificate and return an object for it
  - openssl_x509_verify — Verifies digital signature of x509 certificate against a public key
- OpenSSLCertificate — The OpenSSLCertificate class
- OpenSSLCertificateSigningRequest — The OpenSSLCertificateSigningRequest class
- OpenSSLAsymmetricKey — The OpenSSLAsymmetricKey class

# Password Hashing

# Introduction

The password hashing API provides an easy to use wrapper around crypt() and some other password hashing algorithms, to make it easy to create and manage passwords in a secure manner.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

No external libraries are needed to build this extension.

For Argon2 password hashing, either » libargon2 is required or, as of PHP 8.4.0, OpenSSL version 3.2 or later. As of PHP 7.3.0, libargon2 version 20161029 or later is required if libargon2 is used.

## Installation

There is no installation needed to use these functions; they are part of the PHP core.

However, to enable Argon2 password hashing, PHP must be built either with libargon2 support using the --with-password-argon2 configure option or, starting from PHP 8.4.0, with OpenSSL using --with-openssl and --with-openssl-argon2.

Prior to PHP 8.1.0, it was possible to specify the argon2 directory with --with-password-argon2[=DIR].

# Predefined Constants

The constants below are always available as part of the PHP core.

`PASSWORD_BCRYPT` (string)

  `PASSWORD_BCRYPT` is used to create new password hashes using the `CRYPT_BLOWFISH` algorithm.

  This will always result in a hash using the "$2y$" crypt format, which is always 60 characters wide.

  Supported Options:

  - `salt` (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

    If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation and as of PHP 7.0.0 the salt option has been deprecated.

  - `cost` (int) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

    If omitted, a default value of `12` will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

`PASSWORD_BCRYPT_DEFAULT_COST` (int)

`PASSWORD_ARGON2I` (string)

  `PASSWORD_ARGON2I` is used to create new password hashes using the Argon2i algorithm.

  Supported Options:

  - `memory_cost` (int) - Maximum memory (in kibibytes) that may be used to compute the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_MEMORY_COST`.

  - `time_cost` (int) - Maximum amount of time it may take to compute the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_TIME_COST`.

  - `threads` (int) - Number of threads to use for computing the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_THREADS`. Only available with libargon2, not with libsodium implementation.

  Available as of PHP 7.2.0.

`PASSWORD_ARGON2ID` (string)

  `PASSWORD_ARGON2ID` is used to create new password hashes using the Argon2id algorithm. It supports the same options as `PASSWORD_ARGON2I`.

  Available as of PHP 7.3.0.

`PASSWORD_ARGON2_DEFAULT_MEMORY_COST` (int)

  Default amount of memory in bytes that will be used while trying to compute a hash.

  Available as of PHP 7.2.0.

`PASSWORD_ARGON2_DEFAULT_TIME_COST` (int)

  Default amount of time that will be spent trying to compute a hash.

  Available as of PHP 7.2.0.

`PASSWORD_ARGON2_DEFAULT_THREADS` (int)

  Default number of threads that Argon2lib will use. Not available with libsodium implementation.

  Available as of PHP 7.2.0.

`PASSWORD_ARGON2_PROVIDER` (string)

  Available as of PHP 7.4.0.

`PASSWORD_DEFAULT` (string)

  The default algorithm to use for hashing if no algorithm is provided. This may change in newer PHP releases when newer, stronger hashing algorithms are supported.

  It is worth noting that over time this constant can change. It is thus important to be aware that the length of the resulting hash can change. Therefore, when using `PASSWORD_DEFAULT` the resulting hash must be stored in a way that can store arbitrary hashes, the recommended width is `255` bytes.

  Currently is an alias for `PASSWORD_BCRYPT`.

##### Changelog

Version | Description
--- | ---
7.4.0 | The values of the password algo IDs (`PASSWORD_BCRYPT`, `PASSWORD_ARGON2I`, `PASSWORD_ARGON2ID` and `PASSWORD_DEFAULT`) are now strings. Previously, they have been ints.

# Password Hashing Functions

# password_algos

(PHP 7 >= 7.4.0, PHP 8)

password_algos — Get available password hashing algorithm IDs

### Description

password_algos(): array

Returns a complete list of all registered password hashing algorithm IDs as an array of strings.

### Parameters

This function has no parameters.

### Return Values

Returns the available password hashing algorithm IDs.

### Examples

Example #1 Basic password_algos() usage

`<?php
print_r(password_algos());
?>`

The above example will output something similar to:

    Array
    (
        [0] => 2y
        [1] => argon2i
        [2] => argon2id
    )

# password_get_info

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_get_info — Returns information about the given hash

### Description

password_get_info(string `$hash`): array

When passed in a valid hash created by an algorithm supported by password_hash(), this function will return an array of information about that hash.

### Parameters

`hash`

  A hash created by password_hash().

### Return Values

Returns an associative array with three elements:

- `algo`, which will match a password algorithm constant
- `algoName`, which has the human readable name of the algorithm
- `options`, which includes the options provided when calling password_hash()

# password_hash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_hash — Creates a password hash

### Description

password_hash(#[\SensitiveParameter] string `$password`, string|int|null `$algo`, array `$options` = []): string

password_hash() creates a new password hash using a strong one-way hashing algorithm.

The following algorithms are currently supported:

- `PASSWORD_DEFAULT` - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 bytes (255 bytes would be a good choice).
- `PASSWORD_BCRYPT` - Use the bcrypt algorithm to create the hash. This will produce a standard crypt() compatible hash using the `$2y$` identifier.
- `PASSWORD_ARGON2I` - Use the Argon2i hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
- `PASSWORD_ARGON2ID` - Use the Argon2id hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.

Supported options for `PASSWORD_BCRYPT`:

- `salt` (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

  If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

  Warning

  The salt option is deprecated. It is now preferred to simply use the salt that is generated by default. As of PHP 8.0.0, an explicitly given salt is ignored.

- `cost` (int) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

  If omitted, a default value of `12` will be used. This is a good baseline cost, but it should be adjusted depending on hardware used.

Supported options for `PASSWORD_ARGON2I` and `PASSWORD_ARGON2ID`:

- `memory_cost` (int) - Maximum memory (in kibibytes) that may be used to compute the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_MEMORY_COST`.

- `time_cost` (int) - Maximum amount of time it may take to compute the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_TIME_COST`.

- `threads` (int) - Number of threads to use for computing the Argon2 hash. Defaults to `PASSWORD_ARGON2_DEFAULT_THREADS`.

  Warning

  Only available when PHP uses libargon2, not with libsodium implementation.

### Parameters

`password`

  The user's password.

  Caution

  Using the `PASSWORD_BCRYPT` as the algorithm, will result in the `password` parameter being truncated to a maximum length of 72 bytes.

`algo`

  A password algorithm constant denoting the algorithm to use when hashing the password.

`options`

  An associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm.

### Return Values

Returns the hashed password.

The used algorithm, cost and salt are returned as part of the hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

### Changelog

Version | Description
--- | ---
8.4.0 | The default value of the `cost` option of the `PASSWORD_BCRYPT` algorithm was increased from `10` to `12`.
8.3.0 | password_hash() now sets the underlying Random\RandomException as the Exception::$previous exception when a ValueError is thrown due to a failure in the salt generation.
8.0.0 | password_hash() no longer returns `false` on failure, instead a ValueError will be thrown if the password hashing algorithm is not valid, or an Error if the password hashing failed for an unknown error.
8.0.0 | The `algo` parameter is nullable now.
7.4.0 | The `algo` parameter expects a string now, but still accepts ints for backward compatibility.
7.4.0 | The sodium extension provides an alternative implementation for Argon2 passwords.
7.3.0 | Support for Argon2id passwords using `PASSWORD_ARGON2ID` was added.
7.2.0 | Support for Argon2i passwords using `PASSWORD_ARGON2I` was added.

### Examples

Example #1 password_hash() example

`<?php
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>`

The above example will output something similar to:

    $2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.

Example #2 password_hash() example setting cost manually

`<?php
$options = [
// Increase the bcrypt cost from 12 to 13.
'cost' => 13,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
?>`

The above example will output something similar to:

    $2y$13$xeDfQumlmdm0Sco.4qmH1OGfUUmOcuRmfae0dPJhjX1Bq0yYhqbNi

Example #3 password_hash() example finding a good cost

This code will benchmark the machine to determine how high of a cost can be used without deteriorating user experience. It is recommended to set the highest cost that does not slow down other operations the machine needs to perform. 11 is a good baseline, and more is better if the machine is fast enough. The code below aims for ≤ 350 milliseconds stretching time, which is an appropriate delay for systems handling interactive logins.

`<?php
$timeTarget = 0.350; // 350 milliseconds
$cost = 11;
do {
$cost++;
$start = microtime(true);
password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
$end = microtime(true);
} while (($end - $start) < $timeTarget);
echo "Appropriate Cost Found: " . $cost - 1;
?>`

The above example will output something similar to:

    Appropriate Cost Found: 13

Example #4 password_hash() example using Argon2i

`<?php
echo 'Argon2i hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>`

The above example will output something similar to:

    Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

### Notes

Caution

It is strongly recommended not to provide an explicit salt for this function. A secure salt will automatically be created if no salt is specified.

As noted above, providing the `salt` option in PHP 7.0.0 will generate a deprecation warning. Support for providing a salt explicitly has been removed in PHP 8.0.0.

> Note:

> It is recommended to test this function on the machine used, adjusting the cost parameter(s) so that execution of the function takes less than 350 milliseconds for interactive logins. The script in the above example will help choosing an appropriate bcrypt cost for the given machine.

> Note: Updates to supported algorithms by this function (or changes to the default one) must follow the following rules:

> - Any new algorithm must be in core for at least 1 full release of PHP prior to becoming default. So if, for example, a new algorithm is added in 7.5.5, it would not be eligible for default until 7.7 (since 7.6 would be the first full release). But if a different algorithm was added in 7.6.0, it would also be eligible for default at 7.7.0.
> - The default should only change in a full release (7.3.0, 8.0.0, etc) and not in a revision release. The only exception to this is in an emergency when a critical security flaw is found in the current default.

### See Also

- password_verify() - Verifies that a password matches a hash
- password_needs_rehash() - Checks if the given hash matches the given options
- crypt() - One-way string hashing
- sodium_crypto_pwhash_str() - Get an ASCII-encoded hash

# password_needs_rehash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_needs_rehash — Checks if the given hash matches the given options

### Description

password_needs_rehash(string `$hash`, string|int|null `$algo`, array `$options` = []): bool

This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

### Parameters

`hash`

  A hash created by password_hash().

`algo`

  A password algorithm constant denoting the algorithm to use when hashing the password.

`options`

  An associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm.

### Return Values

Returns `true` if the hash should be rehashed to match the given `algo` and `options`, or `false` otherwise.

### Changelog

Version | Description
--- | ---
7.4.0 | The `algo` parameter expects a string now, but still accepts ints for backward compatibility.

### Examples

Example #1 Usage of password_needs_rehash()

`<?php
$password = 'rasmuslerdorf';
$hash = '$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.';
$algorithm = PASSWORD_BCRYPT;
// bcrypt's cost parameter can change over time as hardware improves
$options = ['cost' => 13];
// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
// Check if either the algorithm or the options have changed
if (password_needs_rehash($hash, $algorithm, $options)) {
// If so, create a new hash, and replace the old one
$newHash = password_hash($password, $algorithm, $options);
// Update the user record with the $newHash
}
// Perform the login.
}
?>`

# password_verify

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_verify — Verifies that a password matches a hash

### Description

password_verify(#[\SensitiveParameter] string `$password`, string `$hash`): bool

Verifies that the given hash matches the given password. password_verify() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_verify().

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

This function is safe against timing attacks.

### Parameters

`password`

  The user's password.

`hash`

  A hash created by password_hash().

### Return Values

Returns `true` if the password and hash match, or `false` otherwise.

### Examples

Example #1 password_verify() example

This is a simplified example; it is recommended to rehash a correct password if necessary; see password_needs_rehash() for an example.

`<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>`

The above example will output:

    Password is valid!

### See Also

- password_needs_rehash() - Checks if the given hash matches the given options
- password_hash() - Creates a password hash
- sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash

## Table of Contents

- password_algos — Get available password hashing algorithm IDs
- password_get_info — Returns information about the given hash
- password_hash — Creates a password hash
- password_needs_rehash — Checks if the given hash matches the given options
- password_verify — Verifies that a password matches a hash

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Password Hashing Functions
  - password_algos — Get available password hashing algorithm IDs
  - password_get_info — Returns information about the given hash
  - password_hash — Creates a password hash
  - password_needs_rehash — Checks if the given hash matches the given options
  - password_verify — Verifies that a password matches a hash

# Rnp

# Introduction

Warning

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.

This module allows you to use » RNP library. RNP is a high performance C++ OpenPGP library used by Mozilla Thunderbird.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

In order to use RNP library functions you need to install the» RNP library. RNP library version >= 0.16.2 is required.

## Installation

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: » https://pecl.php.net/package/rnp

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

`RNP_KEYSTORE_GPG` (string)
  Keystore format "GPG".
`RNP_KEYSTORE_KBX` (string)
  Keystore format "KBX". For public keys only. A keybox is a file format used to store public keys along with meta information and indices.
`RNP_KEYSTORE_G10` (string)
  Keystore format "G10". For private keys.
`RNP_LOAD_SAVE_PUBLIC_KEYS` (integer)
  Load or save public keys only. Can be OR-ed with `RNP_LOAD_SAVE_SECRET_KEYS` to load both public and private keys to the FFI context or save them from the context.
`RNP_LOAD_SAVE_SECRET_KEYS` (integer)
  Load or save secret keys only. Can be OR-ed with `RNP_LOAD_SAVE_PUBLIC_KEYS` to load both public and private keys to the FFI context or save them from the context.
`RNP_LOAD_SAVE_PERMISSIVE` (integer)
  Allows to ignore bad signature/key/subkey packets during key import.
`RNP_LOAD_SAVE_SINGLE` (integer)
  If set, only the first key will be loaded.
`RNP_LOAD_SAVE_BASE64` (integer)
  Allow import of base64-encoded keys (autocrypt ones).
`RNP_FEATURE_SYMM_ALG` (string)
  List available symmetric encryption algorithms.
`RNP_FEATURE_AEAD_ALG` (string)
  List available AEAD algorithms.
`RNP_FEATURE_PROT_MODE` (string)
  List available protection modes.
`RNP_FEATURE_PK_ALG` (string)
  List available public key algorithms.
`RNP_FEATURE_HASH_ALG` (string)
  List available hash algorithms.
`RNP_FEATURE_COMP_ALG` (string)
  List available compression algorithms.
`RNP_FEATURE_CURVE` (string)
  List available elliptic curves.
`RNP_DUMP_MPI` (integer)
  Dump MPI (Multi-precision integer) values.
`RNP_DUMP_RAW` (integer)
  Dump raw packet contents as well.
`RNP_DUMP_GRIP` (integer)
  Dump key fingerprints and grips.
`RNP_JSON_DUMP_MPI` (integer)
  Dump MPI (Multi-precision integer) values.
`RNP_JSON_DUMP_RAW` (integer)
  Dump raw packet contents as well.
`RNP_JSON_DUMP_GRIP` (integer)
  Dump key fingerprints and grips.
`RNP_ENCRYPT_NOWRAP` (integer)
  Allows encryption of signed message. Message is not wrapped into literal data packet.
`RNP_KEY_EXPORT_ARMORED` (integer)
  Enable ASCII-armoring of exported data.
`RNP_KEY_EXPORT_PUBLIC` (integer)
  Export public key.
`RNP_KEY_EXPORT_SECRET` (integer)
  Export secret key.
`RNP_KEY_EXPORT_SUBKEYS` (integer)
  If primary key is being exported, all subkeys will be exported too.
`RNP_KEY_EXPORT_BASE64` (integer)
  Export base64-encoded autocrypt key instead of binary.
`RNP_KEY_REMOVE_PUBLIC` (integer)
  Remove public key.
`RNP_KEY_REMOVE_SECRET` (integer)
  Remove secret key.
`RNP_KEY_REMOVE_SUBKEYS` (integer)
  If primary key is being deleted, all of its subkeys will be removed too.

# Examples

## Table of Contents

- Clearsign text

## Clearsign text

This example will clearsign a given text.

Example #1 RNP clearsign example

`<?php
// init FFI object
$ffi = rnp_ffi_create('GPG', 'GPG');
// generate RSA key
$key = rnp_op_generate_key($ffi, 'test@example.com', 'RSA');
// sign
$data = "Example text to sign";
$signature = rnp_op_sign_cleartext($ffi, $data, array($key));
echo $signature;
// destroy FFI object
rnp_ffi_destroy($ffi);
?>`

# Rnp Functions

# rnp_backend_string

(PECL rnp >= 0.1.1)

rnp_backend_string — Return cryptographic backend library name

### Description

rnp_backend_string(): string

### Parameters

This function has no parameters.

### Return Values

Backend name string. Currently supported backends are "Botan" and "OpenSSL".

# rnp_backend_version

(PECL rnp >= 0.1.1)

rnp_backend_version — Return cryptographic backend library version

### Description

rnp_backend_version(): string

### Parameters

This function has no parameters.

### Return Values

Version string.

# rnp_decrypt

(PECL rnp >= 0.1.1)

rnp_decrypt — Decrypt PGP message

### Description

rnp_decrypt(RnpFFI `$ffi`, string `$input`): string|false

Private keys used for decryption should be loaded into the FFI object before calling this function. If password encryption was used, then password provider should be set by calling rnp_ffi_set_pass_provider().

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`input`
  Encrypted message.

### Return Values

Decrypted message on success or `false` on failure.

# rnp_dump_packets

(PECL rnp >= 0.1.1)

rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format

### Description

rnp_dump_packets(string `$input`, int `$flags`): string|false

### Parameters

`input`
  Input string containing OpenPGP data, either in binary or ASCII-armored format.
`flags`
  See `RNP_DUMP_*` predefined constants.

### Return Values

Text describing packet sequence or `false` on failure.

# rnp_dump_packets_to_json

(PECL rnp >= 0.1.1)

rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string

### Description

rnp_dump_packets_to_json(string `$input`, int `$flags`): string|false

### Parameters

`input`
  Input string containing OpenPGP data, either in binary or ASCII-armored format.
`flags`
  See `RNP_JSON_DUMP_*` predefined constants.

### Return Values

JSON string with dump or `false` on failure.

# rnp_ffi_create

(PECL rnp >= 0.1.1)

rnp_ffi_create — Create the top-level object used for interacting with the library

### Description

rnp_ffi_create(string `$pub_format`, string `$sec_format`): RnpFFI|false

### Parameters

`pub_format`
  the format of the public keyring, RNP_KEYSTORE_GPG or other RNP_KEYSTORE_* constant.
`sec_format`
  the format of the secret keyring, RNP_KEYSTORE_GPG or other RNP_KEYSTORE_* constant

### Return Values

Returns RnpFFI object on success or `false` on failure.

# rnp_ffi_destroy

(PECL rnp >= 0.1.1)

rnp_ffi_destroy — Destroy the top-level object used for interacting with the library

### Description

rnp_ffi_destroy(RnpFFI `$ffi`): void

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().

### Return Values

# rnp_ffi_set_pass_provider

(PECL rnp >= 0.1.1)

rnp_ffi_set_pass_provider — Set password provider callback function

### Description

rnp_ffi_set_pass_provider(RnpFFI `$ffi`, callable `$password_callback`): bool

Sets password provider function. This function can ask for the password on a standard input (if PHP script is executed in a command line environment), display GUI dialog or provide password in any other possible ways. Requested passwords are used to encrypt or decrypt secret keys or perform symmetric encryption/decryption operations.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`password_callback`

  The function that is to be called for every password request. It has the following signature:

  password_callback(string `$key_fp`, string `$pgp_context`, string `&$password`): bool
  - `$key_fp` - The key fingerprint, if any. Can be empty.
  - `$pgp_context` - String describing why the key is being requested.
  - `$password` - Password string reference where provided password should be stored to.
  Callback function should return `true` if password was successfully set or `false` on failure.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 simple callback function example

`<?php
function password_callback(string $key_fp, string $pgp_context, string &$password)
{
$password = "password";
return true;
}
$ffi = rnp_ffi_create('GPG', 'GPG');
rnp_ffi_set_pass_provider($ffi, 'password_callback');`

# rnp_import_keys

(PECL rnp >= 0.1.1)

rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys

### Description

rnp_import_keys(RnpFFI `$ffi`, string `$input`, int `$flags`): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`input`
  OpenPGP packets containing key(s) to be loaded. Can be either binary or ASCII armored.
`flags`
  See `RNP_LOAD_SAVE_*` predefined constants.

### Return Values

JSON string with information about new and updated keys on success or `false` on failure.

# rnp_import_signatures

(PECL rnp >= 0.1.1)

rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys

### Description

rnp_import_signatures(RnpFFI `$ffi`, string `$input`, int `$flags`): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`input`
  OpenPGP packets containing signatures to be imported. Can be either binary or ASCII armored.
`flags`
  Currently must be 0.

### Return Values

JSON string with information about updated keys on success or `false` on failure.

# rnp_key_export

(PECL rnp >= 0.1.1)

rnp_key_export — Export a key

### Description

rnp_key_export(RnpFFI `$ffi`, string `$key_fp`, int `$flags`): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Key fingerprint.
`flags`
  See `RNP_KEY_EXPORT_*` predefined constants (except `RNP_KEY_EXPORT_BASE64`).

### Return Values

OpenPGP packets of exported key (binary or ASCII-armored) on success or `false` on failure.

# rnp_key_export_autocrypt

(PECL rnp >= 0.1.1)

rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)

### Description

rnp_key_export_autocrypt(
RnpFFI `$ffi`,
string `$key_fp`,
string `$subkey_fp`,
string `$uid`,
int `$flags`
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Primary key fingerprint.
`subkey_fp`
  Subkey to export. Can be an empty string to pick the first suitable subkey.
`uid`
  User ID to export. Can be an empty string if exported key has only one uid.
`flags`
  Only `RNP_KEY_EXPORT_BASE64` is currently supported. Enabling it would export base64-encoded key data instead of binary.

### Return Values

OpenPGP packets of exported key on success or `false` on failure.

# rnp_key_export_revocation

(PECL rnp >= 0.1.1)

rnp_key_export_revocation — Generate and export primary key revocation signature

### Description

rnp_key_export_revocation(
RnpFFI `$ffi`,
string `$key_fp`,
int `$flags`,
array `$options` = ?
): string|false

Note: to revoke a key you'll need to import this signature into the keystore or use rnp_key_revoke() function.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Key fingerprint of the primary key to be revoked.
`flags`
  `RNP_KEY_EXPORT_ARMORED` or 0.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"hash"` | string | Set hash algorithm used during signature calculation.
  `"code"` | string | Code reason for revocation code. Possible values: 'no', 'superseded', 'compromised', 'retired'. If not defined, then value 'no' will be used by default.
  `"reason"` | string | Textual representation of the reason for revocation.

### Return Values

Exported revocation signature on success or `false` on failure.

# rnp_key_get_info

(PECL rnp >= 0.1.1)

rnp_key_get_info — Get information about the key

### Description

rnp_key_get_info(RnpFFI `$ffi`, string `$key_fp`): array|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Key fingerprint.

### Return Values

An associative array with information about the key or `false` on failure.

Key | Data type | Description
--- | --- | ---
`"is_primary"` | boolean | `true` if this key is the primary key.
`"is_sub"` | boolean | `true` if this key is a subkey.
`"is_valid"` | boolean | `true` if public key is valid. This includes checks of the self-signatures, expiration times, revocations and so on.
`"is_revoked"` | boolean | `true` if this key is revoked.
`"is_superseded"` | boolean | `true` if this key is superseded. Present only if the key is revoked.
`"is_compromised"` | boolean | `true` if this key is compromised. Present only if the key is revoked.
`"is_retired"` | boolean | `true` if this key is retired. Present only if the key is revoked.
`"is_expired"` | boolean | `true` if this key is expired.
`"have_secret"` | boolean | `true` if this key has secret part.
`"is_locked"` | boolean | `true` if this key is currently locked. Only present for secret keys.
`"is_protected"` | boolean | `true` if this key is protected. Only present for secret keys. A protected key is one that is encrypted and can be safely held in memory and locked/unlocked as needed.
`"have_public"` | boolean | `true` if this key has public part. Generally all keys would have public part.
`"valid_till"` | integer | The timestamp till which key can be considered as valid. Note: this will take into account not only key's expiration, but revocations as well. For the subkey primary key's validity time will be also checked.
`"bits"` | integer | Number of bits in the key. For EC-based keys it will contain size of the curve.
`"alg"` | string | Key algorithm name.
`"subkeys"` | array | An indexed array containing fingerprint strings of subkeys. Only present for primary keys. Could be empty if primary key has no subkeys.
`"uids"` | array | An indexed array containing user ID strings. Only present for primary keys. Could be empty if primary key has no user ID-s.

# rnp_key_remove

(PECL rnp >= 0.1.1)

rnp_key_remove — Remove a key from keyring(s)

### Description

rnp_key_remove(RnpFFI `$ffi`, string `$key_fp`, int `$flags`): bool

Note: you need to call rnp_save_keys() to write updated keyring(s) out.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Key fingerprint.
`flags`
  See `RNP_KEY_REMOVE_*` constants. Flag `RNP_KEY_REMOVE_SUBKEYS` will work only for the primary key and will remove all of its subkeys as well.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_key_revoke

(PECL rnp >= 0.1.1)

rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature

### Description

rnp_key_revoke(
RnpFFI `$ffi`,
string `$key_fp`,
int `$flags`,
array `$options` = ?
): bool

Note: you need to call rnp_save_keys() to write updated keyring(s) out.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`key_fp`
  Key fingerprint.
`flags`
  Currently must be 0.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"hash"` | string | Set hash algorithm used during signature calculation.
  `"code"` | string | Code reason for revocation code. Possible values: 'no', 'superseded', 'compromised', 'retired'. If not defined, then value 'no' will be used by default.
  `"reason"` | string | Textual representation of the reason for revocation.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_list_keys

(PECL rnp >= 0.1.1)

rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type

### Description

rnp_list_keys(RnpFFI `$ffi`, string `$identifier_type`): array|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`identifier_type`
  Key identifier type ("userid", "keyid", "grip", "fingerprint").

### Return Values

An associative array where key is an identifier string and value is a PGP key fingerprint or `false` on failure.

# rnp_load_keys

(PECL rnp >= 0.1.1)

rnp_load_keys — Load keys from PHP string

### Description

rnp_load_keys(
RnpFFI `$ffi`,
string `$format`,
string `$input`,
int `$flags`
): bool

Note that for G10, the input must be a directory (which must already exist).

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`format`
  The key format of the data (GPG, KBX, G10).
`input`
  OpenPGP packets containing key(s) to be loaded. Can be either binary or ASCII armored.
`flags`
  See `RNP_LOAD_SAVE_*` flags description.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_load_keys_from_path

(PECL rnp >= 0.1.1)

rnp_load_keys_from_path — Load keys from specified path

### Description

rnp_load_keys_from_path(
RnpFFI `$ffi`,
string `$format`,
string `$input_path`,
int `$flags`
): bool

Note that for G10, the input must be a directory (which must already exist).

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`format`
  The key format of the data (GPG, KBX, G10).
`input_path`
  file or directory containing the keys.
`flags`
  See `RNP_LOAD_SAVE_*` flags description.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_locate_key

(PECL rnp >= 0.1.1)

rnp_locate_key — Search for the key

### Description

rnp_locate_key(RnpFFI `$ffi`, string `$identifier_type`, string `$identifier`): string|false

Note: only valid userids are checked while searching by userid.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`identifier_type`
  Identifier type string: "userid", "keyid", "fingerprint", "grip".
`identifier`
  PGP User ID (name and email) for "userid" type, hexadecimal string that represents key id, fingerprint or key grip correspondingly.

### Return Values

Returns hexadecimal fingerprint of the key found on success or `false` on failure.

# rnp_op_encrypt

(PECL rnp >= 0.1.1)

rnp_op_encrypt — Encrypt message

### Description

rnp_op_encrypt(
RnpFFI `$ffi`,
string `$message`,
array `$recipient_keys_fp`,
array `$options` = ?
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`message`
  Message to be encrypted.
`recipient_keys_fp`
  Array with fingerprints of recipient's keys. At least one key must be present.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"compression_alg"` | string | Compression algorithm. Both `"compression_alg"` and `"compression_level"` must be set in order to enable data compression.
  `"compression_level"` | integer | Compression level, 0-9. 0 disables compression.
  `"armor"` | boolean | Enable ASCII-armored output. Disabled by default.
  `"add_signature"` | boolean | Encrypted message will be also signed.
  `"hash"` | string | Set hash algorithm used during signature calculation. "add_signature" option should be set to `true`
  `"creation_time"` | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
  `"expiration_time"` | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).
  `"password"` | string | Add password which is used to encrypt data.
  `"cipher"` | string | Set symmetric encryption algorithm. Possible values are "IDEA", "TRIPLEDES", "CAST5", "BLOWFISH", "AES128", "AES192", "AES256", "TWOFISH", "CAMELLIA128", "CAMELLIA192", "CAMELLIA256", "SM4".
  `"aead"` | string | Set AEAD mode algorithm. Possible values are "None" to disable AEAD, "EAX", "OCB".
  `"aead_bits"` | integer | Set chunk length for AEAD mode via number of chunk size bits. Must be between 0 to 56.
  `"flags"` | integer | Set additional encryption flags. Supported flags: RNP_ENCRYPT_NOWRAP - do not wrap the data in a literal data packet. This would allow to encrypt already signed data.
  `"file_name"` | string | Set the internally stored file name for the data being encrypted. Special value _CONSOLE may be used to mark message as 'for your eyes only', i.e. it should not be stored anywhere but only displayed to the receiver. Default is the empty string.
  `"file_mtime"` | integer | Set input file modification date in seconds since Jan, 1 1970 UTC.

### Return Values

Encrypted data on success or `false` on failure.

# rnp_op_generate_key

(PECL rnp >= 0.1.1)

rnp_op_generate_key — Generate key

### Description

rnp_op_generate_key(
RnpFFI `$ffi`,
string `$userid`,
string `$key_alg`,
string `$sub_alg` = ?,
array `$options` = ?
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`userid`
  PGP User ID - text that is intended to represent the name and email address of the key holder.
`key_alg`
  Primary key algorithm (i.e. 'RSA', 'DSA', etc).
`sub_alg`
  Subkey algorithm. If not set, subkey will not be generated.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"bits"` | integer | Primary key size in bits. Applicable only to RSA, DSA and El-Gamal keys.
  `"hash"` | string | Hash algorithm used in self signature or subkey binding signature.
  `"dsa_qbits"` | integer | Set size of a `q` parameter for DSA key. Note: appropriate default value will be set, depending on key bits. However you may override it if needed.
  `"curve"` | string | Set the curve used for ECC key. Note: this is only applicable for ECDSA, ECDH and SM2 keys.
  `"request_password"` | boolean | Enable requesting password via password provider. This password will be used for key encryption. Password provider callback function should be set in advance by calling rnp_ffi_set_pass_provider(). Note: this setting will be ignored if password was set via`"password"`
  `"password"` | string | Set the password used to encrypt the secret key data.
  `"expiration"` | integer | Set the key and subkey expiration time in seconds.
  `"sub_bits"` | integer | Subkey size in bits. Applicable only to RSA, DSA and El-Gamal keys.
  `"sub_hash"` | string | Hash algorithm used in subkey self signature or subkey binding signature.
  `"sub_curve"` | string | Set the curve used for ECC subkey. Note: this is only applicable for ECDSA, ECDH and SM2 keys.

### Return Values

Fingerprint of the generated primary key or `false` on failure. This fingerprint can be used later to reference the key in sign and encrypt operations. The key data is stored in FFI memory context and can be saved using rnp_save_keys() or rnp_save_keys_to_path().

# rnp_op_sign

(PECL rnp >= 0.1.1)

rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)

### Description

rnp_op_sign(
RnpFFI `$ffi`,
string `$data`,
array `$keys_fp`,
array `$options` = ?
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`data`
  Data to be signed.
`keys_fp`
  Array with key fingerprints. At least one key must be provided. Keys should be present in `ffi`.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"compression_alg"` | string | Compression algorithm. Both `"compression_alg"` and `"compression_level"` must be set in order to enable data compression.
  `"compression_level"` | integer | Compression level, 0-9. 0 disables compression.
  `"armor"` | boolean | Enable ASCII-armored output. Disabled by default.
  `"hash"` | string | Set hash algorithm used during signature calculation.
  `"creation_time"` | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
  `"expiration_time"` | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).
  `"file_name"` | string | Set input file name.Special value _CONSOLE may be used to mark message as 'for your eyes only', i.e. it should not be stored anywhere but only displayed to the receiver. Default is the empty string.
  `"file_mtime"` | integer | Set input file modification date in seconds since Jan, 1 1970 UTC.

### Return Values

Data with embedded signature(s) on success or `false` on failure.

# rnp_op_sign_cleartext

(PECL rnp >= 0.1.1)

rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message

### Description

rnp_op_sign_cleartext(
RnpFFI `$ffi`,
string `$data`,
array `$keys_fp`,
array `$options` = ?
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`data`
  Data to be signed.
`keys_fp`
  Array with key fingerprints. At least one key must be provided. Keys should be present in `ffi`.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"armor"` | boolean | Enable ASCII-armored output. Disabled by default.
  `"hash"` | string | Set hash algorithm used during signature calculation.
  `"creation_time"` | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
  `"expiration_time"` | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).

### Return Values

Cleartext signed message containing source data with additional headers and ASCII-armored signature on success or `false` on failure.

# rnp_op_sign_detached

(PECL rnp >= 0.1.1)

rnp_op_sign_detached — Perform signing operation, return detached signature(s)

### Description

rnp_op_sign_detached(
RnpFFI `$ffi`,
string `$data`,
array `$keys_fp`,
array `$options` = ?
): string|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`data`
  Data to be signed.
`keys_fp`
  Array with key fingerprints. At least one key must be provided. Keys should be present in `ffi`.
`options`
  An associative array with options.

  Key | Data type | Description
  --- | --- | ---
  `"armor"` | boolean | Enable ASCII-armored output. Disabled by default.
  `"hash"` | string | Set hash algorithm used during signature calculation.
  `"creation_time"` | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
  `"expiration_time"` | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).

### Return Values

Detached signature(s) data on success or `false` on failure.

# rnp_op_verify

(PECL rnp >= 0.1.1)

rnp_op_verify — Verify embedded or cleartext signatures

### Description

rnp_op_verify(RnpFFI `$ffi`, string `$data`): array|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`data`
  Signed data.

### Return Values

An associative array with information about verification results or `false` on failure.

Key | Data type | Description
--- | --- | ---
`"verification_status"` | string | Overall verification result, either "Success" string or appropriate error message. "Success" result is set when at least one signature is valid and successfully verified. Individual verification results for each signature can be checked in the "signatures" array.
`"file_name"` | string | File name.
`"file_mtime"` | integer | File modification time.
`"mode"` | string | Data protection (encryption) mode used in processed message. Currently defined values are "none", "cfb", "cfb-mdc", "aead-ocb", "aead-eax".
`"cipher"` | string | Symmetric cipher used for data encryption.
`"valid_integrity"` | boolean | `true` if message integrity protection was used (i.e. MDC or AEAD) and it was validated successfully.
`"signatures"` | array | An associative array describing each signature found. See description below.

"signatures" sub-array.

Key | Data type | Description
--- | --- | ---
"verification_status" | string | Signature verification status, either "Success" string or appropriate error message.
"creation_time" | integer | Signature creation time in seconds since Jan, 1 1970 UTC.
"expiration_time" | integer | Signature expiration time in seconds since the creation time or 0 if signature never expires.
"hash" | string | Hash function algorithm used to calculate the signature.
"signing_key" | string | Fingerprint of the key used for signing. Could be "Not found" if corresponding public key is not loaded to the FFI object.
"signature_type" | string | Signature type. Currently defined values are: 'binary', 'text', 'standalone', 'certification (generic)', 'certification (persona)', 'certification (casual)', 'certification (positive)', 'subkey binding', 'primary key binding', 'direct', 'key revocation', 'subkey revocation', 'certification revocation', 'timestamp', 'uknown: 0..255'.

# rnp_op_verify_detached

(PECL rnp >= 0.1.1)

rnp_op_verify_detached — Verify detached signatures

### Description

rnp_op_verify_detached(RnpFFI `$ffi`, string `$data`, string `$signature`): array|false

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`data`
  Source data.
`signature`
  Detached signature data.

### Return Values

An associative array with information about verification results or `false` on failure.

Key | Data type | Description
--- | --- | ---
`"verification_status"` | string | Overall verification result, either "Success" string or appropriate error message. "Success" result is set when at least one signature is valid and successfully verified. Individual verification results for each signature can be checked in the "signatures" array.
`"file_name"` | string | File name.
`"file_mtime"` | integer | File modification time.
`"mode"` | string | Data protection (encryption) mode used in processed message. Currently defined values are "none", "cfb", "cfb-mdc", "aead-ocb", "aead-eax".
`"cipher"` | string | Symmetric cipher used for data encryption.
`"valid_integrity"` | boolean | `true` if message integrity protection was used (i.e. MDC or AEAD) and it was validated successfully.
`"signatures"` | array | An associative array describing each signature found. See description below.

"signatures" sub-array.

Key | Data type | Description
--- | --- | ---
"verification_status" | string | Signature verification status, either "Success" string or appropriate error message.
"creation_time" | integer | Signature creation time in seconds since Jan, 1 1970 UTC.
"expiration_time" | integer | Signature expiration time in seconds since the creation time or 0 if signature never expires.
"hash" | string | Hash function algorithm used to calculate the signature.
"signing_key" | string | Fingerprint of the key used for signing. Could be "Not found" if corresponding public key is not loaded to the FFI object.
"signature_type" | string | Signature type. Currently defined values are: 'binary', 'text', 'standalone', 'certification (generic)', 'certification (persona)', 'certification (casual)', 'certification (positive)', 'subkey binding', 'primary key binding', 'direct', 'key revocation', 'subkey revocation', 'certification revocation', 'timestamp', 'uknown: 0..255'.

# rnp_save_keys

(PECL rnp >= 0.1.1)

rnp_save_keys — Save keys to PHP string

### Description

rnp_save_keys(
RnpFFI `$ffi`,
string `$format`,
string `&$output`,
int `$flags`
): bool

Note that for G10, the output must be a directory (which must already exist).

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`format`
  The key format of the data (GPG, KBX, G10).
`output`
  key packets will be saved to the string referenced by `output`.
`flags`
  See `RNP_LOAD_SAVE_*` flags description.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_save_keys_to_path

(PECL rnp >= 0.1.1)

rnp_save_keys_to_path — Save keys to specified path

### Description

rnp_save_keys_to_path(
RnpFFI `$ffi`,
string `$format`,
string `$output_path`,
int `$flags`
): bool

Saves keys present in the FFI object (loaded or generated) to the specified file or directory.

### Parameters

`ffi`
  The FFI object returned by rnp_ffi_create().
`format`
  The key format of the data (GPG, KBX, G10).
`output_path`
  File or directory path where keys should be saved to.
`flags`
  See `RNP_LOAD_SAVE_*` flags description.

### Return Values

Returns `true` on success or `false` on failure.

# rnp_supported_features

(PECL rnp >= 0.1.1)

rnp_supported_features — Get supported features in JSON format

### Description

rnp_supported_features(string `$type`): string|false

Get the JSON formatted string containing array of supported rnp feature values (algorithms, curves, etc) by type.

### Parameters

`type`
  See RNP_FEATURE_* constants for supported values.

### Return Values

String containing JSON formatted array of supported algorithms, curves, etc or `false` on failure.

# rnp_version_string

(PECL rnp >= 0.1.1)

rnp_version_string — RNP library version

### Description

rnp_version_string(): string

### Parameters

This function has no parameters.

### Return Values

Returns RNP library version string.

# rnp_version_string_full

(PECL rnp >= 0.1.1)

rnp_version_string_full — Full version string of RNP library

### Description

rnp_version_string_full(): string

### Parameters

This function has no parameters.

### Return Values

Returns full version string of RNP library.

## Table of Contents

- rnp_backend_string — Return cryptographic backend library name
- rnp_backend_version — Return cryptographic backend library version
- rnp_decrypt — Decrypt PGP message
- rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format
- rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string
- rnp_ffi_create — Create the top-level object used for interacting with the library
- rnp_ffi_destroy — Destroy the top-level object used for interacting with the library
- rnp_ffi_set_pass_provider — Set password provider callback function
- rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys
- rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys
- rnp_key_export — Export a key
- rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
- rnp_key_export_revocation — Generate and export primary key revocation signature
- rnp_key_get_info — Get information about the key
- rnp_key_remove — Remove a key from keyring(s)
- rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature
- rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type
- rnp_load_keys — Load keys from PHP string
- rnp_load_keys_from_path — Load keys from specified path
- rnp_locate_key — Search for the key
- rnp_op_encrypt — Encrypt message
- rnp_op_generate_key — Generate key
- rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)
- rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message
- rnp_op_sign_detached — Perform signing operation, return detached signature(s)
- rnp_op_verify — Verify embedded or cleartext signatures
- rnp_op_verify_detached — Verify detached signatures
- rnp_save_keys — Save keys to PHP string
- rnp_save_keys_to_path — Save keys to specified path
- rnp_supported_features — Get supported features in JSON format
- rnp_version_string — RNP library version
- rnp_version_string_full — Full version string of RNP library

# The RnpFFI class

(PECL rnp >= 0.1.1)

## Introduction

## Class synopsis

class RnpFFI {
}

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Examples
  - Clearsign text
- Rnp Functions
  - rnp_backend_string — Return cryptographic backend library name
  - rnp_backend_version — Return cryptographic backend library version
  - rnp_decrypt — Decrypt PGP message
  - rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format
  - rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string
  - rnp_ffi_create — Create the top-level object used for interacting with the library
  - rnp_ffi_destroy — Destroy the top-level object used for interacting with the library
  - rnp_ffi_set_pass_provider — Set password provider callback function
  - rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys
  - rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys
  - rnp_key_export — Export a key
  - rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
  - rnp_key_export_revocation — Generate and export primary key revocation signature
  - rnp_key_get_info — Get information about the key
  - rnp_key_remove — Remove a key from keyring(s)
  - rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature
  - rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type
  - rnp_load_keys — Load keys from PHP string
  - rnp_load_keys_from_path — Load keys from specified path
  - rnp_locate_key — Search for the key
  - rnp_op_encrypt — Encrypt message
  - rnp_op_generate_key — Generate key
  - rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)
  - rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message
  - rnp_op_sign_detached — Perform signing operation, return detached signature(s)
  - rnp_op_verify — Verify embedded or cleartext signatures
  - rnp_op_verify_detached — Verify detached signatures
  - rnp_save_keys — Save keys to PHP string
  - rnp_save_keys_to_path — Save keys to specified path
  - rnp_supported_features — Get supported features in JSON format
  - rnp_version_string — RNP library version
  - rnp_version_string_full — Full version string of RNP library
- RnpFFI — The RnpFFI class

# Sodium

# Introduction

Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more. Its goal is to provide all of the core operations needed to build higher-level cryptographic tools.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

This extension requires » libsodium ≥ 1.0.8.

## Installation

As of PHP 7.2.0 this extension is bundled with PHP. For older PHP versions this extension is available via PECL.

## Linux Systems

In order to use this extension you must compile PHP with sodium support by using the --with-sodium[=DIR] configure option.

## Windows

In order to use this extension you have to add `extension=php_sodium.dll` to php.ini.

## Installation via PECL

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: » https://pecl.php.net/package/libsodium

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

`SODIUM_LIBRARY_VERSION` (string)
`SODIUM_LIBRARY_MAJOR_VERSION` (int)
`SODIUM_LIBRARY_MINOR_VERSION` (int)
`SODIUM_BASE64_VARIANT_ORIGINAL` (int)
`SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING` (int)
`SODIUM_BASE64_VARIANT_URLSAFE` (int)
`SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING` (int)
`SODIUM_CRYPTO_AEAD_AEGIS128L_KEYBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS128L_NSECBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS128L_NPUBBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS128L_ABYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS256_KEYBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS256_NSECBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS256_NPUBBYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AEGIS256_ABYTES` (int)
  Available as of PHP 8.4.0.
`SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES` (int)
`SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES` (int)
`SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES` (int)
`SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES` (int)
`SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES` (int)
`SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES` (int)
`SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES` (int)
`SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES` (int)
`SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES` (int)
`SODIUM_CRYPTO_AUTH_BYTES` (int)
`SODIUM_CRYPTO_AUTH_KEYBYTES` (int)
`SODIUM_CRYPTO_BOX_SEALBYTES` (int)
`SODIUM_CRYPTO_BOX_SECRETKEYBYTES` (int)
`SODIUM_CRYPTO_BOX_PUBLICKEYBYTES` (int)
`SODIUM_CRYPTO_BOX_KEYPAIRBYTES` (int)
`SODIUM_CRYPTO_BOX_MACBYTES` (int)
`SODIUM_CRYPTO_BOX_NONCEBYTES` (int)
`SODIUM_CRYPTO_BOX_SEEDBYTES` (int)
`SODIUM_CRYPTO_KDF_BYTES_MIN` (int)
`SODIUM_CRYPTO_KDF_BYTES_MAX` (int)
`SODIUM_CRYPTO_KDF_CONTEXTBYTES` (int)
`SODIUM_CRYPTO_KDF_KEYBYTES` (int)
`SODIUM_CRYPTO_KX_SEEDBYTES` (int)
`SODIUM_CRYPTO_KX_SESSIONKEYBYTES` (int)
`SODIUM_CRYPTO_KX_PUBLICKEYBYTES` (int)
`SODIUM_CRYPTO_KX_SECRETKEYBYTES` (int)
`SODIUM_CRYPTO_KX_KEYPAIRBYTES` (int)
`SODIUM_CRYPTO_GENERICHASH_BYTES` (int)
`SODIUM_CRYPTO_GENERICHASH_BYTES_MIN` (int)
`SODIUM_CRYPTO_GENERICHASH_BYTES_MAX` (int)
`SODIUM_CRYPTO_GENERICHASH_KEYBYTES` (int)
`SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN` (int)
`SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX` (int)
`SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13` (int)
`SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13` (int)
`SODIUM_CRYPTO_PWHASH_ALG_DEFAULT` (int)
`SODIUM_CRYPTO_PWHASH_SALTBYTES` (int)
`SODIUM_CRYPTO_PWHASH_STRPREFIX` (string)
`SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE` (int)
`SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE` (int)
`SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE` (int)
`SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE` (int)
`SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE` (int)
`SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE` (int)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES` (int)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX` (string)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE` (int)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE` (int)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE` (int)
`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE` (int)
`SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_SCALARMULT_BYTES` (int)
`SODIUM_CRYPTO_SCALARMULT_SCALARBYTES` (int)
`SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_SHORTHASH_BYTES` (int)
`SODIUM_CRYPTO_SHORTHASH_KEYBYTES` (int)
`SODIUM_CRYPTO_SECRETBOX_KEYBYTES` (int)
`SODIUM_CRYPTO_SECRETBOX_MACBYTES` (int)
`SODIUM_CRYPTO_SECRETBOX_NONCEBYTES` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH` (int)
`SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY` (int)
`SODIUM_CRYPTO_SIGN_BYTES` (int)
`SODIUM_CRYPTO_SIGN_SEEDBYTES` (int)
`SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES` (int)
`SODIUM_CRYPTO_SIGN_SECRETKEYBYTES` (int)
`SODIUM_CRYPTO_SIGN_KEYPAIRBYTES` (int)
`SODIUM_CRYPTO_STREAM_NONCEBYTES` (int)
`SODIUM_CRYPTO_STREAM_KEYBYTES` (int)
`SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES` (int)
  Available as of PHP 8.1.0.
`SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES` (int)
  Available as of PHP 8.1.0.

# Sodium Functions

# sodium_add

(PHP 7 >= 7.2.0, PHP 8)

sodium_add — Add large numbers

### Description

sodium_add(string `&$string1`, string `$string2`): void

This adds the parameter `string2` to `string1`, overwriting the value stored in `string1`. This function assumes both parameters are binary strings that represent unsigned integers in little-endian byte order.

### Parameters

`string1`
  String representing an arbitrary-length unsigned integer in little-endian byte order. This parameter is passed by reference and will hold the sum of the two parameters.
`string2`
  String representing an arbitrary-length unsigned integer in little-endian byte order.

### Return Values

No value is returned.

# sodium_base642bin

(PHP 7 >= 7.2.0, PHP 8)

sodium_base642bin — Decodes a base64-encoded string into raw binary.

### Description

sodium_base642bin(#[\SensitiveParameter] string `$string`, int `$id`, string `$ignore` = ""): string

Converts a base64 encoded string into raw binary. Unlike base64_decode(), sodium_base642bin() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets.

### Parameters

`string`
  string; Encoded string.
`id`
  - `SODIUM_BASE64_VARIANT_ORIGINAL` for standard (`A-Za-z0-9/\+`) Base64 encoding.
  - `SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING` for standard (`A-Za-z0-9/\+`) Base64 encoding, without `=` padding characters.
  - `SODIUM_BASE64_VARIANT_URLSAFE` for URL-safe (`A-Za-z0-9\-_`) Base64 encoding.
  - `SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING` for URL-safe (`A-Za-z0-9\-_`) Base64 encoding, without `=` padding characters.
`ignore`
  Characters to ignore when decoding (e.g. whitespace characters).

### Return Values

Decoded string.

# sodium_bin2base64

(PHP 7 >= 7.2.0, PHP 8)

sodium_bin2base64 — Encodes a raw binary string with base64.

### Description

sodium_bin2base64(#[\SensitiveParameter] string `$string`, int `$id`): string

Converts a raw binary string into a base64-encoded string. Unlike base64_encode(), sodium_bin2base64() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets.

### Parameters

`string`
  Raw binary string.
`id`
  - `SODIUM_BASE64_VARIANT_ORIGINAL` for standard (`A-Za-z0-9/\+`) Base64 encoding.
  - `SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING` for standard (`A-Za-z0-9/\+`) Base64 encoding, without `=` padding characters.
  - `SODIUM_BASE64_VARIANT_URLSAFE` for URL-safe (`A-Za-z0-9\-_`) Base64 encoding.
  - `SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING` for URL-safe (`A-Za-z0-9\-_`) Base64 encoding, without `=` padding characters.

### Return Values

Base64-encoded string.

# sodium_bin2hex

(PHP 7 >= 7.2.0, PHP 8)

sodium_bin2hex — Encode to hexadecimal

### Description

sodium_bin2hex(#[\SensitiveParameter] string `$string`): string

Converts a raw binary string into a hex-encoded string. Unlike the standard hex-encoding function, sodium_bin2hex() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys).

### Parameters

`string`
  Raw binary string.

### Return Values

Hex encoded string.

# sodium_compare

(PHP 7 >= 7.2.0, PHP 8)

sodium_compare — Compare large numbers

### Description

sodium_compare(#[\SensitiveParameter] string `$string1`, #[\SensitiveParameter] string `$string2`): int

Compare two strings as if they were arbitrary-length, unsigned little-endian integers, without side-channel leakage.

### Parameters

`string1`
  Left operand
`string2`
  Right operand

### Return Values

Returns `-1` if `string1` is less than `string2`.

Returns `1` if `string1` is greater than `string2`.

Returns `0` if both strings are equal.

# sodium_crypto_aead_aegis128l_decrypt

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis128l_decrypt — Verify then decrypt a message with AEGIS-128L

### Description

sodium_crypto_aead_aegis128l_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt a message with AEGIS-128L.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_aegis128l_encrypt().
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message.
`key`
  Encryption key (128-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

### See Also

- sodium_crypto_aead_aegis128l_encrypt() - Encrypt then authenticate a message with AEGIS-128L
- sodium_crypto_aead_aegis128l_keygen() - Generate a random AEGIS-128L key

# sodium_crypto_aead_aegis128l_encrypt

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis128l_encrypt — Encrypt then authenticate a message with AEGIS-128L

### Description

sodium_crypto_aead_aegis128l_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate a message with AEGIS-128L.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message.
`key`
  Encryption key (128-bit).

### Return Values

Returns the ciphertext and authentication tag as a string of raw binary bytes.

### See Also

- sodium_crypto_aead_aegis128l_decrypt() - Verify then decrypt a message with AEGIS-128L
- sodium_crypto_aead_aegis128l_keygen() - Generate a random AEGIS-128L key

# sodium_crypto_aead_aegis128l_keygen

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis128l_keygen — Generate a random AEGIS-128L key

### Description

sodium_crypto_aead_aegis128l_keygen(): string

Generate a random key for use with sodium_crypto_aead_aegis128l_encrypt() and sodium_crypto_aead_aegis128l_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 128-bit random key.

### See Also

- sodium_crypto_aead_aegis128l_decrypt() - Verify then decrypt a message with AEGIS-128L
- sodium_crypto_aead_aegis128l_encrypt() - Encrypt then authenticate a message with AEGIS-128L

# sodium_crypto_aead_aegis256_decrypt

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis256_decrypt — Verify then decrypt a message with AEGIS-256

### Description

sodium_crypto_aead_aegis256_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt a message with AEGIS-256.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_aegis256_encrypt().
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message.
`key`
  Encryption key (256-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

### See Also

- sodium_crypto_aead_aegis256_encrypt() - Encrypt then authenticate a message with AEGIS-256
- sodium_crypto_aead_aegis256_keygen() - Generate a random AEGIS-256 key

# sodium_crypto_aead_aegis256_encrypt

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis256_encrypt — Encrypt then authenticate a message with AEGIS-256

### Description

sodium_crypto_aead_aegis256_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate a message with AEGIS-256.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message.
`key`
  Encryption key (256-bit).

### Return Values

Returns the ciphertext and authentication tag as a string of raw binary bytes.

### See Also

- sodium_crypto_aead_aegis256_decrypt() - Verify then decrypt a message with AEGIS-256
- sodium_crypto_aead_aegis256_keygen() - Generate a random AEGIS-256 key

# sodium_crypto_aead_aegis256_keygen

(PHP 8 >= 8.4.0)

sodium_crypto_aead_aegis256_keygen — Generate a random AEGIS-256 key

### Description

sodium_crypto_aead_aegis256_keygen(): string

Generate a random key for use with sodium_crypto_aead_aegis256_encrypt() and sodium_crypto_aead_aegis256_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

### See Also

- sodium_crypto_aead_aegis256_decrypt() - Verify then decrypt a message with AEGIS-256
- sodium_crypto_aead_aegis256_encrypt() - Encrypt then authenticate a message with AEGIS-256

# sodium_crypto_aead_aes256gcm_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM

### Description

sodium_crypto_aead_aes256gcm_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt with AES-256-GCM. Only available if sodium_crypto_aead_aes256gcm_is_available() returns `true`.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_aes256gcm_encrypt() (ciphertext and tag, concatenated).
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 12 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

# sodium_crypto_aead_aes256gcm_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM

### Description

sodium_crypto_aead_aes256gcm_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate with AES-256-GCM. Only available if sodium_crypto_aead_aes256gcm_is_available() returns `true`.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 12 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the ciphertext and authentication tag as a string of raw binary bytes. (Format: ciphertext, then tag.)

# sodium_crypto_aead_aes256gcm_is_available

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM

### Description

sodium_crypto_aead_aes256gcm_is_available(): bool

The return value of this function depends on whether or not the hardware supports hardware-accelerated AES.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if it is safe to encrypt with AES-256-GCM, and `false` otherwise.

# sodium_crypto_aead_aes256gcm_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key

### Description

sodium_crypto_aead_aes256gcm_keygen(): string

Generate a random key for use with sodium_crypto_aead_aes256gcm_encrypt() and sodium_crypto_aead_aes256gcm_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

# sodium_crypto_aead_chacha20poly1305_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305

### Description

sodium_crypto_aead_chacha20poly1305_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt with ChaCha20-Poly1305.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_chacha20poly1305_encrypt() (ciphertext and tag, concatenated).
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 8 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

# sodium_crypto_aead_chacha20poly1305_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305

### Description

sodium_crypto_aead_chacha20poly1305_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate with ChaCha20-Poly1305.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 8 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the ciphertext and tag on success, or `false` on failure.

# sodium_crypto_aead_chacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag

### Description

sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt with ChaCha20-Poly1305 (IETF variant).

The IETF variant uses 96-bit nonces and 32-bit internal counters, instead of 64-bit for both.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_chacha20poly1305_ietf_encrypt() (ciphertext and tag, concatenated).
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 12 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

# sodium_crypto_aead_chacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message

### Description

sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate with ChaCha20-Poly1305 (IETF variant).

The IETF variant uses 96-bit nonces and 32-bit internal counters, instead of 64-bit for both.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 12 bytes long.
`key`
  Encryption key (256-bit).

### Return Values

Returns the ciphertext and tag on success, or `false` on failure.

# sodium_crypto_aead_chacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.

### Description

sodium_crypto_aead_chacha20poly1305_ietf_keygen(): string

Generate a random key for use with sodium_crypto_aead_chacha20poly1305_ietf_encrypt() and sodium_crypto_aead_chacha20poly1305_ietf_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

# sodium_crypto_aead_chacha20poly1305_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.

### Description

sodium_crypto_aead_chacha20poly1305_keygen(): string

Generate a random key for use with sodium_crypto_aead_chacha20poly1305_encrypt() and sodium_crypto_aead_chacha20poly1305_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

# sodium_crypto_aead_xchacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305

### Description

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
string `$ciphertext`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string|false

Verify then decrypt with ChaCha20-Poly1305 (eXtended-nonce variant).

Generally, XChaCha20-Poly1305 is the best of the provided AEAD modes to use.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() (ciphertext and tag, concatenated).
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

Returns the plaintext on success, or `false` on failure.

# sodium_crypto_aead_xchacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305

### Description

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
#[\SensitiveParameter] string `$message`,
string `$additional_data`,
string `$nonce`,
#[\SensitiveParameter] string `$key`
): string

Encrypt then authenticate with XChaCha20-Poly1305 (eXtended-nonce variant).

Generally, XChaCha20-Poly1305 is the best of the provided AEAD modes to use.

### Parameters

`message`
  The plaintext message to encrypt.
`additional_data`
  Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

Returns the ciphertext and tag on success, or `false` on failure.

# sodium_crypto_aead_xchacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.

### Description

sodium_crypto_aead_xchacha20poly1305_ietf_keygen(): string

Generate a random key for use with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() and sodium_crypto_aead_xchacha20poly1305_ietf_decrypt().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

# sodium_crypto_auth

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth — Compute a tag for the message

### Description

sodium_crypto_auth(string `$message`, #[\SensitiveParameter] string `$key`): string

Symmetric message authentication via sodium_crypto_auth() provides integrity, but not confidentiality.

Unlike with digital signatures (e.g. sodium_crypto_sign_detached()), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.)

### Parameters

`message`
  The message you intend to authenticate
`key`
  Authentication key

### Return Values

Authentication tag

# sodium_crypto_auth_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth

### Description

sodium_crypto_auth_keygen(): string

Generate a key for use with sodium_crypto_auth() and sodium_crypto_auth_verify().

### Parameters

This function has no parameters.

### Return Values

Returns a 256-bit random key.

# sodium_crypto_auth_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth_verify — Verifies that the tag is valid for the message

### Description

sodium_crypto_auth_verify(string `$mac`, string `$message`, #[\SensitiveParameter] string `$key`): bool

Verify the authentication tag is valid for a given message and key.

Unlike with digital signatures (e.g. sodium_crypto_sign_verify_detached()), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.)

### Parameters

`mac`
  Authentication tag produced by sodium_crypto_auth()
`message`
  Message
`key`
  Authentication key

### Return Values

Returns `true` on success or `false` on failure.

# sodium_crypto_box

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box — Authenticated public-key encryption

### Description

sodium_crypto_box(#[\SensitiveParameter] string `$message`, string `$nonce`, #[\SensitiveParameter] string `$key_pair`): string

Encrypt a message using asymmetric (public key) cryptography.

The algorithm used by functions prefixed with sodium_crypto_box() are Elliptic Curve Diffie-Hellman over the Montgomery curve, Curve25519; usually abbreviated as X25519.

### Parameters

`message`
  The message to be encrypted.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key_pair`
  See sodium_crypto_box_keypair_from_secretkey_and_publickey(). This should include the sender's X25519 secret key and the recipient's X25519 public key.

### Return Values

Returns the encrypted message (ciphertext plus authentication tag). The ciphertext will be 16 bytes longer than the plaintext, and a raw binary string. See sodium_bin2base64() for safe encoding for storage.

# sodium_crypto_box_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key

### Description

sodium_crypto_box_keypair(): string

Generates a secret key and a public key as one string.

To get the secret key out of this unified keypair string, see sodium_crypto_box_secretkey(). To get the public key out of this unified keypair string, see sodium_crypto_box_publickey().

### Parameters

This function has no parameters.

### Return Values

One string containing both the X25519 secret key and corresponding X25519 public key.

# sodium_crypto_box_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key

### Description

sodium_crypto_box_keypair_from_secretkey_and_publickey(#[\SensitiveParameter] string `$secret_key`, string `$public_key`): string

This function exists to satisfy the API requirements of e.g. crypto_box(). Pass in one party's secret key and the other's public key, and you will obtain a "keypair" for your conversation.

### Parameters

`secret_key`
  Secret key.
`public_key`
  Public key.

### Return Values

X25519 Keypair.

# sodium_crypto_box_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_open — Authenticated public-key decryption

### Description

sodium_crypto_box_open(string `$ciphertext`, string `$nonce`, #[\SensitiveParameter] string `$key_pair`): string|false

Decrypt a message using asymmetric (public key) cryptography.

### Parameters

`ciphertext`
  The encrypted message to attempt to decrypt.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key_pair`
  See sodium_crypto_box_keypair_from_secretkey_and_publickey(). This should include the sender's public key and the recipient's secret key.

### Return Values

Returns the plaintext message on success, or `false` on failure.

# sodium_crypto_box_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair

### Description

sodium_crypto_box_publickey(#[\SensitiveParameter] string `$key_pair`): string

Given a keypair, fetch only the public key.

### Parameters

`key_pair`
  A keypair, such as one generated by sodium_crypto_box_keypair() or sodium_crypto_box_seed_keypair()

### Return Values

X25519 public key.

# sodium_crypto_box_publickey_from_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key

### Description

sodium_crypto_box_publickey_from_secretkey(#[\SensitiveParameter] string `$secret_key`): string

Given a secret key, calculate the corresponding public key.

This only works with the type of keys intended for use with crypto_box() (which uses Elliptic Curve Diffie-Hellman over the Montgomery curve, Curve25519; abbreviated as X25519), not crypto_sign() (which uses Edwards Digital Signature Algorithm over the Edwards Curve with the corresponding parameters; abbreviated Ed25519).

### Parameters

`secret_key`
  X25519 secret key

### Return Values

X25519 public key.

# sodium_crypto_box_seal

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seal — Anonymous public-key encryption

### Description

sodium_crypto_box_seal(#[\SensitiveParameter] string `$message`, string `$public_key`): string

Encrypt a message such that only the recipient can decrypt it.

Unlike with sodium_crypto_box(), you only need to know the recipient's public key to use sodium_crypto_box_seal(). One consequence of this convenience, however, is that the ciphertext isn't bound to a static public key, and is therefore not authenticated. Hence, anonymous public-key encryption.

sodium_crypto_box_seal() still provides ciphertext integrity. Just not sender identity authentication.

If you also need sender authentication, the sodium_crypto_sign() functions are likely the best place to start.

### Parameters

`message`
  The message to encrypt.
`public_key`
  The public key that corresponds to the only key that can decrypt the message.

### Return Values

A ciphertext string in the format of (one-time public key, encrypted message, authentication tag).

### Examples

Example #1 sodium_crypto_box_seal() example

`<?php
$keypair = sodium_crypto_box_keypair();
$public_key = sodium_crypto_box_publickey($keypair);
// Obfuscated plaintext to make the example more fun
$plaintext_b64 = "V3JpdGluZyBzb2Z0d2FyZSBpbiBQSFAgY2FuIGJlIGEgZGVsaWdodCE=";
$decoded_plaintext = sodium_base642bin($plaintext_b64, SODIUM_BASE64_VARIANT_ORIGINAL);
$sealed = sodium_crypto_box_seal($decoded_plaintext, $public_key);
var_dump(base64_encode($sealed));
$opened = sodium_crypto_box_seal_open($sealed, $keypair);
var_dump($opened);
?>`

The above example will output something similar to:

    string(120) "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw="
    string(41) "Writing software in PHP can be a delight!"

# sodium_crypto_box_seal_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seal_open — Anonymous public-key decryption

### Description

sodium_crypto_box_seal_open(string `$ciphertext`, #[\SensitiveParameter] string `$key_pair`): string|false

Decrypt a message that was encrypted with sodium_crypto_box_seal()

### Parameters

`ciphertext`
  The encrypted message
`key_pair`
  The keypair of the recipient. Must include the secret key.

### Return Values

The plaintext on success, or `false` on failure.

### Examples

Example #1 sodium_crypto_box_seal_open() example

`<?php
// Ciphertext is not sensitive; base64_decode is fine
$sealed_b64 = "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw=";
$sealed = base64_decode($sealed_b64);
// Keypair contains a cryptographic secret; use a timing-safe decoder
$keypair_b64 = "KZkF8wnB7bnC2aXB3lFOqCTc0Z6MllvaQb9ASVG8o2/MsewkuE4u1uaEgTzSakeiYyIW8DGj+02/L3cWIbs9bQ==";
$keypair = sodium_base642bin($keypair_b64, SODIUM_BASE64_VARIANT_ORIGINAL);
$opened = sodium_crypto_box_seal_open($sealed, $keypair);
var_dump($opened);
?>`

The above example will output something similar to:

    string(41) "Writing software in PHP can be a delight!"

# sodium_crypto_box_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair

### Description

sodium_crypto_box_secretkey(#[\SensitiveParameter] string `$key_pair`): string

Given a keypair, fetch only the secret key.

### Parameters

`key_pair`
  A keypair, such as one generated by sodium_crypto_box_keypair() or sodium_crypto_box_seed_keypair()

### Return Values

X25519 secret key.

# sodium_crypto_box_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key

### Description

sodium_crypto_box_seed_keypair(#[\SensitiveParameter] string `$seed`): string

Clamps the seed to form a secret key, derives the public key, and returns the two as a keypair.

The `*_seed_keypair` functions are ideal for generating a keypair from a password and salt. Use the result as a `seed` to generate the desired keys.

### Parameters

`seed`
  Some cryptographic input. Must be 32 bytes.

### Return Values

X25519 Keypair (secret key and public key).

# sodium_crypto_core_ristretto255_add

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_add — Adds an element

### Description

sodium_crypto_core_ristretto255_add(string `$p`, string `$q`): string

Adds an element `q` to `p`. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`p`
  An element.
`q`
  An element.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_add() example

`<?php
$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();
$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_random() - Generates a random key
- sodium_crypto_core_ristretto255_sub() - Subtracts an element

# sodium_crypto_core_ristretto255_from_hash

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_from_hash — Maps a vector

### Description

sodium_crypto_core_ristretto255_from_hash(string `$s`): string

Maps a 64-bytes vector `s` to a group element. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  A 64-bytes vector.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_from_hash() example

`<?php
$hashes = sodium_hex2bin(
'5d1be09e3d0c82fc538112490e35701979d99e06ca3e2b5b54bffe8b4dc772c1' .
'4d98b696a1bbfb5ca32c436cc61c16563790306c79eaca7705668b47dffe5bb6'
);
var_dump(sodium_bin2hex(sodium_crypto_core_ristretto255_from_hash($hashes)));
?>`

The above example will output:

    string(64) "3066f82a1a747d45120d1740f14358531a8f04bbffe6a819f86dfe50f44a0a46"

### See Also

- sodium_hex2bin() - Decodes a hexadecimally encoded binary string
- sodium_bin2hex() - Encode to hexadecimal
- sodium_crypto_core_ristretto255_from_hash()

# sodium_crypto_core_ristretto255_is_valid_point

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve

### Description

sodium_crypto_core_ristretto255_is_valid_point(string `$s`): bool

Determines if a point on the ristretto255 curve, in canonical form, on the main subgroup, and that the point doesn't have a small order. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  An Elliptic-curve point.

### Return Values

Returns `true` if `s` is on the ristretto255 curve, `false` otherwise.

### Examples

Example #1 sodium_crypto_core_ristretto255_is_valid_point() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_scalarmult_ristretto255_base($foo);
var_dump(sodium_crypto_core_ristretto255_is_valid_point($bar));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
- sodium_crypto_scalarmult_ristretto255_base() - Calculates the public key from a secret key

# sodium_crypto_core_ristretto255_random

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_random — Generates a random key

### Description

sodium_crypto_core_ristretto255_random(): string

Generates a random key. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_random() example

`<?php
$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();
$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_add() - Adds an element
- sodium_crypto_core_ristretto255_sub() - Subtracts an element

# sodium_crypto_core_ristretto255_scalar_add

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_add(string `$x`, string `$y`): string

Adds an element `y` to `x`. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`x`
  Scalar, representing the X coordinate.
`y`
  Scalar, representing the Y coordinate.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_scalar_add() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();
$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
- sodium_crypto_core_ristretto255_scalar_sub() - Subtracts a scalar value

# sodium_crypto_core_ristretto255_scalar_complement

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose

### Description

sodium_crypto_core_ristretto255_scalar_complement(string `$s`): string

Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  Scalar value.

### Return Values

Returns a 32-byte random string.

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

# sodium_crypto_core_ristretto255_scalar_invert

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_invert(string `$s`): string

Inverts a scalar value. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  Scalar value.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_scalar_invert() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$inverted = sodium_crypto_core_ristretto255_scalar_invert($foo);
$reInverted = sodium_crypto_core_ristretto255_scalar_invert($inverted);
var_dump(hash_equals($foo, $reInverted));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

# sodium_crypto_core_ristretto255_scalar_mul

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_mul(string `$x`, string `$y`): string

Multiplies a scalar value. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`x`
  Scalar, representing the X coordinate.
`y`
  Scalar, representing the Y coordinate.

### Return Values

Returns a 32-byte random string.

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

# sodium_crypto_core_ristretto255_scalar_negate

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_negate(string `$s`): string

Negates a scalar value. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  Scalar value.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_scalar_negate() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$negate = sodium_crypto_core_ristretto255_scalar_negate($foo);
$reNegate = sodium_crypto_core_ristretto255_scalar_negate($negate);
var_dump(hash_equals($foo, $reNegate));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

# sodium_crypto_core_ristretto255_scalar_random

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_random — Generates a random key

### Description

sodium_crypto_core_ristretto255_scalar_random(): string

Generates a random key. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_scalar_random() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();
$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_add() - Adds a scalar value
- sodium_crypto_core_ristretto255_scalar_sub() - Subtracts a scalar value

# sodium_crypto_core_ristretto255_scalar_reduce

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_reduce(string `$s`): string

Reduces a scalar value. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`s`
  Scalar value.

### Return Values

Returns a 32-byte random string.

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

# sodium_crypto_core_ristretto255_scalar_sub

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value

### Description

sodium_crypto_core_ristretto255_scalar_sub(string `$x`, string `$y`): string

Subtracts a scalar `y` from `x`. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`x`
  Scalar, representing the X coordinate.
`y`
  Scalar, representing the Y coordinate.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_scalar_sub() example

`<?php
$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();
$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
- sodium_crypto_core_ristretto255_scalar_add() - Adds a scalar value

# sodium_crypto_core_ristretto255_sub

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_sub — Subtracts an element

### Description

sodium_crypto_core_ristretto255_sub(string `$p`, string `$q`): string

Subtracts an element `q` from `p`. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`p`
  An element.
`q`
  An element.

### Return Values

Returns a 32-byte random string.

### Examples

Example #1 sodium_crypto_core_ristretto255_sub() example

`<?php
$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();
$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);
var_dump(hash_equals($foo, $value));
?>`

The above example will output:

    bool(true)

### See Also

- sodium_crypto_core_ristretto255_random() - Generates a random key
- sodium_crypto_core_ristretto255_add() - Adds an element

# sodium_crypto_generichash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash — Get a hash of the message

### Description

sodium_crypto_generichash(string `$message`, #[\SensitiveParameter] string `$key` = "", int `$length` = `SODIUM_CRYPTO_GENERICHASH_BYTES`): string

Hash a message with BLAKE2b.

### Parameters

`message`
  The message being hashed.
`key`
  (Optional) cryptographic key. This serves the same function as a HMAC key, but it's utilized as a reserved section of the internal BLAKE2 state.
`length`
  Output size.

### Return Values

The cryptographic hash as raw bytes. If a hex-encoded output is desired, the result can be passed to sodium_bin2hex().

# sodium_crypto_generichash_final

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_final — Complete the hash

### Description

sodium_crypto_generichash_final(string `&$state`, int `$length` = `SODIUM_CRYPTO_GENERICHASH_BYTES`): string

The finalization method for the streaming generichash API.

### Parameters

`state`
  Hash state returned from sodium_crypto_generichash_init()
`length`
  Output length.

### Return Values

Cryptographic hash.

### Examples

Example #1 sodium_crypto_generichash_final() example

`<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init('', 32);
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}
$final = sodium_crypto_generichash_final($state, 32);
var_dump(sodium_bin2hex($final));
$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>`

The above example will output something similar to:

    string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"
    string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"

# sodium_crypto_generichash_init

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_init — Initialize a hash for streaming

### Description

sodium_crypto_generichash_init(#[\SensitiveParameter] string `$key` = "", int `$length` = `SODIUM_CRYPTO_GENERICHASH_BYTES`): string

The initialization method for the streaming generichash API.

### Parameters

`key`
  The generichash key.
`length`
  The expected output length of the hash function.

### Return Values

Returns a hash state, serialized as a raw binary string.

### Examples

Example #1 sodium_crypto_generichash_init() example

`<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init('', 32);
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}
$final = sodium_crypto_generichash_final($state, 32);
var_dump(sodium_bin2hex($final));
$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>`

The above example will output something similar to:

    string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"
    string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"

# sodium_crypto_generichash_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_keygen — Generate a random generichash key

### Description

sodium_crypto_generichash_keygen(): string

Generate a random key for use with the generichash API.

### Parameters

This function has no parameters.

### Return Values

A random 256-bit key.

# sodium_crypto_generichash_update

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_update — Add message to a hash

### Description

sodium_crypto_generichash_update(string `&$state`, string `$message`): true

Appends a message to the internal hash state.

### Parameters

`state`
  The return value of sodium_crypto_generichash_init().
`message`
  Data to append to the hashing state.

### Return Values

Always returns `true`.

### Examples

Example #1 sodium_crypto_generichash_update() example

`<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init();
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}
$final = sodium_crypto_generichash_final($state);
var_dump(sodium_bin2hex($final));
$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>`

The above example will output something similar to:

    string(64) "e16e28bbbbcc39d9f5b1cbc33c41f1d217808640103e57a41f24870f79831e04"
    string(64) "e16e28bbbbcc39d9f5b1cbc33c41f1d217808640103e57a41f24870f79831e04"

# sodium_crypto_kdf_derive_from_key

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kdf_derive_from_key — Derive a subkey

### Description

sodium_crypto_kdf_derive_from_key(
int `$subkey_length`,
int `$subkey_id`,
string `$context`,
#[\SensitiveParameter] string `$key`
): string

Derive a subkey from a root key and additional context.

Similar to hash_hkdf().

### Parameters

`subkey_length`
  Length of the key to return (in bytes)
`subkey_id`
  Return the Nth subkey from a given root key. Useful for seeking.
`context`
  Application-specific context.
`key`
  The root key from which the subkey is derived.

### Return Values

A string of pseudorandom (raw binary) bytes.

# sodium_crypto_kdf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface

### Description

sodium_crypto_kdf_keygen(): string

Generates a random key suitable for serving as the root key for sodium_crypto_kdf_derive_from_key().

### Parameters

This function has no parameters.

### Return Values

A random 256-bit key.

# sodium_crypto_kx_client_session_keys

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.

### Description

sodium_crypto_kx_client_session_keys(#[\SensitiveParameter] string `$client_key_pair`, string `$server_key`): array

Calculate the client-side session keys, using the X25519 + BLAKE2b key-exchange method.

### Parameters

`client_key_pair`
  A crypto_kx keypair, such as one generated by sodium_crypto_kx_keypair().
`server_key`
  A crypto_kx public key.

### Return Values

An array consisting of two strings. The first should be used for receiving data from the server. The second should be used for sending data to the server.

# sodium_crypto_kx_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_keypair — Creates a new sodium keypair

### Description

sodium_crypto_kx_keypair(): string

Create a new sodium keypair consisting of the secret key (32 bytes) followed by the public key (32 bytes). The keys can be retrieved by calling sodium_crypto_kx_secretkey() and sodium_crypto_kx_publickey(), respectively.

### Parameters

This function has no parameters.

### Return Values

Returns the new keypair on success; throws an exception otherwise.

### Examples

Example #1 sodium_crypto_kx_keypair() usage

Create a new keypair and retrieve the secret and the public key from it.

`<?php
$keypair = sodium_crypto_kx_keypair();
$secret = sodium_crypto_kx_secretkey($keypair);
$public = sodium_crypto_kx_publickey($keypair);
printf("secret: %s\npublic: %s", sodium_bin2hex($secret), sodium_bin2hex($public));
?>`

The above example will output something similar to:

    secret: e7c5c918fdc40762e6000542c0118f4368ce8fd242b0e48c1e17202797a25daf
    public: d1f59fda8652caf40ed1a01d2b6f3802b60846986372cd8fa337b7c12c428b18

# sodium_crypto_kx_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair

### Description

sodium_crypto_kx_publickey(#[\SensitiveParameter] string `$key_pair`): string

Extract the public key from a crypto_kx keypair.

### Parameters

`key_pair`
  X25519 keypair, such as one generated by sodium_crypto_kx_keypair().

### Return Values

X25519 public key.

# sodium_crypto_kx_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.

### Description

sodium_crypto_kx_secretkey(#[\SensitiveParameter] string `$key_pair`): string

Extract the secret key from a crypto_kx keypair.

### Parameters

`key_pair`
  X25519 keypair, such as one generated by sodium_crypto_kx_keypair().

### Return Values

X25519 secret key.

# sodium_crypto_kx_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_seed_keypair — Description

### Description

sodium_crypto_kx_seed_keypair(#[\SensitiveParameter] string `$seed`): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`seed`

### Return Values

# sodium_crypto_kx_server_session_keys

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.

### Description

sodium_crypto_kx_server_session_keys(#[\SensitiveParameter] string `$server_key_pair`, string `$client_key`): array

Calculate the server-side session keys, using the X25519 + BLAKE2b key-exchange method.

### Parameters

`server_key_pair`
  A crypto_kx keypair, such as one generated by sodium_crypto_kx_keypair().
`client_key`
  A crypto_kx public key.

### Return Values

An array consisting of two strings. The first should be used for receiving data from the client. The second should be used for sending data to the client.

# sodium_crypto_pwhash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash — Derive a key from a password, using Argon2

### Description

sodium_crypto_pwhash(
int `$length`,
#[\SensitiveParameter] string `$password`,
string `$salt`,
int `$opslimit`,
int `$memlimit`,
int `$algo` = `SODIUM_CRYPTO_PWHASH_ALG_DEFAULT`
): string

This function provides low-level access to libsodium's crypto_pwhash key derivation function. Unless you have specific reason to use this function, you should use sodium_crypto_pwhash_str() or password_hash() functions instead.

A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. sodium_crypto_sign_detached()).

### Parameters

`length`
  int; The length of the password hash to generate, in bytes.
`password`
  string; The password to generate a hash for.
`salt`
  A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as random_bytes(), and have a length of exactly `SODIUM_CRYPTO_PWHASH_SALTBYTES` bytes.
`opslimit`
  Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: `SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE`, `SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE` and `SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE`.
`memlimit`
  The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: `SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE`, `SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE`, and `SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE`. Typically these should be paired with the matching `opslimit` values.
`algo`
  int A number indicating the hash algorithm to use. By default `SODIUM_CRYPTO_PWHASH_ALG_DEFAULT` (the currently recommended algorithm, which can change from one version of libsodium to another), or explicitly using `SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13`, representing the Argon2id algorithm version 1.3.

### Return Values

Returns the derived key. The return value is a binary string of the hash, not an ASCII-encoded representation, and does not contain additional information about the parameters used to create the hash, so you will need to keep that information if you are ever going to verify the password in future. Use sodium_crypto_pwhash_str() to avoid needing to do all that.

### Examples

Example #1 sodium_crypto_pwhash() example

`<?php
//Need to keep the salt if we're ever going to be able to check this password
$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);
//Using bin2hex to keep output readable
echo bin2hex(
sodium_crypto_pwhash(
16, // == 128 bits
'password',
$salt,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13
)
);
?>`

The above example will output something similar to:

    a18f346ba57992eb7e4ae6abf3fd30ee

# sodium_crypto_pwhash_scryptsalsa208sha256

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt

### Description

sodium_crypto_pwhash_scryptsalsa208sha256(
int `$length`,
#[\SensitiveParameter] string `$password`,
string `$salt`,
int `$opslimit`,
int `$memlimit`
): string

This is the scrypt counterpart to sodium_crypto_pwhash().

A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. sodium_crypto_sign_detached()).

### Parameters

`length`
  The length of the password hash to generate, in bytes.
`password`
  The password to generate a hash for.
`salt`
  A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as random_bytes(), and have a length of at least `SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES` bytes.
`opslimit`
  Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: `SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE` and `SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE`.
`memlimit`
  The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: `SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE` and `SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE`. Typically these should be paired with the matching `opslimit` values.

### Return Values

A string of bytes of the desired length.

# sodium_crypto_pwhash_scryptsalsa208sha256_str

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash

### Description

sodium_crypto_pwhash_scryptsalsa208sha256_str(#[\SensitiveParameter] string `$password`, int `$opslimit`, int `$memlimit`): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`password`
`opslimit`
`memlimit`

### Return Values

# sodium_crypto_pwhash_scryptsalsa208sha256_str_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string

### Description

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify(string `$hash`, #[\SensitiveParameter] string `$password`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`hash`
`password`

### Return Values

# sodium_crypto_pwhash_str

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str — Get an ASCII-encoded hash

### Description

sodium_crypto_pwhash_str(#[\SensitiveParameter] string `$password`, int `$opslimit`, int `$memlimit`): string

Uses a CPU- and memory-hard hash algorithm along with a randomly-generated salt, and memory and CPU limits to generate an ASCII-encoded hash suitable for password storage.

### Parameters

`password`
  string; The password to generate a hash for.
`opslimit`
  Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are constants available to set the operations limit to appropriate values depending on intended use, in order of strength: `SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE`, `SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE` and `SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE`.
`memlimit`
  The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: `SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE`, `SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE`, and `SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE`. Typically these should be paired with the matching opslimit values.

### Return Values

Returns the hashed password.

In order to produce the same password hash from the same password, the same values for `opslimit` and `memlimit` must be used. These are embedded within the generated hash, so everything that's needed to verify the hash is included. This allows the sodium_crypto_pwhash_str_verify() function to verify the hash without needing separate storage for the other parameters.

### Examples

Example #1 sodium_crypto_pwhash_str() example

`<?php
$password = 'password';
echo sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);`

The above example will output something similar to:

    $argon2id$v=19$m=65536,t=2,p=1$oWIfdaXwWwhVmovOBc2NAQ$EbsZ+JnZyyavkafS0hoc4HdaOB0ILWZESAZ7kVGa+Iw

### Notes

> Note: Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks. In contrast to the password_hash() function, there is no salt parameter (a salt is generated automatically), and the `opslimit` and `memlimit` parameters are not optional.

### See Also

- sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash
- sodium_crypto_pwhash() - Derive a key from a password, using Argon2
- password_hash() - Creates a password hash
- password_verify() - Verifies that a password matches a hash
- » Libsodium Argon2 docs

# sodium_crypto_pwhash_str_needs_rehash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password

### Description

sodium_crypto_pwhash_str_needs_rehash(string `$password`, int `$opslimit`, int `$memlimit`): bool

Determine whether or not to rehash a password, based on the current hash `opslimit` and `memlimit`.

### Parameters

`password`
  Password hash
`opslimit`
  Configured opslimit; see sodium_crypto_pwhash_str()
`memlimit`
  Configured memlimit; see sodium_crypto_pwhash_str()

### Return Values

Returns `true` if the provided memlimit/opslimit do not match what's stored in the hash. Returns `false` if they match.

# sodium_crypto_pwhash_str_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash

### Description

sodium_crypto_pwhash_str_verify(string `$hash`, #[\SensitiveParameter] string `$password`): bool

Checks that a password hash created using sodium_crypto_pwhash_str() matches a given plain-text password. Note that the parameters are in the opposite order to the same parameters in the similar password_verify() function.

### Parameters

`hash`
  A hash created by password_hash().
`password`
  The user's password.

### Return Values

Returns `true` if the password and hash match, or `false` otherwise.

### Notes

> Note: Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks.

### See Also

- sodium_crypto_pwhash_str() - Get an ASCII-encoded hash
- password_hash() - Creates a password hash
- password_verify() - Verifies that a password matches a hash

# sodium_crypto_scalarmult

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key

### Description

sodium_crypto_scalarmult(string `$n`, string `$p`): string

Elliptic Curve Diffie-Hellman. Calculates scalar n times point p, on an elliptic curve.

### Parameters

`n`
  scalar, which is typically a secret key
`p`
  point (x-coordinate), which is typically a public key

### Return Values

A 32-byte random string.

# sodium_crypto_scalarmult_base

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_scalarmult_base — Alias of sodium_crypto_box_publickey_from_secretkey()

### Description

This function is an alias of: sodium_crypto_box_publickey_from_secretkey().

# sodium_crypto_scalarmult_ristretto255

(PHP 8 >= 8.1.1)

sodium_crypto_scalarmult_ristretto255 — Computes a shared secret

### Description

sodium_crypto_scalarmult_ristretto255(string `$n`, string `$p`): string

Calculates scalar `n` times point `p`. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`n`
  A scalar, which is typically a secret key.
`p`
  A point (x-coordinate), which is typically a public key.

### Return Values

Returns a 32-byte random string.

### See Also

- sodium_crypto_scalarmult_ristretto255_base() - Calculates the public key from a secret key

# sodium_crypto_scalarmult_ristretto255_base

(PHP 8 >= 8.1.1)

sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key

### Description

sodium_crypto_scalarmult_ristretto255_base(string `$n`): string

Given a secret key, calculates the corresponding public key. Available as of libsodium 1.0.18.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`n`
  A secret key.

### Return Values

Returns a 32-byte random string.

### See Also

- sodium_crypto_scalarmult_ristretto255() - Computes a shared secret

# sodium_crypto_secretbox

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox — Authenticated shared-key encryption

### Description

sodium_crypto_secretbox(#[\SensitiveParameter] string `$message`, string `$nonce`, #[\SensitiveParameter] string `$key`): string

Encrypt a message with a symmetric (shared) key.

### Parameters

`message`
  The plaintext message to encrypt.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

Returns the encrypted string.

### Errors/Exceptions

- If `nonce` has a length of bytes different than `SODIUM_CRYPTO_SECRETBOX_NONCEBYTES` (24 bytes), a SodiumException will be thrown.
- If `key` has a length of bytes different than `SODIUM_CRYPTO_SECRETBOX_KEYBYTES` (32 bytes), a SodiumException will be thrown.
- Throws a SodiumException on failure.

### Examples

Example #1 sodium_crypto_secretbox() example

`<?php
// The $key must be kept confidential
$key = sodium_crypto_secretbox_keygen();
// Do not reuse $nonce with the same key
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext = "message to be encrypted";
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
var_dump(bin2hex($ciphertext));
// The same nonce and key are required to decrypt the $ciphertext
var_dump(sodium_crypto_secretbox_open($ciphertext, $nonce, $key));
?>`

The above example will output something similar to:

    string(78) "3a1fa3e9f7b72ef8be51d40abf8e296c6899c185d07b18b4c93e7f26aa776d24c50852cd6b1076"
    string(23) "message to be encrypted"

### See Also

- sodium_crypto_secretbox_open() - Authenticated shared-key decryption
- sodium_crypto_secretbox_keygen() - Generate random key for sodium_crypto_secretbox
- random_bytes() - Get cryptographically secure random bytes

# sodium_crypto_secretbox_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox

### Description

sodium_crypto_secretbox_keygen(): string

Generate a key for use with sodium_crypto_secretbox() and sodium_crypto_secretbox_open().

### Parameters

This function has no parameters.

### Return Values

Returns the generated string of cryptographically secure random bytes.

### Examples

Example #1 sodium_crypto_secretbox_keygen() example

`<?php
$key = sodium_crypto_secretbox_keygen();
var_dump( sodium_bin2hex( $key ) );
?>`

The above example will output something similar to:

    string(64) "88bd1dc51ec81984f3ddc5a8f59a3d95b647e2da3e879f1b9ceb0abd89e7286c"

Example #2 Comparing sodium_crypto_secretbox_keygen() with random_bytes()

`<?php
$key = sodium_crypto_secretbox_keygen();
$bytes = random_bytes( SODIUM_CRYPTO_SECRETBOX_KEYBYTES );
var_dump( mb_strlen( $key, '8bit' ) === mb_strlen( $bytes, '8bit' ) );
?>`

The above example will output:

    bool(true)

### See Also

- sodium_bin2hex() - Encode to hexadecimal
- random_bytes() - Get cryptographically secure random bytes

# sodium_crypto_secretbox_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox_open — Authenticated shared-key decryption

### Description

sodium_crypto_secretbox_open(string `$ciphertext`, string `$nonce`, #[\SensitiveParameter] string `$key`): string|false

Decrypt an encrypted message with a symmetric (shared) key.

### Parameters

`ciphertext`
  Must be in the format provided by sodium_crypto_secretbox() (ciphertext and tag, concatenated).
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

The decrypted string on success or `false` on failure.

### Errors/Exceptions

- If `nonce` has a length of bytes different than `SODIUM_CRYPTO_SECRETBOX_NONCEBYTES` (24 bytes), a SodiumException will be thrown.
- If `key` has a length of bytes different than `SODIUM_CRYPTO_SECRETBOX_KEYBYTES` (32 bytes), a SodiumException will be thrown.

### Examples

Example #1 sodium_crypto_secretbox_open() example

`<?php
// The $key must be kept confidential
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
// Do not reuse $nonce with the same key
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox('message to be encrypted', $nonce, $key);
// The same nonce and key are required to decrypt the $ciphertext
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plaintext !== false) {
echo $plaintext . PHP_EOL;
}
?>`

The above example will output:

    message to be encrypted

### See Also

- sodium_crypto_secretbox() - Authenticated shared-key encryption
- sodium_crypto_secretbox_keygen() - Generate random key for sodium_crypto_secretbox
- random_bytes() - Get cryptographically secure random bytes

# sodium_crypto_secretstream_xchacha20poly1305_init_pull

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption

### Description

sodium_crypto_secretstream_xchacha20poly1305_init_pull(string `$header`, #[\SensitiveParameter] string `$key`): string

Initialize a secretstream context for decryption.

### Parameters

`header`
  The header of the secretstream. This should be one of the values produced by sodium_crypto_secretstream_xchacha20poly1305_init_push().
`key`
  Encryption key (256-bit).

### Return Values

Secretstream state.

### Examples

Example #1 sodium_crypto_secretstream_xchacha20poly1305_init_pull() example

`<?php
function decrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
$inputFile = fopen($inputFilePath, 'rb');
$outputFile = fopen($outputFilePath, 'wb');
$header = fread($inputFile, 24);
$state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
$inputFileSize = fstat($inputFile)['size'];
// Decrypt the file and write its contents to the output file:
for ($i = 24; $i < $inputFileSize; $i += 8192) {
$ctxt_chunk = fread($inputFile, 8192);
// We're not using $tag, but in real protocols you can use this on encrypt to e.g.
// trigger a re-key or indicate the end of file. Then, on decrypt, you can assert
// this behavior.
[$ptxt_chunk, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $ctxt_chunk);
fwrite($outputFile, $ptxt_chunk);
}
sodium_memzero($state);
fclose($inputFile);
fclose($outputFile);
}
// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);
$example = sodium_hex2bin('971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c');
file_put_contents('hello.enc', $example);
decrypt_file('hello.enc', 'hello.txt.decrypted', $key);
var_dump(file_get_contents('hello.txt.decrypted'));
?>`

The above example will output something similar to:

    string(12) "Hello world!"

# sodium_crypto_secretstream_xchacha20poly1305_init_push

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption

### Description

sodium_crypto_secretstream_xchacha20poly1305_init_push(#[\SensitiveParameter] string `$key`): array

Initialize a secretstream context for encryption.

### Parameters

`key`
  Cryptography key. See sodium_crypto_secretstream_xchacha20poly1305_keygen().

### Return Values

An array with two string values:

- The secretstream state, needed for further pushes
- The secretstream header, which needs to be provided to the recipient so they can pull data

### Examples

Example #1 sodium_crypto_secretstream_xchacha20poly1305_init_push() example

`<?php
function encrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
[$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);
$inputFile = fopen($inputFilePath, 'rb');
$outputFile = fopen($outputFilePath, 'wb');
// Write the header:
fwrite($outputFile, $header);
$inputFileSize = fstat($inputFile)['size'];
// Encrypt the file and write its contents to the output file:
for ($i = 0; $i < $inputFileSize; $i += 8175) {
$ptxt_chunk = fread($inputFile, 8175);
$ctxt_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($state, $ptxt_chunk);
fwrite($outputFile, $ctxt_chunk);
}
sodium_memzero($state);
fclose($inputFile);
fclose($outputFile);
}
// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);
file_put_contents('hello.txt', 'Hello world!');
encrypt_file('hello.txt', 'hello.txt.encrypted', $key);
var_dump(sodium_bin2hex(file_get_contents('hello.txt.encrypted')));
?>`

The above example will output something similar to:

    string(106) "971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c"

# sodium_crypto_secretstream_xchacha20poly1305_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.

### Description

sodium_crypto_secretstream_xchacha20poly1305_keygen(): string

Generate a random secretstream key.

### Parameters

This function has no parameters.

### Return Values

Returns a string of random bytes.

# sodium_crypto_secretstream_xchacha20poly1305_pull

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream

### Description

sodium_crypto_secretstream_xchacha20poly1305_pull(string `&$state`, string `$ciphertext`, string `$additional_data` = ""): array|false

Decrypt a chunk of data from an encrypted stream.

### Parameters

`state`
  See sodium_crypto_secretstream_xchacha20poly1305_init_pull() and sodium_crypto_secretstream_xchacha20poly1305_init_push()
`ciphertext`
  The ciphertext chunk to decrypt.
`additional_data`
  Optional additional data to include in the authentication tag.

### Return Values

An array with two values:

- string; The decrypted chunk

- int; An optional tag (if provided during push). Possible values:

  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE`: the most common tag, that doesn't add any information about the nature of the message.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL`: indicates that the message marks the end of the stream, and erases the secret key used to encrypt the previous sequence.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH`: indicates that the message marks the end of a set of messages, but not the end of the stream. For example, a huge JSON string sent as multiple chunks can use this tag to indicate to the application that the string is complete and that it can be decoded. But the stream itself is not closed, and more data may follow.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY`: "forget" the key used to encrypt this message and the previous ones, and derive a new secret key.

# sodium_crypto_secretstream_xchacha20poly1305_push

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API

### Description

sodium_crypto_secretstream_xchacha20poly1305_push(
string `&$state`,
#[\SensitiveParameter] string `$message`,
string `$additional_data` = "",
int `$tag` = `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE`
): string

Encrypt a chunk of data so that it can safely be decrypted in a streaming API.

### Parameters

`state`
  See sodium_crypto_secretstream_xchacha20poly1305_init_pull() and sodium_crypto_secretstream_xchacha20poly1305_init_push()
`message`
`additional_data`
`tag`
  Optional. Can be used to assert decryption behavior (i.e. re-keying or indicating the final chunk in a stream).
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE`: the most common tag, that doesn't add any information about the nature of the message.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL`: indicates that the message marks the end of the stream, and erases the secret key used to encrypt the previous sequence.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH`: indicates that the message marks the end of a set of messages, but not the end of the stream. For example, a huge JSON string sent as multiple chunks can use this tag to indicate to the application that the string is complete and that it can be decoded. But the stream itself is not closed, and more data may follow.
  - `SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY`: "forget" the key used to encrypt this message and the previous ones, and derive a new secret key.

### Return Values

Returns the encrypted ciphertext.

# sodium_crypto_secretstream_xchacha20poly1305_rekey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state

### Description

sodium_crypto_secretstream_xchacha20poly1305_rekey(string `&$state`): void

Explicitly rotate the key in the secretstream state. Overwrites the value passed in.

### Parameters

`state`
  Secretstream state.

### Return Values

No value is returned.

# sodium_crypto_shorthash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_shorthash — Compute a short hash of a message and key

### Description

sodium_crypto_shorthash(string `$message`, #[\SensitiveParameter] string `$key`): string

sodium_crypto_shorthash() wraps a hash function called SipHash-2-4, which is ideal for implementing hash tables that are not susceptible to hash collision denial of service attacks (Hash-DoS).

SipHash-2-4 isn't a general purpose cryptographic hash function.

### Parameters

`message`
  The message to hash.
`key`
  The hash key.

### Return Values

# sodium_crypto_shorthash_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_shorthash_keygen — Get random bytes for key

### Description

sodium_crypto_shorthash_keygen(): string

Generate a key for use with sodium_crypto_shorthash().

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# sodium_crypto_sign

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign — Sign a message

### Description

sodium_crypto_sign(string `$message`, #[\SensitiveParameter] string `$secret_key`): string

Sign a message with a secret key, that can be verified by the corresponding public key. This function attaches the signature to the message. See sodium_crypto_sign_detached() for detached signatures.

### Parameters

`message`
  Message to sign.
`secret_key`
  Secret key. See sodium_crypto_sign_secretkey()

### Return Values

Signed message (not encrypted).

# sodium_crypto_sign_detached

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_detached — Sign the message

### Description

sodium_crypto_sign_detached(string `$message`, #[\SensitiveParameter] string `$secret_key`): string

Sign a message with a secret key, that can be verified by the corresponding public key. This function returns a detached signature.

### Parameters

`message`
  Message to sign.
`secret_key`
  Secret key. See sodium_crypto_sign_secretkey()

### Return Values

Cryptographic signature.

# sodium_crypto_sign_ed25519_pk_to_curve25519

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key

### Description

sodium_crypto_sign_ed25519_pk_to_curve25519(string `$public_key`): string

Given an Ed25519 public key, calculate the birationally equivalent X25519 public key.

### Parameters

`public_key`
  Public key suitable for the crypto_sign functions.

### Return Values

Public key suitable for the crypto_box functions.

# sodium_crypto_sign_ed25519_sk_to_curve25519

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key

### Description

sodium_crypto_sign_ed25519_sk_to_curve25519(#[\SensitiveParameter] string `$secret_key`): string

Given an Ed25519 secret key, calculate the birationally equivalent X25519 secret key.

### Parameters

`secret_key`
  Secret key suitable for the crypto_sign functions.

### Return Values

Secret key suitable for the crypto_box functions.

# sodium_crypto_sign_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key

### Description

sodium_crypto_sign_keypair(): string

Generate a random Ed25519 keypair as one string.

### Parameters

This function has no parameters.

### Return Values

Ed25519 keypair.

# sodium_crypto_sign_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together

### Description

sodium_crypto_sign_keypair_from_secretkey_and_publickey(#[\SensitiveParameter] string `$secret_key`, string `$public_key`): string

Join a secret key and public key together.

### Parameters

`secret_key`
  Ed25519 secret key
`public_key`
  Ed25519 public key

### Return Values

Keypair

# sodium_crypto_sign_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_open — Check that the signed message has a valid signature

### Description

sodium_crypto_sign_open(string `$signed_message`, string `$public_key`): string|false

Verify the signature attached to a message and return the message

### Parameters

`signed_message`
  A message signed with sodium_crypto_sign()
`public_key`
  An Ed25519 public key

### Return Values

Returns the original signed message on success, or `false` on failure.

# sodium_crypto_sign_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair

### Description

sodium_crypto_sign_publickey(#[\SensitiveParameter] string `$key_pair`): string

Extract the Ed25519 public key from a keypair

### Parameters

`key_pair`
  Ed25519 keypair (see: sodium_crypto_sign_keypair())

### Return Values

Ed25519 public key

# sodium_crypto_sign_publickey_from_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key

### Description

sodium_crypto_sign_publickey_from_secretkey(#[\SensitiveParameter] string `$secret_key`): string

Extract the Ed25519 public key from the secret key

### Parameters

`secret_key`
  Ed25519 secret key

### Return Values

Ed25519 public key

# sodium_crypto_sign_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair

### Description

sodium_crypto_sign_secretkey(#[\SensitiveParameter] string `$key_pair`): string

Extract the Ed25519 secret key from a keypair

### Parameters

`key_pair`
  Ed25519 keypair (see: sodium_crypto_sign_keypair())

### Return Values

Ed25519 secret key

# sodium_crypto_sign_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key

### Description

sodium_crypto_sign_seed_keypair(#[\SensitiveParameter] string `$seed`): string

Clamps the seed to form a secret key, derives the public key, and returns the two as a keypair.

The `*_seed_keypair` functions are ideal for generating a keypair from a password and salt. Use the result as a `seed` to generate the desired keys.

### Parameters

`seed`
  Some cryptographic input. Must be 32 bytes.

### Return Values

Keypair (secret key and public key)

# sodium_crypto_sign_verify_detached

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_verify_detached — Verify signature for the message

### Description

sodium_crypto_sign_verify_detached(string `$signature`, string `$message`, string `$public_key`): bool

Verify signature for the message

### Parameters

`signature`
  The cryptographic signature obtained from sodium_crypto_sign_detached()
`message`
  The message being verified
`public_key`
  Ed25519 public key

### Return Values

Returns `true` on success or `false` on failure.

# sodium_crypto_stream

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed

### Description

sodium_crypto_stream(int `$length`, string `$nonce`, #[\SensitiveParameter] string `$key`): string

Generate a deterministic sequence of bytes from a seed, using the XSalsa20 stream cipher.

### Parameters

`length`
  The number of bytes to return.
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

String of pseudorandom bytes.

# sodium_crypto_stream_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.

### Description

sodium_crypto_stream_keygen(): string

Generate a key for use with sodium_crypto_stream() and sodium_crypto_stream_xor().

### Parameters

This function has no parameters.

### Return Values

Encryption key (256-bit).

# sodium_crypto_stream_xchacha20

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes

### Description

sodium_crypto_stream_xchacha20(int `$length`, string `$nonce`, #[\SensitiveParameter] string `$key`): string

Expands the `key` and `nonce` into a keystream of pseudorandom bytes.

### Parameters

`length`
  Number of bytes desired.
`nonce`
  24-byte nonce.
`key`
  Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

### Return Values

Returns a pseudorandom stream that can be used with sodium_crypto_stream_xchacha20_xor().

# sodium_crypto_stream_xchacha20_keygen

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20_keygen — Returns a secure random key

### Description

sodium_crypto_stream_xchacha20_keygen(): string

Returns a secure random key for use with sodium_crypto_stream_xchacha20().

### Parameters

This function has no parameters.

### Return Values

Returns a 32-byte secure random key for use with sodium_crypto_stream_xchacha20().

# sodium_crypto_stream_xchacha20_xor

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)

### Description

sodium_crypto_stream_xchacha20_xor(#[\SensitiveParameter] string `$message`, string `$nonce`, #[\SensitiveParameter] string `$key`): string

Encrypts a `message` using a `nonce` and a secret `key` (no authentication).

Caution

This encryption is unauthenticated, and does not prevent chosen-ciphertext attacks. Make sure to combine the ciphertext with a Message Authentication Code, for example with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() function, or sodium_crypto_auth().

### Parameters

`message`
  The message to encrypt.
`nonce`
  24-byte nonce.
`key`
  Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

### Return Values

Encrypted message.

### See Also

- sodium_crypto_stream_xchacha20_xor_ic() - Encrypts a message using a nonce and a secret key (no authentication)

# sodium_crypto_stream_xchacha20_xor_ic

(PHP 8 >= 8.2.0)

sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)

### Description

sodium_crypto_stream_xchacha20_xor_ic(
#[\SensitiveParameter] string `$message`,
string `$nonce`,
int `$counter`,
#[\SensitiveParameter] string `$key`
): string

The function is similar to sodium_crypto_stream_xchacha20_xor() but adds the ability to set the initial value of the block counter to a non-zero value. This permits direct access to any block without having to compute the previous ones.

Caution

This encryption is unauthenticated, and does not prevent chosen-ciphertext attacks. Make sure to combine the ciphertext with a Message Authentication Code, for example with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() function, or sodium_crypto_auth().

### Parameters

`message`
  The message to encrypt.
`nonce`
  24-byte nonce.
`counter`
  The initial value of the block counter.
`key`
  Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

### Return Values

Encrypted message, or `false` on failure.

### Examples

Example #1 sodium_crypto_stream_xchacha20_xor_ic() example

`<?php
$n2 = random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES);
$left = str_repeat("\x01", 64);
$right = str_repeat("\xfe", 64);
// All at once:
$stream7_unified = sodium_crypto_stream_xchacha20_xor($left . $right, $n2, $key);
// Piecewise, with initial counter:
$stream7_left = sodium_crypto_stream_xchacha20_xor_ic($left, $n2, 0, $key);
$stream7_right = sodium_crypto_stream_xchacha20_xor_ic($right, $n2, 1, $key);
$stream7_concat = $stream7_left . $stream7_right;
var_dump(strlen($stream7_concat));
var_dump($stream7_unified === $stream7_concat);
?>`

The above example will output something similar to:

    int(128)
    bool(true)

### See Also

- sodium_crypto_stream_xchacha20_xor() - Encrypts a message using a nonce and a secret key (no authentication)

# sodium_crypto_stream_xor

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream_xor — Encrypt a message without authentication

### Description

sodium_crypto_stream_xor(#[\SensitiveParameter] string `$message`, string `$nonce`, #[\SensitiveParameter] string `$key`): string

This function encrypts a message with XSalsa20, but does not provide any ciphertext guarantees about the plaintext.

### Parameters

`message`
  The message to encrypt
`nonce`
  A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).
`key`
  Encryption key (256-bit).

### Return Values

Encrypted message.

# sodium_hex2bin

(PHP 7 >= 7.2.0, PHP 8)

sodium_hex2bin — Decodes a hexadecimally encoded binary string

### Description

sodium_hex2bin(#[\SensitiveParameter] string `$string`, string `$ignore` = ""): string

Decodes a hexadecimally encoded binary string.

Like sodium_bin2hex(), sodium_hex2bin() is resistant to side-channel attacks while hex2bin() is not.

### Parameters

`string`
  Hexadecimal representation of data.
`ignore`
  Optional string argument for characters to ignore.

### Return Values

Returns the binary representation of the given `string` data.

# sodium_increment

(PHP 7 >= 7.2.0, PHP 8)

sodium_increment — Increment large number

### Description

sodium_increment(string `&$string`): void

Treat the string as a little-endian unsigned integer, then increase it by 1. Constant-time.

### Parameters

`string`
  String to increment.

### Return Values

No value is returned.

# sodium_memcmp

(PHP 7 >= 7.2.0, PHP 8)

sodium_memcmp — Test for equality in constant-time

### Description

sodium_memcmp(#[\SensitiveParameter] string `$string1`, #[\SensitiveParameter] string `$string2`): int

Compare two strings in constant-time.

In practice, you almost always want to use hash_equals() instead, since it provides the same logic but returns a bool instead of an int. However, if you're using the return value of a comparison in a calculation that's timing-sensitive, and worried about timing leaks with bool-to-int conversions, sodium_memcmp() is an ideal replacement.

### Parameters

`string1`
  String to compare
`string2`
  Other string to compare

### Return Values

Returns `0` if both strings are equal; `-1` otherwise.

# sodium_memzero

(PHP 7 >= 7.2.0, PHP 8)

sodium_memzero — Overwrite a string with NUL characters

### Description

sodium_memzero(#[\SensitiveParameter] string `&$string`): void

sodium_memzero() zeroes out the string that is passed by reference.

### Parameters

`string`
  String.

### Return Values

No value is returned.

# sodium_pad

(PHP 7 >= 7.2.0, PHP 8)

sodium_pad — Add padding data

### Description

sodium_pad(#[\SensitiveParameter] string `$string`, int `$block_size`): string

Right-pad a string to a desired length. Timing-safe.

### Parameters

`string`
  Unpadded string.
`block_size`
  The string will be padded until it is an even multiple of the block size.

### Return Values

Padded string.

# sodium_unpad

(PHP 7 >= 7.2.0, PHP 8)

sodium_unpad — Remove padding data

### Description

sodium_unpad(#[\SensitiveParameter] string `$string`, int `$block_size`): string

Unpad a padded string. Timing-safe.

### Parameters

`string`
  Padded string.
`block_size`
  The block size for padding.

### Return Values

Unpadded string.

## Table of Contents

- sodium_add — Add large numbers
- sodium_base642bin — Decodes a base64-encoded string into raw binary.
- sodium_bin2base64 — Encodes a raw binary string with base64.
- sodium_bin2hex — Encode to hexadecimal
- sodium_compare — Compare large numbers
- sodium_crypto_aead_aegis128l_decrypt — Verify then decrypt a message with AEGIS-128L
- sodium_crypto_aead_aegis128l_encrypt — Encrypt then authenticate a message with AEGIS-128L
- sodium_crypto_aead_aegis128l_keygen — Generate a random AEGIS-128L key
- sodium_crypto_aead_aegis256_decrypt — Verify then decrypt a message with AEGIS-256
- sodium_crypto_aead_aegis256_encrypt — Encrypt then authenticate a message with AEGIS-256
- sodium_crypto_aead_aegis256_keygen — Generate a random AEGIS-256 key
- sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM
- sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM
- sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
- sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key
- sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305
- sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305
- sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag
- sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message
- sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.
- sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.
- sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305
- sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
- sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.
- sodium_crypto_auth — Compute a tag for the message
- sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth
- sodium_crypto_auth_verify — Verifies that the tag is valid for the message
- sodium_crypto_box — Authenticated public-key encryption
- sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
- sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key
- sodium_crypto_box_open — Authenticated public-key decryption
- sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair
- sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key
- sodium_crypto_box_seal — Anonymous public-key encryption
- sodium_crypto_box_seal_open — Anonymous public-key decryption
- sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair
- sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
- sodium_crypto_core_ristretto255_add — Adds an element
- sodium_crypto_core_ristretto255_from_hash — Maps a vector
- sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve
- sodium_crypto_core_ristretto255_random — Generates a random key
- sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value
- sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose
- sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value
- sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value
- sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value
- sodium_crypto_core_ristretto255_scalar_random — Generates a random key
- sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value
- sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value
- sodium_crypto_core_ristretto255_sub — Subtracts an element
- sodium_crypto_generichash — Get a hash of the message
- sodium_crypto_generichash_final — Complete the hash
- sodium_crypto_generichash_init — Initialize a hash for streaming
- sodium_crypto_generichash_keygen — Generate a random generichash key
- sodium_crypto_generichash_update — Add message to a hash
- sodium_crypto_kdf_derive_from_key — Derive a subkey
- sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface
- sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.
- sodium_crypto_kx_keypair — Creates a new sodium keypair
- sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair
- sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.
- sodium_crypto_kx_seed_keypair — Description
- sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.
- sodium_crypto_pwhash — Derive a key from a password, using Argon2
- sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt
- sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
- sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
- sodium_crypto_pwhash_str — Get an ASCII-encoded hash
- sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password
- sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
- sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
- sodium_crypto_scalarmult_base — Alias of sodium_crypto_box_publickey_from_secretkey
- sodium_crypto_scalarmult_ristretto255 — Computes a shared secret
- sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key
- sodium_crypto_secretbox — Authenticated shared-key encryption
- sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox
- sodium_crypto_secretbox_open — Authenticated shared-key decryption
- sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption
- sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption
- sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.
- sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream
- sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API
- sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state
- sodium_crypto_shorthash — Compute a short hash of a message and key
- sodium_crypto_shorthash_keygen — Get random bytes for key
- sodium_crypto_sign — Sign a message
- sodium_crypto_sign_detached — Sign the message
- sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key
- sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key
- sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
- sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together
- sodium_crypto_sign_open — Check that the signed message has a valid signature
- sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair
- sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key
- sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair
- sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key
- sodium_crypto_sign_verify_detached — Verify signature for the message
- sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
- sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.
- sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes
- sodium_crypto_stream_xchacha20_keygen — Returns a secure random key
- sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)
- sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)
- sodium_crypto_stream_xor — Encrypt a message without authentication
- sodium_hex2bin — Decodes a hexadecimally encoded binary string
- sodium_increment — Increment large number
- sodium_memcmp — Test for equality in constant-time
- sodium_memzero — Overwrite a string with NUL characters
- sodium_pad — Add padding data
- sodium_unpad — Remove padding data

# The SodiumException class

(PHP 7 >= 7.2.0, PHP 8)

## Introduction

Exceptions thrown by the sodium functions.

## Class synopsis

class SodiumException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Sodium Functions
  - sodium_add — Add large numbers
  - sodium_base642bin — Decodes a base64-encoded string into raw binary.
  - sodium_bin2base64 — Encodes a raw binary string with base64.
  - sodium_bin2hex — Encode to hexadecimal
  - sodium_compare — Compare large numbers
  - sodium_crypto_aead_aegis128l_decrypt — Verify then decrypt a message with AEGIS-128L
  - sodium_crypto_aead_aegis128l_encrypt — Encrypt then authenticate a message with AEGIS-128L
  - sodium_crypto_aead_aegis128l_keygen — Generate a random AEGIS-128L key
  - sodium_crypto_aead_aegis256_decrypt — Verify then decrypt a message with AEGIS-256
  - sodium_crypto_aead_aegis256_encrypt — Encrypt then authenticate a message with AEGIS-256
  - sodium_crypto_aead_aegis256_keygen — Generate a random AEGIS-256 key
  - sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM
  - sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM
  - sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
  - sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key
  - sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305
  - sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305
  - sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag
  - sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message
  - sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.
  - sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.
  - sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305
  - sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
  - sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.
  - sodium_crypto_auth — Compute a tag for the message
  - sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth
  - sodium_crypto_auth_verify — Verifies that the tag is valid for the message
  - sodium_crypto_box — Authenticated public-key encryption
  - sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
  - sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key
  - sodium_crypto_box_open — Authenticated public-key decryption
  - sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair
  - sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key
  - sodium_crypto_box_seal — Anonymous public-key encryption
  - sodium_crypto_box_seal_open — Anonymous public-key decryption
  - sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair
  - sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
  - sodium_crypto_core_ristretto255_add — Adds an element
  - sodium_crypto_core_ristretto255_from_hash — Maps a vector
  - sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve
  - sodium_crypto_core_ristretto255_random — Generates a random key
  - sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value
  - sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose
  - sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value
  - sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value
  - sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value
  - sodium_crypto_core_ristretto255_scalar_random — Generates a random key
  - sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value
  - sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value
  - sodium_crypto_core_ristretto255_sub — Subtracts an element
  - sodium_crypto_generichash — Get a hash of the message
  - sodium_crypto_generichash_final — Complete the hash
  - sodium_crypto_generichash_init — Initialize a hash for streaming
  - sodium_crypto_generichash_keygen — Generate a random generichash key
  - sodium_crypto_generichash_update — Add message to a hash
  - sodium_crypto_kdf_derive_from_key — Derive a subkey
  - sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface
  - sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.
  - sodium_crypto_kx_keypair — Creates a new sodium keypair
  - sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair
  - sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.
  - sodium_crypto_kx_seed_keypair — Description
  - sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.
  - sodium_crypto_pwhash — Derive a key from a password, using Argon2
  - sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt
  - sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
  - sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
  - sodium_crypto_pwhash_str — Get an ASCII-encoded hash
  - sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password
  - sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
  - sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
  - sodium_crypto_scalarmult_base — Alias of sodium_crypto_box_publickey_from_secretkey
  - sodium_crypto_scalarmult_ristretto255 — Computes a shared secret
  - sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key
  - sodium_crypto_secretbox — Authenticated shared-key encryption
  - sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox
  - sodium_crypto_secretbox_open — Authenticated shared-key decryption
  - sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption
  - sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption
  - sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.
  - sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream
  - sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API
  - sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state
  - sodium_crypto_shorthash — Compute a short hash of a message and key
  - sodium_crypto_shorthash_keygen — Get random bytes for key
  - sodium_crypto_sign — Sign a message
  - sodium_crypto_sign_detached — Sign the message
  - sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key
  - sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key
  - sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
  - sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together
  - sodium_crypto_sign_open — Check that the signed message has a valid signature
  - sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair
  - sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key
  - sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair
  - sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key
  - sodium_crypto_sign_verify_detached — Verify signature for the message
  - sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
  - sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.
  - sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes
  - sodium_crypto_stream_xchacha20_keygen — Returns a secure random key
  - sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)
  - sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)
  - sodium_crypto_stream_xor — Encrypt a message without authentication
  - sodium_hex2bin — Decodes a hexadecimally encoded binary string
  - sodium_increment — Increment large number
  - sodium_memcmp — Test for equality in constant-time
  - sodium_memzero — Overwrite a string with NUL characters
  - sodium_pad — Add padding data
  - sodium_unpad — Remove padding data
- SodiumException — The SodiumException class

# Xpass

# Introduction

This extension provides password hashing algorithms used by Linux distributions, using extended crypt library.

It also provides additional functions from libxcrypt missing in core PHP.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation via PECL

## Requirements

This extension requires » libxcrypt version 4.4 or higher.

## Installation via PECL

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: » https://pecl.php.net/package/xpass.

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

Xpass extension provides various set of constants. Hash methods (`CRYPT_PREFIX_*`) for crypt_gensalt() prefix parameter. Error codes (`CRYPT_SALT_*`) returned by crypt_checksalt(). Password algorithms (`PASSWORD_*`) for password_hash() algo parameter.

Hashing methods
`CRYPT_PREFIX_STD_DES` (string)
  The original hashing method from Unix V7, based on the DES block cipher. Because DES is cheap on modern hardware, because there are only `4096` possible salts and 2**56 distinct passphrases, which it truncates to 8 characters, it is feasible to discover any passphrase hashed with this method. It should only be used when supporting old operating systems that support no other hash generation algorithm, due to how weak DES hashes are.
`CRYPT_PREFIX_EXT_DES` (string)
  An extension of traditional DES, which eliminates the length limit, increases the salt size, and makes the time cost tunable. It originates with BSDI BSD/OS and is also available on at least NetBSD, OpenBSD, and FreeBSD due to the use of David Burren's FreeSec library. It is much better than traditional DES and bigcrypt, but still should not be used for new hashes.
`CRYPT_PREFIX_MD5` (string)
  A hash based on the MD5 algorithm, originally developed by Poul-Henning Kamp for FreeBSD. Supported on most free Unixes and newer versions of Solaris. Not as weak as the DES-based hashes below, but MD5 is so cheap on modern hardware that it should not be used for new hashes. Processing cost is not adjustable.
`CRYPT_PREFIX_BLOWFISH` (string)
  A hash based on the Blowfish block cipher, modified to have an extra-expensive key schedule. Originally developed by Niels Provos and David Mazieres for OpenBSD and also supported on recent versions of FreeBSD and NetBSD, on Solaris 10 and newer, and on several GNU/*/Linux distributions.
`CRYPT_PREFIX_SHA256` (string)
  A hash based on SHA-2 with 256-bit output, originally developed by Ulrich Drepper for GNU libc. Supported on Linux but not common elsewhere. Acceptable for new hashes. The default processing cost parameter is `5000`, which is too low for modern hardware.
`CRYPT_PREFIX_SHA512` (string)
  A hash based on SHA-2 with 512-bit output, originally developed by Ulrich Drepper for GNU libc. Supported on Linux but not common elsewhere. Acceptable for new hashes. The default processing cost parameter is `5000`, which is too low for modern hardware.
`CRYPT_PREFIX_SCRYPT` (string)
  Scrypt is a password-based key derivation function created by Colin Percival, originally for the Tarsnap online backup service. The algorithm was specifically designed to make it costly to perform large-scale custom hardware attacks by requiring large amounts of memory. In 2016, the scrypt algorithm was published by IETF as RFC 7914.
`CRYPT_PREFIX_GOST_YESCRYPT` (string)
  Gost-yescrypt uses the output from yescrypt as an input message to HMAC with the GOST R 34.11-2012 (Streebog) hash function with a 256-bit digest. Thus, yescrypt's cryptographic properties are superseded by those of the GOST hash function. This hashing method is useful in applications that need modern passphrase hashing, but have to rely on GOST algorithms. The GOST R 34.11-2012 (Streebog) hash function has been published by the IETF as RFC 6986. Acceptable for new hashes where required.
`CRYPT_PREFIX_YESCRYPT` (string)
  Yescrypt is a scalable passphrase hashing scheme designed by Solar Designer, which is based on Colin Percival's scrypt. While yescrypt's strength against password guessing attacks comes from its algorithm design, its cryptographic security is guaranteed by its use of SHA-256 on the outer layer. The SHA-256 hash function has been published by NIST in FIPS PUB 180-2 (and its subsequent revisions such as FIPS PUB 180-4) and by the IETF as RFC 4634 (and subsequently RFC 6234). Recommended for new hashes.
`CRYPT_PREFIX_SM3CRYPT` (string)
  A hash based on the ShangMi 3 hash function with 256-bit output, that uses the same design as sha256crypt and/or sha512crypt. Supported on EulerOS, Kylin, openEuler, and openKylin, but not common elsewhere. Acceptable for new hashes where required. The default processing cost parameter is 5000, which is too low for modern hardware. Available as of 1.2.0 with libcxcrypt >= 4.5.0.
`CRYPT_PREFIX_SM3_YESCRYPT` (string)
  Sm3-yescrypt uses the output from yescrypt as an input message to HMAC with the ShangMi 3 hash function with a 256-bit digest. Thus, yescrypt's cryptographic properties are superseded by those of the ShangMi 3 hash function. This hashing method is useful in applications that need modern passphrase hashing, but have to rely on algorithms approved by the Chinese Office of State Commercial Cryptography Administration (OSCCA). The ShangMi 3 hash function has been published in Part 3: "Dedicated hash-functions" of the ISO/IEC 10118-3:2018. Acceptable for new hashes where required. Available as of 1.2.0 with libcxcrypt >= 4.5.0.

Error codes
`CRYPT_SALT_OK` (int)
  No error.
`CRYPT_SALT_INVALID` (int)
  Unknown hashing method or invalid parameters.
`CRYPT_SALT_METHOD_DISABLED` (int)
  Hashing method is no longer allowed to be used.
`CRYPT_SALT_METHOD_LEGACY` (int)
  Hashing method is no longer considered strong enough.
`CRYPT_SALT_TOO_CHEAP` (int)
  Cost parameters are considered too cheap.

Password algorithms
`PASSWORD_SHA512` (string)
  `PASSWORD_SHA512` is used to create new password hashes using the `CRYPT_PREFIX_SHA512` algorithm.
`PASSWORD_YESCRYPT` (string)
  `PASSWORD_YESCRYPT` is used to create new password hashes using the `CRYPT_PREFIX_YESCRYPT` algorithm.
`PASSWORD_SM3CRYPT` (string)
  `PASSWORD_SM3CRYPT` is used to create new password hashes using the `CRYPT_PREFIX_SM3CRYPT` algorithm. Available as of 1.2.0 with libcxcrypt >= 4.5.0.
`PASSWORD_SM3_YESCRYPT` (string)
  `PASSWORD_SM3_YESCRYPT` is used to create new password hashes using the `CRYPT_PREFIX_SM3_YESCRYPT` algorithm. Available as of 1.2.0 with libcxcrypt >= 4.5.0.

# Xpass Functions

# crypt_checksalt

(PECL xpass >= 1.1.0)

crypt_checksalt — Validate a crypt setting string

### Description

crypt_checksalt(string `$salt`): ?string

Checks the salt string against the system configuration and reports whether the hashing method and parameters it specifies are acceptable. It is intended to be used to determine whether the user's passphrase should be re-hashed using the currently preferred hashing method.

### Parameters

`salt`
  Salt string to check.

### Return Values

Returns one of the `CRYPT_SALT_*` as an int.

### Examples

Example #1 A crypt_checksalt() example

`<?php
// Generate a salt for a legacy method
$salt = crypt_gensalt(CRYPT_PREFIX_STD_DES);
// Check the salt
$test = crypt_checksalt($salt);
var_dump($test === CRYPT_SALT_METHOD_LEGACY);
// Generate a salt for default method
$salt = crypt_gensalt();
// Check the salt
$test = crypt_checksalt($salt);
var_dump($test === CRYPT_SALT_OK);
?>`

The above example will output:

    bool(true)
    bool(true)

### See Also

- crypt_gensalt() - Compile a string for use as the salt argument to crypt

# crypt_gensalt

(PECL xpass >= 1.1.0)

crypt_gensalt — Compile a string for use as the salt argument to crypt

### Description

crypt_gensalt(string `$prefix` = `null`, int `$count` = 0): ?string

Compile a string for use as the salt argument to crypt().

### Parameters

`prefix`
  Hashing method. One of the `CRYPT_PREFIX_*` constant. If `null`, the best available hashing method will be selected.
`count`
  Controls the processing cost of the hash; the valid range and exact meaning of count depend on the hashing method, but larger numbers correspond to more costly hashes in terms of CPU time and possibly memory usage. If count is `0`, a low default cost will be selected.

### Return Values

Returns a string with the setting, or `null` in case of an error.

### Examples

Example #1 A crypt_gensalt() example

`<?php
// Generate the salt
$salt = crypt_gensalt(CRYPT_PREFIX_BLOWFISH);
// Hash the password
$hash = crypt("secret", $salt);
// Check the hash
$test = hash_equals(crypt("secret", $hash), $hash);
var_dump($salt, $hash, $test);
?>`

The above example will output:

    string(29) "$2y$05$GcPykP.Am8C1.dGamdpwW."
    string(60) "$2y$05$GcPykP.Am8C1.dGamdpwW.1RR.7uicWvJPZfJfCEizZHqVWwuaJLm"
    bool(true)

### See Also

- crypt_preferred_method() - Get the prefix of the preferred hash method
- crypt() - One-way string hashing
- hash_equals() - Timing attack safe string comparison

# crypt_preferred_method

(PECL xpass >= 1.1.0)

crypt_preferred_method — Get the prefix of the preferred hash method

### Description

crypt_preferred_method(): ?string

Get the prefix of the preferred hash method.

### Parameters

This function has no parameters.

### Return Values

Returns a string with the prefix, or `null` in case of an error.

### Examples

Example #1 A crypt_preferred_method() example

`<?php
var_dump(crypt_preferred_method());
?>`

The above example will output:

    string(3) "$y$"

### See Also

- crypt_gensalt() - Compile a string for use as the salt argument to crypt

## Table of Contents

- crypt_checksalt — Validate a crypt setting string
- crypt_gensalt — Compile a string for use as the salt argument to crypt
- crypt_preferred_method — Get the prefix of the preferred hash method

- Installing/Configuring
  - Requirements
  - Installation via PECL
- Predefined Constants
- Xpass Functions
  - crypt_checksalt — Validate a crypt setting string
  - crypt_gensalt — Compile a string for use as the salt argument to crypt
  - crypt_preferred_method — Get the prefix of the preferred hash method

- Hash — HASH Message Digest Framework
  - Installing/Configuring
  - Predefined Constants
  - HashContext — The HashContext class
  - Hash Functions
- Mcrypt
  - Installing/Configuring
  - Predefined Constants
  - Mcrypt ciphers
  - Mcrypt Functions
- Mhash
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Mhash Functions
- OpenSSL
  - Installing/Configuring
  - Predefined Constants
  - Key/Certificate parameters
  - Certificate Verification
  - OpenSSL Functions
  - OpenSSLCertificate — The OpenSSLCertificate class
  - OpenSSLCertificateSigningRequest — The OpenSSLCertificateSigningRequest class
  - OpenSSLAsymmetricKey — The OpenSSLAsymmetricKey class
- Password Hashing
  - Installing/Configuring
  - Predefined Constants
  - Password Hashing Functions
- Rnp
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Rnp Functions
  - RnpFFI — The RnpFFI class
- Sodium
  - Installing/Configuring
  - Predefined Constants
  - Sodium Functions
  - SodiumException — The SodiumException class
- Xpass
  - Installing/Configuring
  - Predefined Constants
  - Xpass Functions

# Database Extensions

# Abstraction Layers

# Database (dbm-style) Abstraction Layer

# Introduction

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as » Oracle Berkeley DB.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

List of DBA handlers
Handler | Notes
--- | ---
`dbm` | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
`ndbm` | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
`gdbm` | Gdbm is the » GNU database manager.
`db2` | DB2 is for » Oracle Berkeley DB 2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications."
`db3` | DB3 is for » Oracle Berkeley DB 3.
`db4` | DB4 is for » Oracle Berkeley DB 4 or 5. This option can be used with BDB 5 as of PHP 5.3.3.
`cdb` | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at » http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. We support writing (not updating) through the internal cdb library.
`cdb_make` | We support creation (not updating) of cdb files when the bundled cdb library is used.
`flatfile` | This is available for compatibility with the deprecated `dbm` extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
`inifile` | This is available to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is the function dba_key_split() which allows to convert the string keys into array keys without loosing `false`.
`qdbm` | The qdbm library can be downloaded from » http://fallabs.com/qdbm/index.html.
`tcadb` | The Tokyo Cabinet library can be downloaded from » http://fallabs.com/tokyocabinet/.
`lmdb` | This is available since PHP 7.2.0. The Lightning Memory-Mapped Database library can be downloaded from » https://symas.com/lmdb/.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

## Installation

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX or --enable-XXXX configure switch to your PHP configure line.

Warning

After configuring and compiling PHP you must execute the following test from commandline: `php run-tests.php ext/dba`. This shows whether your combination of handlers works. Most problematic are `dbm` and `ndbm` which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfunctioning single handlers but not combinations.

Supported DBA handlers
Handler | Configure Switch
--- | ---
`dbm` | To enable support for dbm add --with-dbm[=DIR]. Note: dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.
`ndbm` | To enable support for ndbm add --with-ndbm[=DIR]. Note: ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.
`gdbm` | To enable support for gdbm add --with-gdbm[=DIR].
`db2` | To enable support for Oracle Berkeley DB 2 add --with-db2[=DIR]. Note: db2 conflicts with db3 and db4.
`db3` | To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR]. Note: db3 conflicts with db2 and db4.
`db4` | To enable support for Oracle Berkeley DB 4 or 5 add --with-db4[=DIR]. Note: db4 conflicts with db2 and db3. Note: The db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version. Support for BDB 5 was added in PHP 5.3.3.
`cdb` | To enable support for cdb add --with-cdb[=DIR]. Note: You can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.
`flatfile` | To enable support for flatfile add --enable-flatfile. Before PHP 5.2.1 the --with-flatfile had to be used instead. Note: This was added to add compatibility with deprecated `dbm` extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.
`inifile` | To enable support for `inifile` add --enable-inifile. Before PHP 5.2.1 the --with-inifile had to be used instead. Note: This was added to allow to read and set microsoft style .ini files (like the php.ini file).
`qdbm` | To enable support for qdbm add --with-qdbm[=DIR]. Note: qdbm conflicts with dbm and gdbm. Note: The qdbm library can be downloaded from » http://fallabs.com/qdbm/index.html.
`tcadb` | To enable support for Tokyo Cabinet add --with-tcadb[=DIR]. Note: The Tokyo Cabinet library can be downloaded from » http://fallabs.com/tokyocabinet/.
`lmdb` | To enable support for the Lightning Memory-Mapped Database add --with-lmdb[=DIR]. Note: This was added in PHP 7.2.0. The Lightning Memory-Mapped Database library can be downloaded from » https://symas.com/lmdb/.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

DBA Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
dba.default_handler | DBA_DEFAULT | `INI_ALL` |

Here's a short explanation of the configuration directives.

`dba.default_handler` string
  The name of the default handler

## Resource Types

Prior to PHP 8.4.0, most DBA functions operate on or return resources (e.g. dba_open() returns a positive DBA link identifier required by most DBA functions).

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

`DBA_LMDB_USE_SUB_DIR` (int)
  LMDB Driver flag to allow the creation of a subdirectory for the database files. Available as of PHP 8.2.0.
`DBA_LMDB_NO_SUB_DIR` (int)
  LMDB Driver flag to disallow the creation of a subdirectory for the database files. Available as of PHP 8.2.0.

# Examples

## Table of Contents

- Basic usage

## Basic usage

Example #1 DBA example

`<?php
$id = dba_open("/tmp/test.db", "n", "db2");
if (!$id) {
echo "dba_open failed\n";
exit;
}
dba_replace("key", "This is an example!", $id);
if (dba_exists("key", $id)) {
echo dba_fetch("key", $id);
dba_delete("key", $id);
}
dba_close($id);
?>`

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Example #2 Traversing a database

`<?php
// ...open database...
$key = dba_firstkey($id);
while ($key !== false) {
if (true) { // remember the key to perform some action later
$handle_later[] = $key;
}
$key = dba_nextkey($id);
}
foreach ($handle_later as $val) {
dba_delete($val, $id);
}
?>`

# The Dba\Connection class

(PHP 8 >= 8.4.0)

## Introduction

A fully opaque class which replaces a `dba` resource as of PHP 8.4.0.

## Class synopsis

namespace Dba;
final class Connection {
}

# DBA Functions

# dba_close

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_close — Close a DBA database

### Description

dba_close(Dba\Connection `$dba`): void

dba_close() closes the established database and frees all resources of the specified database handle.

### Parameters

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_open() - Open database
- dba_popen() - Open database persistently

# dba_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_delete — Delete DBA entry specified by key

### Description

dba_delete(string|array `$key`, Dba\Connection `$dba`): bool

dba_delete() deletes the specified entry from the database.

### Parameters

`key`
  The key of the entry which is deleted.
`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_exists() - Check whether key exists
- dba_fetch() - Fetch data specified by key
- dba_insert() - Insert entry
- dba_replace() - Replace or insert entry

# dba_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_exists — Check whether key exists

### Description

dba_exists(string|array `$key`, Dba\Connection `$dba`): bool

dba_exists() checks whether the specified `key` exists in the database.

### Parameters

`key`
  The key the check is performed for.
`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` if the key exists, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_delete() - Delete DBA entry specified by key
- dba_fetch() - Fetch data specified by key
- dba_insert() - Insert entry
- dba_replace() - Replace or insert entry

# dba_fetch

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_fetch — Fetch data specified by key

### Description

dba_fetch(string|array `$key`, Dba\Connection `$dba`, int `$skip` = 0): string|false

Overloaded signature deprecated as of 8.3.0:

dba_fetch(string|array `$key`, int `$skip`, resource `$dba`): string

dba_fetch() fetches the data specified by `key` from the database specified with `dba`.

### Parameters

`key`
  The key the data is specified by.

  > Note: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().
`skip`
  The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

### Return Values

Returns the associated string if the key/data pair is found, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.
8.3.0 | Calling dba_fetch() with `dba` as the 3rd argument is now deprecated.
8.2.0 | dba_fetch()'s optional skip argument is now at the end in line with PHP userland semantics. The previously overloaded signature is still accepted but discouraged.

### See Also

- dba_exists() - Check whether key exists
- dba_delete() - Delete DBA entry specified by key
- dba_insert() - Insert entry
- dba_replace() - Replace or insert entry
- dba_key_split() - Splits a key in string representation into array representation

# dba_firstkey

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_firstkey — Fetch first key

### Description

dba_firstkey(Dba\Connection `$dba`): string|false

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

### Parameters

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns the key on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_nextkey() - Fetch next key
- dba_key_split() - Splits a key in string representation into array representation
- Example 2 in the DBA examples

# dba_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

dba_handlers — List all the handlers available

### Description

dba_handlers(bool `$full_info` = `false`): array

dba_handlers() list all the handlers supported by this extension.

### Parameters

`full_info`
  Turns on/off full information display in the result.

### Return Values

Returns an array of database handlers. If `full_info` is set to `true`, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

> Note: When the internal cdb library is used you will see `cdb` and `cdb_make`.

### Examples

Example #1 dba_handlers() Example

`<?php
echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
// clean the versions
$handler_version = str_replace('$', '', $handler_version);
echo " - $handler_name: $handler_version\n";
}
?>`

The above example will output something similar to:

    Available DBA handlers:
     - cdb: 0.75, Revision: 1.3.2.3
     - cdb_make: 0.75, Revision: 1.2.2.4
     - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
     - inifile: 1.0, Revision: 1.6.2.3
     - flatfile: 1.0, Revision: 1.5.2.4

# dba_insert

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_insert — Insert entry

### Description

dba_insert(string|array `$key`, string `$value`, Dba\Connection `$dba`): bool

dba_insert() inserts the entry described with `key` and `value` into the database.

### Parameters

`key`
  The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.
`value`
  The value to be inserted.
`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_exists() - Check whether key exists
- dba_delete() - Delete DBA entry specified by key
- dba_fetch() - Fetch data specified by key
- dba_replace() - Replace or insert entry

# dba_key_split

(PHP 5, PHP 7, PHP 8)

dba_key_split — Splits a key in string representation into array representation

### Description

dba_key_split(string|false|null `$key`): array|false

dba_key_split() splits a key (string representation) into an array representation.

### Parameters

`key`
  The key in string representation.

### Return Values

Returns an array of the form `array(0 => group, 1 => value_name)`. This function will return `false` if `key` is `null` or `false`.

### Changelog

Version | Description
--- | ---
8.4.0 | Passing `null` or `false` to `key` is now deprecated.

### See Also

- dba_firstkey() - Fetch first key
- dba_nextkey() - Fetch next key
- dba_fetch() - Fetch data specified by key

# dba_list

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

dba_list — List all open database files

### Description

dba_list(): array

dba_list() list all open database files.

### Parameters

This function has no parameters.

### Return Values

An associative array, in the form `resourceid => filename`.

# dba_nextkey

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_nextkey — Fetch next key

### Description

dba_nextkey(Dba\Connection `$dba`): string|false

dba_nextkey() returns the next key of the database and advances the internal key pointer.

### Parameters

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns the key on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_firstkey() - Fetch first key
- dba_key_split() - Splits a key in string representation into array representation
- Example 2 in the DBA examples

# dba_open

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_open — Open database

### Description

dba_open(
string `$path`,
string `$mode`,
?string `$handler` = `null`,
int `$permission` = 0644,
int `$map_size` = 0,
?int `$flags` = `null`
): Dba\Connection|false

dba_open() establishes a database instance for `path` with `mode` using `handler`.

### Parameters

`path`
  Commonly a regular path in your filesystem.
`mode`
  It is `r` for read access, `w` for read/write access to an already existing database, `c` for read/write access and database creation if it doesn't currently exist, and `n` for create, truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue) are not supported. Additionally you can set the database lock method with the next char. Use `l` to lock the database with a .lck file or `d` to lock the databasefile itself. It is important that all of your applications do this consistently. If you want to test the access and do not want to wait for the lock you can add `t` as third character. When you are absolutely sure that you do not require database locking you can do so by using `-` instead of `l` or `d`. When none of `d`, `l` or `-` is used, dba will lock on the database file as it would with `d`.

  > Note:

  > There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

  > DBA locking
  > already open | `mode` = "rl" | `mode` = "rlt" | `mode` = "wl" | `mode` = "wlt" | `mode` = "rd" | `mode` = "rdt" | `mode` = "wd" | `mode` = "wdt"
  > --- | --- | --- | --- | --- | --- | --- | --- | ---
  > not open | ok | ok | ok | ok | ok | ok | ok | ok
  > `mode` = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
  > `mode` = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
  > `mode` = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
  > `mode` = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false

  > - ok: the second call will be successful.
  > - wait: the second call waits until dba_close() is called for the first.
  > - false: the second call returns false.
  > - illegal: you must not mix `"l"` and `"d"` modifiers for `mode` parameter.

`handler`
  The name of the handler which shall be used for accessing `path`. It is passed all optional parameters given to dba_open() and can act on behalf of them. If `handler` is `null`, then the default handler is invoked.
`permission`
  Optional int parameter which is passed to the driver. It has the same meaning as the `permissions` parameter of chmod(), and defaults to `0644`. The `db1`, `db2`, `db3`, `db4`, `dbm`, `gdbm`, `ndbm`, and `lmdb` drivers support the `permission` parameter.
`map_size`
  Optional int parameter which is passed to the driver. Its value should be a multiple of the page size of the OS, or zero, to use the default map size. Only the `lmdb` driver accepts the `map_size` parameter.
`flags`
  Flags to pass to the database drivers. If `null` the default flags will be provided. Currently, only the LMDB driver supports the following flags `DBA_LMDB_USE_SUB_DIR` and `DBA_LMDB_NO_SUB_DIR`.

### Return Values

Returns a Dba\Connection instance on success or `false` on failure.

### Errors/Exceptions

`false` is returned and an `E_WARNING` level error is issued when `handler` is `null`, but there is no default handler.

### Changelog

Version | Description
--- | ---
8.4.0 | Returns a Dba\Connection instance now; previously, a resource was returned.
8.2.0 | `flags` is added.
8.2.0 | `handler` is now nullable.
7.3.14, 7.4.2 | The `lmdb` driver now supports an additional `map_size` parameter.

### See Also

- dba_popen() - Open database persistently
- dba_close() - Close a DBA database

# dba_optimize

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_optimize — Optimize database

### Description

dba_optimize(Dba\Connection `$dba`): bool

dba_optimize() optimizes the underlying database.

### Parameters

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_sync() - Synchronize database

# dba_popen

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_popen — Open database persistently

### Description

dba_popen(
string `$path`,
string `$mode`,
?string `$handler` = `null`,
int `$permission` = 0644,
int `$map_size` = 0,
?int `$flags` = `null`
): Dba\Connection|false

dba_popen() establishes a persistent database instance for `path` with `mode` using `handler`.

### Parameters

`path`
  Commonly a regular path in your filesystem.
`mode`
  It is `r` for read access, `w` for read/write access to an already existing database, `c` for read/write access and database creation if it doesn't currently exist, and `n` for create, truncate and read/write access.
`handler`
  The name of the handler which shall be used for accessing `path`. It is passed all optional parameters given to dba_popen() and can act on behalf of them. If `handler` is `null`, then the default handler is invoked.
`permission`
  Optional int parameter which is passed to the driver. It has the same meaning as the `permissions` parameter of chmod(), and defaults to `0644`. The `db1`, `db2`, `db3`, `db4`, `dbm`, `gdbm`, `ndbm`, and `lmdb` drivers support the `permission` parameter.
`map_size`
  Optional int parameter which is passed to the driver. Its value should be a multiple of the page size of the OS, or zero, to use the default mapsize. The `lmdb` driver accepts the `map_size` parameter.
`flags`
  Allows to pass flags to the DB drivers. Currently, only LMDB with `DBA_LMDB_USE_SUB_DIR` and `DBA_LMDB_NO_SUB_DIR` are supported.

### Return Values

Returns a Dba\Connection instance on success or `false` on failure.

### Errors/Exceptions

`false` is returned and an `E_WARNING` level error is issued when `handler` is `null`, but there is no default handler.

### Changelog

Version | Description
--- | ---
8.4.0 | Returns a Dba\Connection instance now; previously, a resource was returned.
8.2.0 | `flags` is added.
8.1.0 | `handler` is now nullable.
7.3.14, 7.4.2 | The `lmdb` driver now supports an additional `map_size` parameter.

### See Also

- dba_open() - Open database
- dba_close() - Close a DBA database

# dba_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_replace — Replace or insert entry

### Description

dba_replace(string|array `$key`, string `$value`, Dba\Connection `$dba`): bool

dba_replace() replaces or inserts the entry described with `key` and `value` into the database specified by `dba`.

### Parameters

`key`
  The key of the entry to be replaced.
`value`
  The value to be replaced.
`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_exists() - Check whether key exists
- dba_delete() - Delete DBA entry specified by key
- dba_fetch() - Fetch data specified by key
- dba_insert() - Insert entry

# dba_sync

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_sync — Synchronize database

### Description

dba_sync(Dba\Connection `$dba`): bool

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

### Parameters

`dba`
  A Dba\Connection instance, returned by dba_open() or dba_popen().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | The `dba` parameter expects a Dba\Connection instance now; previously, a valid `dba` resource was expected.

### See Also

- dba_optimize() - Optimize database

## Table of Contents

- dba_close — Close a DBA database
- dba_delete — Delete DBA entry specified by key
- dba_exists — Check whether key exists
- dba_fetch — Fetch data specified by key
- dba_firstkey — Fetch first key
- dba_handlers — List all the handlers available
- dba_insert — Insert entry
- dba_key_split — Splits a key in string representation into array representation
- dba_list — List all open database files
- dba_nextkey — Fetch next key
- dba_open — Open database
- dba_optimize — Optimize database
- dba_popen — Open database persistently
- dba_replace — Replace or insert entry
- dba_sync — Synchronize database

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
  - Basic usage
- Dba\Connection — The Dba\Connection class
- DBA Functions
  - dba_close — Close a DBA database
  - dba_delete — Delete DBA entry specified by key
  - dba_exists — Check whether key exists
  - dba_fetch — Fetch data specified by key
  - dba_firstkey — Fetch first key
  - dba_handlers — List all the handlers available
  - dba_insert — Insert entry
  - dba_key_split — Splits a key in string representation into array representation
  - dba_list — List all open database files
  - dba_nextkey — Fetch next key
  - dba_open — Open database
  - dba_optimize — Optimize database
  - dba_popen — Open database persistently
  - dba_replace — Replace or insert entry
  - dba_sync — Synchronize database

# ODBC (Unified)

# Introduction

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: » Adabas D, » IBM DB2, » iODBC, » Solid, and » Sybase SQL Anywhere.

> Note:

> With the exception of iODBC, there is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. However, building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. More information on iODBC, is available at » www.iodbc.org with the alternative unixODBC available at » www.unixodbc.org.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

To access any of the supported databases you need to have the required libraries installed.

## Installation

--with-adabas[=DIR]

  Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.

--with-sapdb[=DIR]

  Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.

--with-solid[=DIR]

  Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.

--with-ibm-db2[=DIR]

  Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.

--with-empress[=DIR]

  Include Empress support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. This option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

  Include `"Empress Local Access"` support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. This option only supports Empress Version 8.60 and above.

--with-birdstep[=DIR]

  Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

  Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script:

         CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
         LDFLAGS=-lunix
         CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

  Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

  Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

  Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

  Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

  Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

Windows users must enable php_odbc.dll in order to use this extension.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Unified ODBC Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
odbc.allow_persistent | "1" | `INI_SYSTEM` |
odbc.check_persistent | "1" | `INI_SYSTEM` |
odbc.max_persistent | "-1" | `INI_SYSTEM` |
odbc.max_links | "-1" | `INI_SYSTEM` |
odbc.defaultlrl | "4096" | `INI_ALL` |
odbc.defaultbinmode | "1" | `INI_ALL` |
odbc.default_cursortype | "3" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`odbc.default_db` string

  ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

`odbc.default_user` string

  User name to use if none is specified in odbc_connect() or odbc_pconnect().

`odbc.default_pw` string

  Password to use if none is specified in odbc_connect() or odbc_pconnect().

`odbc.allow_persistent` bool

  Whether to allow persistent ODBC connections.

`odbc.check_persistent` bool

  Check that a connection is still valid before reuse.

`odbc.max_persistent` int

  The maximum number of persistent ODBC connections per process.

`odbc.max_links` int

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

`odbc.defaultlrl` int

  Handling of LONG fields. Specifies the number of bytes returned to variables. See odbc_longreadlen() for details.

  When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
`odbc.defaultbinmode` int

  Handling of binary data. See odbc_binmode() for details.

`odbc.default_cursortype` int

  Controls the ODBC cursor model. Possible values are `SQL_CURSOR_FORWARD_ONLY`, `SQL_CURSOR_KEYSET_DRIVEN`, `SQL_CURSOR_DYNAMIC` and `SQL_CURSOR_STATIC` (default).

## Resource Types

Prior to PHP 8.4.0, this extension defined two resource types: an ODBC connection identifier and an ODBC result identifier.

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

`ODBC_TYPE` (string)
`ODBC_BINMODE_PASSTHRU` (int)
`ODBC_BINMODE_RETURN` (int)
`ODBC_BINMODE_CONVERT` (int)
`SQL_ODBC_CURSORS` (int)
`SQL_CUR_USE_DRIVER` (int)
`SQL_CUR_USE_IF_NEEDED` (int)
`SQL_CUR_USE_ODBC` (int)
`SQL_CONCURRENCY` (int)
`SQL_CONCUR_READ_ONLY` (int)
`SQL_CONCUR_LOCK` (int)
`SQL_CONCUR_ROWVER` (int)
`SQL_CONCUR_VALUES` (int)
`SQL_CURSOR_TYPE` (int)
`SQL_CURSOR_FORWARD_ONLY` (int)
`SQL_CURSOR_KEYSET_DRIVEN` (int)
`SQL_CURSOR_DYNAMIC` (int)
`SQL_CURSOR_STATIC` (int)
`SQL_KEYSET_SIZE` (int)
`SQL_CHAR` (int)
`SQL_VARCHAR` (int)
`SQL_LONGVARCHAR` (int)
`SQL_WCHAR` (int)
  Unicode character string of fixed string length.
`SQL_WVARCHAR` (int)
  Unicode variable-length character string.
`SQL_WLONGVARCHAR` (int)
  Unicode variable-length character data. Maximum length is data source-dependent.
`SQL_DECIMAL` (int)
`SQL_NUMERIC` (int)
`SQL_BIT` (int)
`SQL_TINYINT` (int)
`SQL_SMALLINT` (int)
`SQL_INTEGER` (int)
`SQL_BIGINT` (int)
`SQL_REAL` (int)
`SQL_FLOAT` (int)
`SQL_DOUBLE` (int)
`SQL_BINARY` (int)
`SQL_VARBINARY` (int)
`SQL_LONGVARBINARY` (int)
`SQL_DATE` (int)
`SQL_TIME` (int)
`SQL_TIMESTAMP` (int)
`SQL_TYPE_DATE` (int)
`SQL_TYPE_TIME` (int)
`SQL_TYPE_TIMESTAMP` (int)
`SQL_BEST_ROWID` (int)
`SQL_ROWVER` (int)
`SQL_SCOPE_CURROW` (int)
`SQL_SCOPE_TRANSACTION` (int)
`SQL_SCOPE_SESSION` (int)
`SQL_NO_NULLS` (int)
`SQL_NULLABLE` (int)
`SQL_INDEX_UNIQUE` (int)
`SQL_INDEX_ALL` (int)
`SQL_ENSURE` (int)
`SQL_QUICK` (int)
`SQL_FETCH_FIRST` (int)
  Return the first rowset.
`SQL_FETCH_NEXT` (int)
  Return the next rowset.

# ODBC Functions

# odbc_autocommit

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_autocommit — Toggle autocommit behaviour

### Description

odbc_autocommit(Odbc\Connection `$odbc`, ?bool `$enable` = `null`): int|bool

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`enable`

  If `enable` is `true`, auto-commit is enabled, if it is `false` auto-commit is disabled. If `null` is passed, this function returns the auto-commit status for `odbc`.

### Return Values

With a `null` `enable` parameter, this function returns auto-commit status for `odbc`. Non-zero is returned if auto-commit is on, 0 if it is off, or `false` if an error occurs.

If `enable` is non-null, this function returns `true` on success and `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.3.0 | `enable` is now nullable.

### See Also

- odbc_commit() - Commit an ODBC transaction
- odbc_rollback() - Rollback a transaction

# odbc_binmode

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_binmode — Handling of binary column data

### Description

odbc_binmode(Odbc\Result `$statement`, int `$mode`): true

Controls handling of binary column data. ODBC SQL types affected are `BINARY`, `VARBINARY`, and `LONGVARBINARY`. The default mode can be set using the uodbc.defaultbinmode php.ini directive.

When binary SQL data is converted to character C data (`ODBC_BINMODE_CONVERT`), each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary `00000001` is converted to `"01"` and a binary `11111111` is converted to `"FF"`.

While the handling of `BINARY` and `VARBINARY` columns only depend on the binmode, the handling of `LONGVARBINARY` columns also depends on the longreadlen as well:

LONGVARBINARY handling
binmode | longreadlen | result
--- | --- | ---
`ODBC_BINMODE_PASSTHRU` | 0 | passthru
`ODBC_BINMODE_RETURN` | 0 | passthru
`ODBC_BINMODE_CONVERT` | 0 | passthru
`ODBC_BINMODE_PASSTHRU` | >0 | passthru
`ODBC_BINMODE_RETURN` | >0 | return as is
`ODBC_BINMODE_CONVERT` | >0 | return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns. If odbc_result() is used, passthru means that the data are sent directly to the client (i.e. printed).

### Parameters

`statement`

  The ODBC result object.

`mode`

  Possible values for `mode` are:

  - `ODBC_BINMODE_PASSTHRU`: Passthru BINARY data
  - `ODBC_BINMODE_RETURN`: Return as is
  - `ODBC_BINMODE_CONVERT`: Convert to char and return

  > Note: Handling of binary long columns is also affected by odbc_longreadlen().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_close

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_close — Close an ODBC connection

### Description

odbc_close(Odbc\Connection `$odbc`): void

Closes down the connection to the database server.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.

### Notes

> Note:

> This function will fail if there are open transactions on this connection. The connection will remain open in this case.

# odbc_close_all

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_close_all — Close all ODBC connections

### Description

odbc_close_all(): void

odbc_close_all() will close down all connections to database server(s).

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Notes

> Note:

> This function will fail if there are open transactions on a connection. This connection will remain open in this case.

# odbc_columnprivileges

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_columnprivileges — Lists columns and associated privileges for the given table

### Description

odbc_columnprivileges(
Odbc\Connection `$odbc`,
?string `$catalog`,
string `$schema`,
string `$table`,
string `$column`
): Odbc\Result|false

Lists columns and associated privileges for the given table.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`table`

  The table name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`column`

  The column name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

### Return Values

Returns an ODBC result object or `false` on failure. This result object can be used to fetch a list of columns and associated privileges.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `COLUMN_NAME`
- `GRANTOR`
- `GRANTEE`
- `PRIVILEGE`
- `IS_GRANTABLE`

Drivers can report additional columns.

The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `COLUMN_NAME` and `PRIVILEGE`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.

### Examples

Example #1 List Privileges for a Column

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$privileges = odbc_columnprivileges($conn, 'TutorialDB', 'dbo', 'test', 'id');
while (($row = odbc_fetch_array($privileges))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => TutorialDB
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => test
        [COLUMN_NAME] => id
        [GRANTOR] => dbo
        [GRANTEE] => dbo
        [PRIVILEGE] => INSERT
        [IS_GRANTABLE] => YES
    )

# odbc_columns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_columns — Lists the column names in specified tables

### Description

odbc_columns(
Odbc\Connection `$odbc`,
?string `$catalog` = `null`,
?string `$schema` = `null`,
?string `$table` = `null`,
?string `$column` = `null`
): Odbc\Result|false

Lists all columns in the requested range.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`table`

  The table name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`column`

  The column name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `COLUMN_NAME`
- `DATA_TYPE`
- `TYPE_NAME`
- `COLUMN_SIZE`
- `BUFFER_LENGTH`
- `DECIMAL_DIGITS`
- `NUM_PREC_RADIX`
- `NULLABLE`
- `REMARKS`
- `COLUMN_DEF`
- `SQL_DATA_TYPE`
- `SQL_DATETIME_SUB`
- `CHAR_OCTET_LENGTH`
- `ORDINAL_POSITION`
- `IS_NULLABLE`

Drivers can report additional columns.

The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME` and `ORDINAL_POSITION`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.0.0 | `schema`, `table` and `column` are now nullable.

### Examples

Example #1 List Columns of a Table

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$columns = odbc_columns($conn, 'TutorialDB', 'dbo', 'test', '%');
while (($row = odbc_fetch_array($columns))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => TutorialDB
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => TEST
        [COLUMN_NAME] => id
        [DATA_TYPE] => 4
        [TYPE_NAME] => int
        [COLUMN_SIZE] => 10
        [BUFFER_LENGTH] => 4
        [DECIMAL_DIGITS] => 0
        [NUM_PREC_RADIX] => 10
        [NULLABLE] => 0
        [REMARKS] =>
        [COLUMN_DEF] =>
        [SQL_DATA_TYPE] => 4
        [SQL_DATETIME_SUB] =>
        [CHAR_OCTET_LENGTH] =>
        [ORDINAL_POSITION] => 1
        [IS_NULLABLE] => NO
    )

### See Also

- odbc_columnprivileges() - Lists columns and associated privileges for the given table
- odbc_procedurecolumns() - Retrieve information about parameters to procedures

# odbc_commit

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_commit — Commit an ODBC transaction

### Description

odbc_commit(Odbc\Connection `$odbc`): bool

Commits all pending transactions on the connection.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.

# odbc_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_connect — Connect to a datasource

### Description

odbc_connect(
string `$dsn`,
?string `$user` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
int `$cursor_option` = `SQL_CUR_USE_DRIVER`
): Odbc\Connection|false

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

### Parameters

`dsn`

  The database source name for the connection. Alternatively, a DSN-less connection string can be used.

`user`

  The username. This parameter is ignored if `dsn` contains `uid`. To connect without specifying a `user`, use `null`.

`password`

  The password. This parameter is ignored if `dsn` contains `pwd`. To connect without specifying a `password`, use `null`.

`cursor_option`

  This sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

  The following constants are defined for cursortype:

  - SQL_CUR_USE_IF_NEEDED
  - SQL_CUR_USE_ODBC
  - SQL_CUR_USE_DRIVER

### Return Values

Returns an ODBC connection, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | This function returns a Odbc\Connection instance now; previously, a resource was returned.
8.4.0 | `user` and `password` are now nullable, they are now also optional and default to `null`.
8.4.0 | Previously, using an empty string for `password` would not include `pwd` in the generated connection string for `dsn`. It is now generated to include a `pwd` which has an empty string as its value. To restore the previous behaviour `password` can now be set to `null`.
8.4.0 | Previously, if `dsn` contained `uid` or `pwd` both `user` and `password` parameters were ignored. Now `user` is only ignored if `dsn` contains `uid`, and `password` is only ignored if `dsn` contains `pwd`.

### Examples

Example #1 DSN-less connections

`<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);
// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>`

### See Also

- For persistent connections: odbc_pconnect() - Open a persistent database connection

# odbc_connection_string_is_quoted

(PHP 8 >= 8.2.0)

odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted

### Description

odbc_connection_string_is_quoted(string `$str`): bool

Determines if a string is properly quoted for an ODBC connection string value. ODBC connection string quoting is performed using curly braces, and ending braces within a string must be escaped through repeating them twice, similar to SQL quoting.

### Parameters

`str`

  The string to check for quoting.

### Return Values

`true` if quoted properly, `false` if not.

### See Also

- odbc_connection_string_quote() - Quotes an ODBC connection string value
- odbc_connection_string_should_quote() - Determines if an ODBC connection string value should be quoted

# odbc_connection_string_quote

(PHP 8 >= 8.2.0)

odbc_connection_string_quote — Quotes an ODBC connection string value

### Description

odbc_connection_string_quote(string `$str`): string

Quotes a value for a connection string, according to ODBC rules. That is, it will be surrounded by quotes, and any ending curly braces will be escaped. This should be done for any connection string values that come from user input. Not doing so can lead to issues with parsing the connection string, or values being injected into the connection string.

Note that this function does not check if the string is already quoted, nor if the string needs quoting. For that, call odbc_connection_string_is_quoted() and odbc_connection_string_should_quote().

### Parameters

`str`

  The unquoted string.

### Return Values

A quoted string, surrounded by curly braces, and properly escaped.

### Examples

Example #1 odbc_connection_string_quote() example

This example quotes a string, then puts it in a connection string. Note that the string is quoted, and the ending quote character in the middle of the string has been escaped.

`<?php
$value = odbc_connection_string_quote("foo}bar");
$connection_string = "DSN=PHP;UserValue=$value";
echo $connection_string;
?>`

The above example will output something similar to:

    DSN=PHP;UserValue={foo}}bar}

### See Also

- odbc_connection_string_is_quoted() - Determines if an ODBC connection string value is quoted
- odbc_connection_string_should_quote() - Determines if an ODBC connection string value should be quoted

# odbc_connection_string_should_quote

(PHP 8 >= 8.2.0)

odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted

### Description

odbc_connection_string_should_quote(string `$str`): bool

Determines if a string needs to be quoted for an ODBC connection string value; that is, if it contains special characters.

Note that this does not check if the string is already quoted; an already quoted string will contain characters that will make this function return true. You should call odbc_connection_string_is_quoted() to check.

### Parameters

`str`

  The string to check for.

### Return Values

`true` if the string should be quoted; `false` otherwise.

### See Also

- odbc_connection_string_quote() - Quotes an ODBC connection string value
- odbc_connection_string_is_quoted() - Determines if an ODBC connection string value is quoted

# odbc_cursor

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_cursor — Get cursorname

### Description

odbc_cursor(Odbc\Result `$statement`): string|false

Gets the cursorname for the given result_id.

### Parameters

`statement`

  The ODBC result object.

### Return Values

Returns the cursor name, as a string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_data_source

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

odbc_data_source — Returns information about available DSNs

### Description

odbc_data_source(Odbc\Connection `$odbc`, int `$fetch_type`): array|null|false

This function will return the list of available DSN (after calling it several times).

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`fetch_type`

  The `fetch_type` can be one of two constant types: `SQL_FETCH_FIRST`, `SQL_FETCH_NEXT`. Use `SQL_FETCH_FIRST` the first time this function is called, thereafter use the `SQL_FETCH_NEXT`.

### Return Values

Returns `false` on error, an array upon success, and `null` after fetching the last available DSN.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.

### Examples

Example #1 List available DSNs

`<?php
$conn = odbc_connect('dsn', 'user', 'pass');
$dsn_info = odbc_data_source($conn, SQL_FETCH_FIRST);
while ($dsn_info) {
print_r($dsn_info);
$dsn_info = odbc_data_source($conn, SQL_FETCH_NEXT);
}
?>`

The above example will output something similar to:

    Array
    (
        [server] => dsn
        [description] => ODBC Driver 17 for SQL Server
    )
    Array
    (
        [server] => other_dsn
        [description] => Microsoft Access Driver (*.mdb, *.accdb)
    )

# odbc_do

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_do — Alias of odbc_exec()

### Description

This function is an alias of: odbc_exec().

# odbc_error

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_error — Get the last error code

### Description

odbc_error(?Odbc\Connection `$odbc` = `null`): string

Returns a six-digit ODBC state, or an empty string if there has been no errors.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

### Return Values

If `odbc` is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned `false`).

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.0.0 | `odbc` is now nullable.

### See Also

- odbc_errormsg() - Get the last error message
- odbc_exec() - Directly execute an SQL statement

# odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_errormsg — Get the last error message

### Description

odbc_errormsg(?Odbc\Connection `$odbc` = `null`): string

Returns a string containing the last ODBC error message, or an empty string if there has been no errors.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

### Return Values

If `odbc` is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned `false`).

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.0.0 | `odbc` is now nullable.

### See Also

- odbc_error() - Get the last error code
- odbc_exec() - Directly execute an SQL statement

# odbc_exec

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_exec — Directly execute an SQL statement

### Description

odbc_exec(Odbc\Connection `$odbc`, string `$query`): Odbc\Result|false

Sends an SQL statement to the database server.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`query`

  The SQL statement.

### Return Values

Returns an ODBC result object if the SQL command was executed successfully, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.
8.0.0 | `flags` was removed.

### See Also

- odbc_prepare() - Prepares a statement for execution
- odbc_execute() - Execute a prepared statement

# odbc_execute

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_execute — Execute a prepared statement

### Description

odbc_execute(Odbc\Result `$statement`, array `$params` = []): bool

Executes a statement prepared with odbc_prepare().

### Parameters

`statement`

  The ODBC result object from odbc_prepare().

`params`

  Parameters in `params` will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function.

  Any parameters in `params` which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

  If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.
8.0.0 | The unused `flags` parameter was removed.

### Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be `true` if all three parameters to myproc are IN parameters:

`<?php
$a = 1;
$b = 2;
$c = 3;
$stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>`

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, oci8 for Oracle).

### See Also

- odbc_prepare() - Prepares a statement for execution

# odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

odbc_fetch_array — Fetch a result row as an associative array

### Description

odbc_fetch_array(Odbc\Result `$statement`, ?int `$row` = `null`): array|false

Fetch an associative array from an ODBC query.

### Parameters

`statement`

  The ODBC result object from odbc_exec().

`row`

  Optionally choose which row number to retrieve.

### Return Values

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

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.
8.4.0 | `row` is now nullable.

### Notes

> Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

### See Also

- odbc_fetch_row() - Fetch a row
- odbc_fetch_object() - Fetch a result row as an object
- odbc_num_rows() - Number of rows in a result

# odbc_fetch_into

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_fetch_into — Fetch one result row into array

### Description

odbc_fetch_into(Odbc\Result `$statement`, array `&$array`, ?int `$row` = `null`): int|false

Fetch one result row into array.

### Parameters

`statement`

  The ODBC result object.

`array`

  The result array that can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

`row`

  The row number.

### Return Values

Returns the number of columns in the result; `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.
8.4.0 | `row` is now nullable.

### Examples

Example #1 odbc_fetch_into() examples

`<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>`

or

`<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>`

# odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

odbc_fetch_object — Fetch a result row as an object

### Description

odbc_fetch_object(Odbc\Result `$statement`, ?int `$row` = `null`): stdClass|false

Fetch an object from an ODBC query.

### Parameters

`statement`

  The ODBC result object from odbc_exec().

`row`

  Optionally choose which row number to retrieve.

### Return Values

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

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.
8.4.0 | `row` is now nullable.

### Notes

> Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

### See Also

- odbc_fetch_row() - Fetch a row
- odbc_fetch_array() - Fetch a result row as an associative array
- odbc_num_rows() - Number of rows in a result

# odbc_fetch_row

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_fetch_row — Fetch a row

### Description

odbc_fetch_row(Odbc\Result `$statement`, ?int `$row` = `null`): bool

Fetches a row of the data that was returned by odbc_do() or odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

### Parameters

`statement`

  The ODBC result object.

`row`

  If `row` is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without `row` can be mixed.

  To step through the result more than once, you can call odbc_fetch_row() with `row` 1, and then continue doing odbc_fetch_row() without `row` to review the result. If a driver doesn't support fetching rows by number, the `row` parameter is ignored.

### Return Values

Returns `true` if there was a row, `false` otherwise.

### Errors/Exceptions

An `E_WARNING` is emitted when `row` is equal or less than zero.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.
8.4.0 | An `E_WARNING` is now emitted when `row` is equal or less than zero.
8.0.0 | `row` is now nullable.

# odbc_field_len

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_len — Get the length (precision) of a field

### Description

odbc_field_len(Odbc\Result `$statement`, int `$field`): int|false

Gets the length of the field referenced by number in the given result identifier.

### Parameters

`statement`

  The ODBC result object.

`field`

  The field number. Field numbering starts at 1.

### Return Values

Returns the field length, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### See Also

- odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

# odbc_field_name

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_name — Get the columnname

### Description

odbc_field_name(Odbc\Result `$statement`, int `$field`): string|false

Gets the name of the field occupying the given column number in the given result object.

### Parameters

`statement`

  The ODBC result object.

`field`

  The field number. Field numbering starts at 1.

### Return Values

Returns the field name as a string, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_field_num

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_num — Return column number

### Description

odbc_field_num(Odbc\Result `$statement`, string `$field`): int|false

Gets the number of the column slot that corresponds to the named field in the given result object.

### Parameters

`statement`

  The ODBC result object.

`field`

  The field name.

### Return Values

Returns the field number as an integer, or `false` on error. Field numbering starts at 1.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_field_precision

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_precision — Alias of odbc_field_len()

### Description

This function is an alias of: odbc_field_len().

### See Also

- odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

# odbc_field_scale

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_scale — Get the scale of a field

### Description

odbc_field_scale(Odbc\Result `$statement`, int `$field`): int|false

Gets the scale of the field referenced by number in the given result identifier.

### Parameters

`statement`

  The ODBC result object.

`field`

  The field number. Field numbering starts at 1.

### Return Values

Returns the field scale as an integer, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_field_type

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_type — Datatype of a field

### Description

odbc_field_type(Odbc\Result `$statement`, int `$field`): string|false

Gets the SQL type of the field referenced by number in the given result identifier.

### Parameters

`statement`

  The ODBC result object.

`field`

  The field number. Field numbering starts at 1.

### Return Values

Returns the field type as a string, or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_foreignkeys

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_foreignkeys — Retrieves a list of foreign keys

### Description

odbc_foreignkeys(
Odbc\Connection `$odbc`,
?string `$pk_catalog`,
string `$pk_schema`,
string `$pk_table`,
string `$fk_catalog`,
string `$fk_schema`,
string `$fk_table`
): Odbc\Result|false

Retrieves a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`pk_catalog`

  The catalog ('qualifier' in ODBC 2 parlance) of the primary key table.

`pk_schema`

  The schema ('owner' in ODBC 2 parlance) of the primary key table.

`pk_table`

  The primary key table.

`fk_catalog`

  The catalog ('qualifier' in ODBC 2 parlance) of the foreign key table.

`fk_schema`

  The schema ('owner' in ODBC 2 parlance) of the foreign key table.

`fk_table`

  The foreign key table.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `PKTABLE_CAT`
- `PKTABLE_SCHEM`
- `PKTABLE_NAME`
- `PKCOLUMN_NAME`
- `FKTABLE_CAT`
- `FKTABLE_SCHEM`
- `FKTABLE_NAME`
- `FKCOLUMN_NAME`
- `KEY_SEQ`
- `UPDATE_RULE`
- `DELETE_RULE`
- `FK_NAME`
- `PK_NAME`
- `DEFERRABILITY`

Drivers can report additional columns.

If the foreign keys associated with a primary key are requested, the result set is ordered by `FKTABLE_CAT`, `FKTABLE_SCHEM`, `FKTABLE_NAME` and `KEY_SEQ`. If the primary keys associated with a foreign key are requested, the result set is ordered by `PKTABLE_CAT`, `PKTABLE_SCHEM`, `PKTABLE_NAME` and `KEY_SEQ`.

If `pk_table` contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If `fk_table` contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both `pk_table` and `fk_table` contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in `fk_table` that refer to the primary key of the table specified in `pk_table`. This should be one key at most.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### See Also

- odbc_tables() - Get the list of table names stored in a specific data source
- odbc_primarykeys() - Gets the primary keys for a table

# odbc_free_result

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_free_result — Free objects associated with a result

### Description

odbc_free_result(Odbc\Result `$statement`): true

Free objects associated with a result.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished.

### Parameters

`statement`

  The ODBC result object.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### Notes

> Note:

> If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

# odbc_gettypeinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

### Description

odbc_gettypeinfo(Odbc\Connection `$odbc`, int `$data_type` = 0): Odbc\Result|false

Retrieves information about data types supported by the data source.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`data_type`

  The data type, which can be used to restrict the information to a single data type.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- TYPE_NAME
- DATA_TYPE
- PRECISION
- LITERAL_PREFIX
- LITERAL_SUFFIX
- CREATE_PARAMS
- NULLABLE
- CASE_SENSITIVE
- SEARCHABLE
- UNSIGNED_ATTRIBUTE
- MONEY
- AUTO_INCREMENT
- LOCAL_TYPE_NAME
- MINIMUM_SCALE
- MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

# odbc_longreadlen

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_longreadlen — Handling of LONG columns

### Description

odbc_longreadlen(Odbc\Result `$statement`, int `$length`): true

Controls handling of `LONG`, `LONGVARCHAR` and `LONGVARBINARY` columns. The default length can be set using the uodbc.defaultlrl php.ini directive.

### Parameters

`statement`

  The ODBC result object.

`length`

  The number of bytes returned to PHP is controlled by the parameter length. If it is set to `0`, long column data is passed through to the client (i.e. printed) when retrieved with odbc_result().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### Notes

> Note:

> Handling of `LONGVARBINARY` columns is also affected by odbc_binmode().

# odbc_next_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_next_result — Checks if multiple results are available

### Description

odbc_next_result(Odbc\Result `$statement`): bool

Checks if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

### Parameters

`statement`

  The ODBC result object.

### Return Values

Returns `true` if there are more result sets, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### Examples

Example #1 odbc_next_result()

`<?php
$r_Connection = odbc_connect($dsn, $username, $password);
$s_SQL = <<<END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;
$r_Results = odbc_exec($r_Connection, $s_SQL);
$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);
echo "Get second results set ";
var_dump(odbc_next_result($r_Results));
$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);
echo "Get third results set ";
var_dump(odbc_next_result($r_Results));
$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);
echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?>`

The above example will output:

    Dump first result set array(1) {
      ["A"]=>
      string(1) "A"
    }
    bool(false)
    Get second results set bool(true)
    Dump second result set array(1) {
      ["B"]=>
      string(1) "B"
    }
    bool(false)
    Get third results set bool(true)
    Dump third result set array(1) {
      ["C"]=>
      string(1) "C"
    }
    bool(false)
    Try for a fourth result set bool(false)

# odbc_num_fields

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_num_fields — Number of columns in a result

### Description

odbc_num_fields(Odbc\Result `$statement`): int

Gets the number of fields (columns) in an ODBC result.

### Parameters

`statement`

  The ODBC result object returned by odbc_exec().

### Return Values

Returns the number of fields, or -1 on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

# odbc_num_rows

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_num_rows — Number of rows in a result

### Description

odbc_num_rows(Odbc\Result `$statement`): int

Gets the number of rows in a result. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

### Parameters

`statement`

  The ODBC result object returned by odbc_exec().

### Return Values

Returns the number of rows in an ODBC result. This function will return -1 on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### Notes

> Note:

> Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

# odbc_pconnect

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_pconnect — Open a persistent database connection

### Description

odbc_pconnect(
string `$dsn`,
?string `$user` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
int `$cursor_option` = `SQL_CUR_USE_DRIVER`
): Odbc\Connection|false

Opens a persistent database connection.

This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same `dsn`, `user`, `password` combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

### Parameters

See odbc_connect() for details.

### Return Values

Returns an ODBC connection, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | This function returns a Odbc\Connection instance now; previously, a resource was returned.
8.4.0 | `user` and `password` are now nullable, they are now also optional and default to `null`.
8.4.0 | Previously, using an empty string for `password` would not include `pwd` in the generated connection string for `dsn`. It is now generated to include a `pwd` which has an empty string as its value. To restore the previous behaviour `password` can now be set to `null`.
8.4.0 | Previously, if `dsn` contained `uid` or `pwd` both `user` and `password` parameters were ignored. Now `user` is only ignored if `dsn` contains `uid`, and `password` is only ignored if `dsn` contains `pwd`.

### Notes

> Note: Persistent connections have no effect if PHP is used as a CGI program.

### See Also

- odbc_connect() - Connect to a datasource
- Persistent Database Connections

# odbc_prepare

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_prepare — Prepares a statement for execution

### Description

odbc_prepare(Odbc\Connection `$odbc`, string `$query`): Odbc\Result|false

Prepares a statement for execution. The ODBC result object can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`query`

  The query string statement being prepared.

### Return Values

Returns an ODBC result object if the SQL command was prepared successfully. Returns `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be `true` if all three parameters to myproc are IN parameters:

`<?php
$a = 1;
$b = 2;
$c = 3;
$stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>`

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, oci8 for Oracle).

### See Also

- odbc_execute() - Execute a prepared statement

# odbc_primarykeys

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_primarykeys — Gets the primary keys for a table

### Description

odbc_primarykeys(
Odbc\Connection `$odbc`,
?string `$catalog`,
string `$schema`,
string `$table`
): Odbc\Result|false

Returns a result object that can be used to fetch the column names that comprise the primary key for a table.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance).

`table`

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `COLUMN_NAME`
- `KEY_SEQ`
- `PK_NAME`

Drivers can report additional columns.

The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME` and `KEY_SEQ`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### Examples

Example #1 List primary Keys of a Column

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$primarykeys = odbc_primarykeys($conn, 'TutorialDB', 'dbo', 'TEST');
while (($row = odbc_fetch_array($primarykeys))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => TutorialDB
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => TEST
        [COLUMN_NAME] => id
        [KEY_SEQ] => 1
        [PK_NAME] => PK__TEST__3213E83FE141F843
    )

### See Also

- odbc_tables() - Get the list of table names stored in a specific data source
- odbc_foreignkeys() - Retrieves a list of foreign keys

# odbc_procedurecolumns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_procedurecolumns — Retrieve information about parameters to procedures

### Description

odbc_procedurecolumns(
Odbc\Connection `$odbc`,
?string `$catalog` = `null`,
?string `$schema` = `null`,
?string `$procedure` = `null`,
?string `$column` = `null`
): Odbc\Result|false

Retrieve information about parameters to procedures.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`procedure`

  The proc. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`column`

  The column. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

### Return Values

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `PROCEDURE_CAT`
- `PROCEDURE_SCHEM`
- `PROCEDURE_NAME`
- `COLUMN_NAME`
- `COLUMN_TYPE`
- `DATA_TYPE`
- `TYPE_NAME`
- `COLUMN_SIZE`
- `BUFFER_LENGTH`
- `DECIMAL_DIGITS`
- `NUM_PREC_RADIX`
- `NULLABLE`
- `REMARKS`
- `COLUMN_DEF`
- `SQL_DATA_TYPE`
- `SQL_DATETIME_SUB`
- `CHAR_OCTET_LENGTH`
- `ORDINAL_POSITION`
- `IS_NULLABLE`

Drivers can report additional columns.

The result set is ordered by `PROCEDURE_CAT`, `PROCEDURE_SCHEM`, `PROCEDURE_NAME` and `COLUMN_TYPE`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.
8.0.0 | Prior to this version, the function could only be called with either one or five arguments.

### Examples

Example #1 List Columns of a stored Procedure

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$columns = odbc_procedurecolumns($conn, 'TutorialDB', 'dbo', 'GetEmployeeSalesYTD;1', '%');
while (($row = odbc_fetch_array($columns))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [PROCEDURE_CAT] => TutorialDB
        [PROCEDURE_SCHEM] => dbo
        [PROCEDURE_NAME] => GetEmployeeSalesYTD;1
        [COLUMN_NAME] => @SalesPerson
        [COLUMN_TYPE] => 1
        [DATA_TYPE] => -9
        [TYPE_NAME] => nvarchar
        [COLUMN_SIZE] => 50
        [BUFFER_LENGTH] => 100
        [DECIMAL_DIGITS] =>
        [NUM_PREC_RADIX] =>
        [NULLABLE] => 1
        [REMARKS] =>
        [COLUMN_DEF] =>
        [SQL_DATA_TYPE] => -9
        [SQL_DATETIME_SUB] =>
        [CHAR_OCTET_LENGTH] => 100
        [ORDINAL_POSITION] => 1
        [IS_NULLABLE] => YES
    )

### See Also

- odbc_columns() - Lists the column names in specified tables

# odbc_procedures

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_procedures — Get the list of procedures stored in a specific data source

### Description

odbc_procedures(
Odbc\Connection `$odbc`,
?string `$catalog` = `null`,
?string `$schema` = `null`,
?string `$procedure` = `null`
): Odbc\Result|false

Lists all procedures in the requested range.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`procedure`

  The name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

### Return Values

Returns an ODBC result object containing the information or `false` on failure.

The result set has the following columns:

- `PROCEDURE_CAT`
- `PROCEDURE_SCHEM`
- `PROCEDURE_NAME`
- `NUM_INPUT_PARAMS`
- `NUM_OUTPUT_PARAMS`
- `NUM_RESULT_SETS`
- `REMARKS`
- `PROCEDURE_TYPE`

Drivers can report additional columns.

The result set is ordered by `PROCEDURE_CAT`, `PROCEDURE_SCHEMA` and `PROCEDURE_NAME`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.
8.0.0 | Prior to this version, the function could only be called with either one or four arguments.

### Examples

Example #1 List stored Procedures of a Database

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$procedures = odbc_procedures($conn, $catalog, $schema, '%');
while (($row = odbc_fetch_array($procedures))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [PROCEDURE_CAT] => TutorialDB
        [PROCEDURE_SCHEM] => dbo
        [PROCEDURE_NAME] => GetEmployeeSalesYTD;1
        [NUM_INPUT_PARAMS] => -1
        [NUM_OUTPUT_PARAMS] => -1
        [NUM_RESULT_SETS] => -1
        [REMARKS] =>
        [PROCEDURE_TYPE] => 2
    )

### See Also

- odbc_procedurecolumns() - Retrieve information about parameters to procedures
- odbc_tables() - Get the list of table names stored in a specific data source

# odbc_result

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_result — Get result data

### Description

odbc_result(Odbc\Result `$statement`, string|int `$field`): string|bool|null

Get result data

### Parameters

`statement`

  The ODBC result object.

`field`

  The field name being retrieved. It can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field.

### Return Values

Returns the string contents of the field, `false` on error, `null` for NULL data, or `true` for binary data.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.

### Examples

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Example #1 odbc_result() examples

`<?php
$item_3 = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>`

### Notes

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

# odbc_result_all

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_result_all — Print result as HTML table

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
odbc_result_all(Odbc\Result `$statement`, string `$format` = ""): int|false

Prints all rows from a result object produced by odbc_exec(). The result is printed in HTML table format. The data is not escaped.

This function is not supposed to be used in production environments; it is merely meant for development purposes, to get a result set quickly rendered.

### Parameters

`statement`

  The ODBC result object.

`format`

  Additional overall table formatting.

### Return Values

Returns the number of rows in the result or `false` on error.

### Changelog

Version | Description
--- | ---
8.4.0 | `statement` expects an Odbc\Result instance now; previously, a resource was expected.
8.1.0 | This function has been deprecated.

# odbc_rollback

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_rollback — Rollback a transaction

### Description

odbc_rollback(Odbc\Connection `$odbc`): bool

Rolls back all pending statements on the connection.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.

# odbc_setoption

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_setoption — Adjust ODBC settings

### Description

odbc_setoption(
Odbc\Connection|Odbc\Result `$odbc`,
int `$which`,
int `$option`,
int `$value`
): bool

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

### Parameters

`odbc`

  Is a connection id or result id on which to change the settings. For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

`which`

  Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

`option`

  The option to set.

`value`

  The value for the given `option`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection or an Odbc\Result instance now; previously, a resource was expected.

### Examples

Example #1 odbc_setoption() examples

`<?php
// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
// Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
// This example has the same effect as
// odbc_autocommit($conn, true);
odbc_setoption($conn, 1, 102, 1);
// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
// This example sets the query to timeout after 30 seconds.
$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?>`

# odbc_specialcolumns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_specialcolumns — Retrieves special columns

### Description

odbc_specialcolumns(
Odbc\Connection `$odbc`,
int `$type`,
?string `$catalog`,
string `$schema`,
string `$table`,
int `$scope`,
int `$nullable`
): Odbc\Result|false

Retrieves either the optimal set of columns that uniquely identifies a row in the table, or columns that are automatically updated when any value in the row is updated by a transaction.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`type`
  When the type argument is `SQL_BEST_ROWID`, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table. When the type argument is `SQL_ROWVER`, odbc_specialcolumns() returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance).

`table`

  The table.

`scope`

  The scope, which orders the result set. One of `SQL_SCOPE_CURROW`, `SQL_SCOPE_TRANSACTION` or `SQL_SCOPE_SESSION`.

`nullable`

  Determines whether to return special columns that can have a NULL value. One of `SQL_NO_NULLS` or `SQL_NULLABLE`.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `SCOPE`
- `COLUMN_NAME`
- `DATA_TYPE`
- `TYPE_NAME`
- `COLUMN_SIZE`
- `BUFFER_LENGTH`
- `DECIMAL_DIGITS`
- `PSEUDO_COLUMN`

Drivers can report additional columns.

The result set is ordered by `SCOPE`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### See Also

- odbc_tables() - Get the list of table names stored in a specific data source

# odbc_statistics

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_statistics — Retrieve statistics about a table

### Description

odbc_statistics(
Odbc\Connection `$odbc`,
?string `$catalog`,
string `$schema`,
string `$table`,
int `$unique`,
int `$accuracy`
): Odbc\Result|false

Get statistics about a table and its indexes.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance).

`table`

  The table name.

`unique`

  The type of the index. One of `SQL_INDEX_UNIQUE` or `SQL_INDEX_ALL`.

`accuracy`

  One of `SQL_ENSURE` or `SQL_QUICK`. The latter requests that the driver retrieve the `CARDINALITY` and `PAGES` only if they are readily available from the server.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `NON_UNIQUE`
- `INDEX_QUALIFIER`
- `INDEX_NAME`
- `TYPE`
- `ORDINAL_POSITION`
- `COLUMN_NAME`
- `ASC_OR_DESC`
- `CARDINALITY`
- `PAGES`
- `FILTER_CONDITION`

Drivers can report additional columns.

The result set is ordered by `NON_UNIQUE`, `TYPE`, `INDEX_QUALIFIER`, `INDEX_NAME` and `ORDINAL_POSITION`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### Examples

Example #1 List Statistics of a Table

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$statistics = odbc_statistics($conn, 'TutorialDB', 'dbo', 'TEST', SQL_INDEX_UNIQUE, SQL_QUICK);
while (($row = odbc_fetch_array($statistics))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => TutorialDB
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => TEST
        [NON_UNIQUE] =>
        [INDEX_QUALIFIER] =>
        [INDEX_NAME] =>
        [TYPE] => 0
        [ORDINAL_POSITION] =>
        [COLUMN_NAME] =>
        [ASC_OR_DESC] =>
        [CARDINALITY] => 15
        [PAGES] => 3
        [FILTER_CONDITION] =>
    )

### See Also

- odbc_tables() - Get the list of table names stored in a specific data source

# odbc_tableprivileges

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_tableprivileges — Lists tables and the privileges associated with each table

### Description

odbc_tableprivileges(
Odbc\Connection `$odbc`,
?string `$catalog`,
string `$schema`,
string `$table`
): Odbc\Result|false

Lists tables in the requested range and the privileges associated with each table.

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`table`

  The name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

### Return Values

Returns an ODBC result object or `false` on failure.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `GRANTOR`
- `GRANTEE`
- `PRIVILEGE`
- `IS_GRANTABLE`

Drivers can report additional columns.

The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `PRIVILEGE` and `GRANTEE`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.

### Examples

Example #1 List Privileges of a Table

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$privileges = odbc_tableprivileges($conn, 'SalesOrders', 'dbo', 'Orders');
while (($row = odbc_fetch_array($privileges))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => SalesOrders
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => Orders
        [GRANTOR] => dbo
        [GRANTEE] => dbo
        [PRIVILEGE] => DELETE
        [IS_GRANTABLE] => YES
    )

### See Also

- odbc_tables() - Get the list of table names stored in a specific data source

# odbc_tables

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_tables — Get the list of table names stored in a specific data source

### Description

odbc_tables(
Odbc\Connection `$odbc`,
?string `$catalog` = `null`,
?string `$schema` = `null`,
?string `$table` = `null`,
?string `$types` = `null`
): Odbc\Result|false

Lists all tables in the requested range.

To support enumeration of qualifiers, owners, and table types, the following special semantics for the `catalog`, `schema`, `table`, and `table_type` are available:

- If `catalog` is a single percent character (%) and `schema` and `table` are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)
- If `schema` is a single percent character (%) and `catalog` and `table` are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)
- If `table_type` is a single percent character (%) and `catalog`, `schema` and `table` are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

### Parameters

`odbc`

  The ODBC connection object, see odbc_connect() for details.

`catalog`

  The catalog ('qualifier' in ODBC 2 parlance).

`schema`

  The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`table`

  The name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.

`types`

  If `table_type` is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (`'`) or unquoted. For example, `'TABLE','VIEW'` or `TABLE, VIEW`. If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

### Return Values

Returns an ODBC result object containing the information or `false` on failure.

The result set has the following columns:

- `TABLE_CAT`
- `TABLE_SCHEM`
- `TABLE_NAME`
- `TABLE_TYPE`
- `REMARKS`

Drivers can report additional columns.

The result set is ordered by `TABLE_TYPE`, `TABLE_CAT`, `TABLE_SCHEM` and `TABLE_NAME`.

### Changelog

Version | Description
--- | ---
8.4.0 | `odbc` expects an Odbc\Connection instance now; previously, a resource was expected.
8.4.0 | This function returns an Odbc\Result instance now; previously, a resource was returned.
8.0.0 | `schema`, `table` and `types` are now nullable.

### Examples

Example #1 List Tables in a Catalog

`<?php
$conn = odbc_connect($dsn, $user, $pass);
$tables = odbc_tables($conn, 'SalesOrders', 'dbo', '%', 'TABLE');
while (($row = odbc_fetch_array($tables))) {
print_r($row);
break; // further rows omitted for brevity
}
?>`

The above example will output something similar to:

    Array
    (
        [TABLE_CAT] => SalesOrders
        [TABLE_SCHEM] => dbo
        [TABLE_NAME] => Orders
        [TABLE_TYPE] => TABLE
        [REMARKS] =>
    )

### See Also

- odbc_tableprivileges() - Lists tables and the privileges associated with each table
- odbc_columns() - Lists the column names in specified tables
- odbc_specialcolumns() - Retrieves special columns
- odbc_statistics() - Retrieve statistics about a table
- odbc_procedures() - Get the list of procedures stored in a specific data source

## Table of Contents

- odbc_autocommit — Toggle autocommit behaviour
- odbc_binmode — Handling of binary column data
- odbc_close — Close an ODBC connection
- odbc_close_all — Close all ODBC connections
- odbc_columnprivileges — Lists columns and associated privileges for the given table
- odbc_columns — Lists the column names in specified tables
- odbc_commit — Commit an ODBC transaction
- odbc_connect — Connect to a datasource
- odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted
- odbc_connection_string_quote — Quotes an ODBC connection string value
- odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted
- odbc_cursor — Get cursorname
- odbc_data_source — Returns information about available DSNs
- odbc_do — Alias of odbc_exec
- odbc_error — Get the last error code
- odbc_errormsg — Get the last error message
- odbc_exec — Directly execute an SQL statement
- odbc_execute — Execute a prepared statement
- odbc_fetch_array — Fetch a result row as an associative array
- odbc_fetch_into — Fetch one result row into array
- odbc_fetch_object — Fetch a result row as an object
- odbc_fetch_row — Fetch a row
- odbc_field_len — Get the length (precision) of a field
- odbc_field_name — Get the columnname
- odbc_field_num — Return column number
- odbc_field_precision — Alias of odbc_field_len
- odbc_field_scale — Get the scale of a field
- odbc_field_type — Datatype of a field
- odbc_foreignkeys — Retrieves a list of foreign keys
- odbc_free_result — Free objects associated with a result
- odbc_gettypeinfo — Retrieves information about data types supported by the data source
- odbc_longreadlen — Handling of LONG columns
- odbc_next_result — Checks if multiple results are available
- odbc_num_fields — Number of columns in a result
- odbc_num_rows — Number of rows in a result
- odbc_pconnect — Open a persistent database connection
- odbc_prepare — Prepares a statement for execution
- odbc_primarykeys — Gets the primary keys for a table
- odbc_procedurecolumns — Retrieve information about parameters to procedures
- odbc_procedures — Get the list of procedures stored in a specific data source
- odbc_result — Get result data
- odbc_result_all — Print result as HTML table
- odbc_rollback — Rollback a transaction
- odbc_setoption — Adjust ODBC settings
- odbc_specialcolumns — Retrieves special columns
- odbc_statistics — Retrieve statistics about a table
- odbc_tableprivileges — Lists tables and the privileges associated with each table
- odbc_tables — Get the list of table names stored in a specific data source

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- ODBC Functions
  - odbc_autocommit — Toggle autocommit behaviour
  - odbc_binmode — Handling of binary column data
  - odbc_close — Close an ODBC connection
  - odbc_close_all — Close all ODBC connections
  - odbc_columnprivileges — Lists columns and associated privileges for the given table
  - odbc_columns — Lists the column names in specified tables
  - odbc_commit — Commit an ODBC transaction
  - odbc_connect — Connect to a datasource
  - odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted
  - odbc_connection_string_quote — Quotes an ODBC connection string value
  - odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted
  - odbc_cursor — Get cursorname
  - odbc_data_source — Returns information about available DSNs
  - odbc_do — Alias of odbc_exec
  - odbc_error — Get the last error code
  - odbc_errormsg — Get the last error message
  - odbc_exec — Directly execute an SQL statement
  - odbc_execute — Execute a prepared statement
  - odbc_fetch_array — Fetch a result row as an associative array
  - odbc_fetch_into — Fetch one result row into array
  - odbc_fetch_object — Fetch a result row as an object
  - odbc_fetch_row — Fetch a row
  - odbc_field_len — Get the length (precision) of a field
  - odbc_field_name — Get the columnname
  - odbc_field_num — Return column number
  - odbc_field_precision — Alias of odbc_field_len
  - odbc_field_scale — Get the scale of a field
  - odbc_field_type — Datatype of a field
  - odbc_foreignkeys — Retrieves a list of foreign keys
  - odbc_free_result — Free objects associated with a result
  - odbc_gettypeinfo — Retrieves information about data types supported by the data source
  - odbc_longreadlen — Handling of LONG columns
  - odbc_next_result — Checks if multiple results are available
  - odbc_num_fields — Number of columns in a result
  - odbc_num_rows — Number of rows in a result
  - odbc_pconnect — Open a persistent database connection
  - odbc_prepare — Prepares a statement for execution
  - odbc_primarykeys — Gets the primary keys for a table
  - odbc_procedurecolumns — Retrieve information about parameters to procedures
  - odbc_procedures — Get the list of procedures stored in a specific data source
  - odbc_result — Get result data
  - odbc_result_all — Print result as HTML table
  - odbc_rollback — Rollback a transaction
  - odbc_setoption — Adjust ODBC settings
  - odbc_specialcolumns — Retrieves special columns
  - odbc_statistics — Retrieve statistics about a table
  - odbc_tableprivileges — Lists tables and the privileges associated with each table
  - odbc_tables — Get the list of table names stored in a specific data source

# PHP Data Objects

# Introduction

The `PHP Data Objects` (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-pdo

Installing PDO on Unix systems

1. PDO and the PDO_SQLITE driver is enabled by default. You may need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that.

   > Note:

   > When building PDO as a shared extension (not recommended) then all PDO drivers must be loaded after PDO itself.

2. When installing PDO as a shared module, the php.ini file needs to be updated so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the extension=pdo line, as PDO must be initialized before the database-specific extensions can be loaded. If you built PDO and the database-specific extensions statically, you can skip this step.

       extension=pdo

Windows users

1. PDO is enabled by default. Choose the other database-specific DLL files and either use dl() to load them at runtime, or enable them in php.ini. For example, this loads the PDO_SQLITE driver but leaves the PDO_ODBC driver commented out:

       ;extension=pdo_odbc
       extension=pdo_sqlite

   These DLLs should exist in the system's extension_dir.

> Note:

> Remember that after making changes to your php.ini file you will need to restart PHP for your new configuration directives to take effect.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
pdo.dsn.* |  | php.ini only |

Here's a short explanation of the configuration directives.

`pdo.dsn.*` string

  Defines DSN alias. See PDO::__construct() for thorough explanation.

# Predefined Constants

## Table of Contents

- Fetch Modes

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.

## Fetch Modes

See cursor constants for the `PDO::FETCH_ORI_*` cursor constants.

## Basic Fetch Modes

Fetch Mode | Summary
--- | ---
`PDO::FETCH_DEFAULT` | Special value for using the current default fetch mode.
`PDO::FETCH_ASSOC` | Array indexed by column name only.
`PDO::FETCH_BOTH` (Default) | Array indexed by both column number and name.
`PDO::FETCH_NAMED` | Variant of `PDO::FETCH_ASSOC` that retains duplicated columns.
`PDO::FETCH_NUM` | Array indexed by column number only.
`PDO::FETCH_COLUMN` | A single column.
`PDO::FETCH_KEY_PAIR` | Key-value pairs, indexed by the first column.
`PDO::FETCH_FUNC` | Use a function to create the return value. (PDOStatement::fetchAll() only)
`PDO::FETCH_OBJ` | Anonymous (stdClass) object.
`PDO::FETCH_CLASS` | An object of a specified class.

## PDO::FETCH_CLASS options

These modes are used to implement options when using `PDO::FETCH_CLASS`.

Fetch Mode | Summary
--- | ---
`PDO::FETCH_CLASSTYPE` | Use the first column as the class name.
`PDO::FETCH_PROPS_LATE` | Call the constructor before setting properties.
`PDO::FETCH_SERIALIZE` | Use PHP serialized data. Deprecated as of PHP 8.1.0.

## Single Result Modes

The following modes cannot be used with PDOStatement::fetchAll().

Fetch Mode | Summary
--- | ---
`PDO::FETCH_BOUND` | Bind values to specified variables.
`PDO::FETCH_INTO` | Update an existing object.
`PDO::FETCH_LAZY` | Lazy fetch via PDORow for array- and object-like access.

## Special Behavior Flags for PDOStatement::fetchAll()

The following special modes for multiple results only work with PDOStatement::fetchAll() and do not work with some other fetch modes. Check the full documentation for details.

Fetch Mode | Summary
--- | ---
`PDO::FETCH_GROUP` | Results are grouped by the first column.
`PDO::FETCH_UNIQUE` | Results are (uniquely) indexed by the first column.

## Handling of Duplicated Column Names

It's possible for results to contain multiple columns that use the same name. For example, when joining 2 tables that both contain a column with the same name.

Because PHP structures such as arrays and objects don't support multiple keys or properties that use the same name, the returned array or object will contain only 1 of the values using the same name.

Which value is returned for a given duplicated name should be considered undefined.

To avoid this issue, explicitly name columns using an alias. For example:

    SELECT table1.created_at AS t1_created_at,
           table2.created_at AS t2_created_at
    FROM table1
    JOIN table2 ON table1.table2id = table2.id

See also `PDO::FETCH_NAMED`, `PDO::ATTR_FETCH_TABLE_NAMES` and `PDO::ATTR_FETCH_CATALOG_NAMES`.

## Setting the Default Fetch Mode

It is possible to set default fetch mode for all queries using `PDO::ATTR_DEFAULT_FETCH_MODE` with PDO::__construct() or PDO::setAttribute().

The default fetch mode for a specific statement can be set using PDOStatement::setFetchMode(). This affects reuse as a prepared statement and iteration (using `foreach`).

Caution

PDOStatement::setAttribute() cannot be used to set the default fetch mode. It only accepts driver specific attributes and silently ignores attributes that are not recognized.

## PDO::FETCH_DEFAULT (int)

Available as of PHP 8.0.7.

This is a special value that uses the current default fetch mode for a PDOStatement. It's specifically useful as the default value for method parameters when extending PDOStatement for use with `PDO::ATTR_STATEMENT_CLASS`.

This value cannot be used with `PDO::ATTR_DEFAULT_FETCH_MODE`.

## PDO::FETCH_ASSOC (int)

`PDO::FETCH_ASSOC` returns an array indexed by column name only.

`<?php
$stmt = $pdo->query("SELECT userid, name, country FROM users");
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
print_r($row);`

The above example will output:

    Array
    (
        [userid] => 104
        [name] => Chris
        [country] => Ukraine
    )

## PDO::FETCH_BOTH (int)

This is the default fetch mode.

`PDO::FETCH_BOTH` returns an array indexed by both column number and name. This means that every returned value is duplicated for each result row.

The column number starts at 0 and is determined by the result column order in the query, not (for example) the order columns are defined in the table.

> Note: Using the numeric column index is not recommended as this may change when the query is changed, or when the table schema is changed when using `SELECT *`.

> Note: The number of entries indexed by name may not match the number of entries indexed by number in cases where multiple returned columns use the same name.

`<?php
$stmt = $pdo->query("SELECT userid, name, country FROM users");
$row = $stmt->fetch(\PDO::FETCH_BOTH);
print_r($row);`

The above example will output:

    Array
    (
        [id] => 104,
        [0] => 104,
        [name] => Chris,
        [1] => Chris,
        [country] => Ukraine,
        [2] => Ukraine
    )

## PDO::FETCH_NAMED (int)

`PDO::FETCH_NAMED` returns results in the same format as `PDO::FETCH_ASSOC` except that where multiple columns use the same name, all values are returned as a list.

For more information on handling of duplicated column names and alternatives, see the handling of duplicated names section above.

The order in which duplicated values are returned should be considered undefined. There's no way to tell where each value came from.

`<?php
$stmt = $pdo->query(
"SELECT users.*, referrer.name
FROM users
LEFT JOIN users AS referrer ON users.referred_by = referrer.userid
WHERE userid = 109"
);
$row = $stmt->fetch(\PDO::FETCH_NUM);
print_r($row);`

The above example will output:

    Array
    (
        [userid] => 109
        [name] => Array
            (
                [0] => Toni
                [1] => Chris
            )
        [country] => Germany
        [referred_by] = 104
    )

## PDO::FETCH_NUM (int)

`PDO::FETCH_NUM` returns an array indexed by column number only. The column number starts at 0 and is determined by the result column order in the query, not (for example) the order columns are defined in the table.

> Note: Using the numeric column index is not recommended as this may change when the query is changed, or when the table schema is changed when using `SELECT *`.

`<?php
$stmt = $pdo->query("SELECT userid, name, country FROM users");
$row = $stmt->fetch(\PDO::FETCH_NUM);
print_r($row);`

The above example will output:

    Array
    (
        [0] => 104
        [1] => Chris
        [2] => Ukraine
    )

## PDO::FETCH_COLUMN (int)

`PDO::FETCH_COLUMN` returns values from a single column. Use the second argument for PDOStatement::setFetchMode() or PDOStatement::fetchAll() to specify which column is returned.

If the specified column does not exist a ValueError will be thrown.

`<?php
$stmt = $pdo->query("SELECT name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_COLUMN);
print_r($row);
$stmt = $pdo->query("SELECT name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_COLUMN, 1);
print_r($row);`

The above example will output:

    Array
    (
        [0] => Chris
        [1] => Jamie
        [2] => Robin
    )

    Array
    (
        [0] => Ukraine
        [1] => England
        [2] => Germany
    )

## PDO::FETCH_KEY_PAIR (int)

`PDO::FETCH_KEY_PAIR` returns pairs of values, indexed by the first column. The results must contain only 2 columns. This fetch mode only makes sense with PDOStatement::fetchAll().

> Note: If the first column is not unique, values will be lost. Which value(s) are lost should be considered undefined.

`<?php
$stmt = $pdo->query("SELECT name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);
print_r($row);`

The above example will output:

    Array
    (
        [Chris] => Ukraine
        [Jamie] => England
        [Robin] => Germany
    )

## PDO::FETCH_FUNC (int)

Specify a function to create the returned value. This mode can only be used with PDOStatement::fetchAll().

The function receives the values as parameters. There's no way to retrieve the column name a given value was associated with. It is crucial to ensure that the column order in the query matches the order of parameters of the function.

> Note: The effects of `PDO::FETCH_GROUP` and `PDO::FETCH_UNIQUE` are applied to results before the function is called.

`<?php
function valueCreator($col1, $col2, $col3)
{
return [
'col1' => $col1,
'col2' => strtoupper($col2),
'col3' => $col3,
'customKey' => 'customValue',
];
}
$stmt = $pdo->query("SELECT userid, name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_FUNC, valueCreator(...));
print_r($row);`

The above example will output:

    Array
    (
        [0] => Array
            (
                [col1] => 104
                [col2] => SAM
                [col3] => Ukraine
                [customKey] => customValue
            )

        [1] => Array
            (
                [col1] => 105
                [col2] => JAMIE
                [col3] => England
                [customKey] => customValue
            )

        [2] => Array
            (
                [col1] => 107
                [col2] => ROBIN
                [col3] => Germany
                [customKey] => customValue
            )

    )

## PDO::FETCH_OBJ (int)

`PDO::FETCH_OBJ` returns a stdClass object.

See also PDOStatement::fetchObject() and `PDO::FETCH_CLASS`.

`<?php
$stmt = $pdo->query("SELECT userid, name, country FROM users");
$row = $stmt->fetch(\PDO::FETCH_OBJ);
print_r($row);`

The above example will output:

    stdClass Object
    (
        [userid] => 104
        [name] => Chris
        [country] => Ukraine
    )

## PDO::FETCH_CLASS (int)

Returns an object of a specified class. For additional behaviors see the option flags.

If a property does not exist with the name of a returned column, it will be dynamically declared. This behavior is deprecated and will cause an error from PHP 9.0.

See also PDOStatement::fetchObject().

`<?php
class TestEntity
{
public $userid;
public $name;
public $country;
public $referred_by_userid;
public function __construct()
{
print "Constructor called with ". count(func_get_args()) ." args\n";
print "Properties set when constructor called? "
. (isset($this->name) ? 'Yes' : 'No') . "\n";
}
}
$stmt = $db->query(
"SELECT userid, name, country, referred_by_userid FROM users"
);
$stmt->setFetchMode(PDO::FETCH_CLASS, TestEntity::class);
$result = $stmt->fetch();
var_dump($result);`

The above example will output something similar to:

    Constructor called with 0 args
    Properties set when constructor called? Yes
    object(TestEntity)#3 (4) {
      ["userid"]=>
      int(104)
      ["name"]=>
      string(5) "Chris"
      ["country"]=>
      string(7) "Ukraine"
      ["referred_by_userid"]=>
      NULL
    }

## PDO::FETCH_CLASSTYPE (int)

This fetch mode can only be used combined with `PDO::FETCH_CLASS` (and its other options).

When this fetch mode is used, PDO will use the first returned column as the name of the class to return.

If the specified class cannot be found, a stdClass object will be returned, without warning or error.

`<?php
class TestEntity
{
public $userid;
public $name;
public $country;
public $referred_by_userid;
public function __construct()
{
print "Constructor called with ". count(func_get_args()) ." args\n";
print "Properties set when constructor called? "
. (isset($this->name) ? 'Yes' : 'No') . "\n";
}
}
$stmt = $db->query(
"SELECT 'TestEntity', userid, name, country, referred_by_userid FROM users"
);
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
$result = $stmt->fetch();
var_dump($result);`

The above example will output something similar to:

    Constructor called with 0 args
    Properties set when constructor called? Yes
    object(TestEntity)#3 (4) {
      ["userid"]=>
      int(104)
      ["name"]=>
      string(5) "Chris"
      ["country"]=>
      string(7) "Ukraine"
      ["referred_by_userid"]=>
      NULL
    }

## PDO::FETCH_PROPS_LATE (int)

This fetch mode can only be used combined with `PDO::FETCH_CLASS` (and its other options).

When this fetch mode is used, the constructor will be called before the properties are set.

`<?php
class TestEntity
{
public $userid;
public $name;
public $country;
public $referred_by_userid;
public function __construct()
{
print "Constructor called with ". count(func_get_args()) ." args\n";
print "Properties set when constructor called? "
. (isset($this->name) ? 'Yes' : 'No') . "\n";
}
}
$stmt = $db->query(
"SELECT userid, name, country, referred_by_userid FROM users"
);
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, TestEntity::class);
$result = $stmt->fetch();
var_dump($result);`

The above example will output something similar to:

    Constructor called with 0 args
    Properties set when constructor called? No
    object(TestEntity)#3 (4) {
      ["userid"]=>
      int(104)
      ["name"]=>
      string(5) "Chris"
      ["country"]=>
      string(7) "Ukraine"
      ["referred_by_userid"]=>
      NULL
    }

## PDO::FETCH_SERIALIZE (int)

Warning

This feature has been DEPRECATED as of PHP 8.1.0. Relying on this feature is highly discouraged.

This fetch mode can only be used combined with `PDO::FETCH_CLASS` (and its other options).

When this fetch mode is used, the specified class must be Serializable.

Caution

This feature does not support a string that contains a complete serialized object (with serialize()).

Caution

This fetch mode does not call the constructor.

`<?php
class TestEntity implements Serializable
{
public $userid;
public $name;
public $country;
public $referred_by_userid;
public function __construct()
{
print "Constructor called with " . count(func_get_args()) . " args\n";
print "Properties set when constructor called? "
. (isset($this->name) ? 'Yes' : 'No') . "\n";
}
public function serialize()
{
return join(
"|",
[$this->userid, $this->name, $this->country, $this->referred_by_userid]
);
}
public function unserialize(string $data)
{
$parts = explode("|", $data);
$this->userid = (int) $parts[0];
$this->name = $parts[1];
$this->country = $parts[2];
$refId = $parts[3];
$this->referred_by_userid = ($refId === "" ? null : (int) $refId);
}
}
print "Set up record (constructor called manually):\n";
$db->exec(
"CREATE TABLE serialize (
sdata TEXT
)"
);
$origObj = new TestEntity();
$origObj->userid = 200;
$origObj->name = 'Seri';
$origObj->country = 'Syria';
$origObj->referred_by_userid = null;
$insert = $db->prepare("INSERT INTO serialize (sdata) VALUES (:sdata)");
$insert->execute(['sdata' => $origObj->serialize()]);
print "\nRetrieve result:\n";
$query = "SELECT sdata FROM serialize";
$stmt = $db->query($query);
// NOTE: Constructor is never called!
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_SERIALIZE, TestEntity::class);
$result = $stmt->fetch();
var_dump($result);`

The above example will output something similar to:

    Deprecated: TestEntity implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize() instead (or in addition, if support for old PHP versions is necessary) in Standard input code on line 2
    Set up record (constructor called manually):
    Constructor called with 0 args
    Properties set when constructor called? No

    Retrieve result:
    Deprecated: PDOStatement::setFetchMode(): The PDO::FETCH_SERIALIZE mode is deprecated in Standard input code on line 58

    Deprecated: PDOStatement::fetch(): The PDO::FETCH_SERIALIZE mode is deprecated in Standard input code on line 59
    object(TestEntity)#5 (4) {
      ["userid"]=>
      int(200)
      ["name"]=>
      string(4) "Seri"
      ["country"]=>
      string(5) "Syria"
      ["referred_by_userid"]=>
      NULL
    }

## PDO::FETCH_BOUND (int)

This fetch mode cannot be used with PDOStatement::fetchAll().

This fetch mode does not directly return a result, but binds values to variables specified with PDOStatement::bindColumn(). The called fetch method returns `true`.

> Note: When using prepared statements, to work correctly, variables must be bound after the query is executed.

`<?php
$query = "SELECT users.userid, users.name, users.country, referrer.name
FROM users
LEFT JOIN users AS referrer ON users.referred_by_userid = referrer.userid";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bindColumn('userid', $userId);
$stmt->bindColumn('name', $name);
$stmt->bindColumn('country', $country);
// Bind by column position to resolve duplicated column name
// To avoid this breaking if the query is changed, use an SQL alias instead
// For example: referrer.name AS referrer_name
$stmt->bindColumn(4, $referrerName);
while ($stmt->fetch(\PDO::FETCH_BOUND)) {
print join("\t", [$userId, $name, $country, ($referrerName ?? 'NULL')]) . "\n";
}`

The above example will output:

    104	Chris	Ukraine	NULL
    105	Jamie	England	NULL
    107	Robin	Germany	Chris
    108	Sean	Ukraine	NULL
    109	Toni	Germany	NULL
    110	Toni	Germany	NULL

## PDO::FETCH_INTO (int)

This fetch mode cannot be used with PDOStatement::fetchAll().

This fetch mode updates properties in the specified object. The object is returned on success.

If a property does not exist with the name of a returned column, it will be dynamically declared. This behavior is deprecated and will cause an error from PHP 9.0.

Properties must be `public` and cannot be `readonly`.

Caution

There's no way to change the object to be updated without using PDOStatement::setFetchMode() between retrieving each record.

`<?php
class TestEntity
{
public $userid;
public $name;
public $country;
public $referred_by_userid;
}
$obj = new TestEntity();
$stmt = $db->query("SELECT userid, name, country, referred_by_userid FROM users");
$stmt->setFetchMode(\PDO::FETCH_INTO, $obj);
$result = $stmt->fetch();
var_dump($result);`

The above example will output something similar to:

    object(TestEntity)#3 (4) {
      ["userid"]=>
      int(104)
      ["name"]=>
      string(5) "Chris"
      ["country"]=>
      string(7) "Ukraine"
      ["referred_by_userid"]=>
      NULL
    }

## PDO::FETCH_LAZY (int)

This fetch mode cannot be used with PDOStatement::fetchAll().

This fetch mode returns a PDORow object which provides both array- and object-like access to values (i.e. combines the behavior of `PDO::FETCH_BOTH` and `PDO::FETCH_OBJ`), retrieved in a lazy manner.

This can provide memory efficient access (on the PHP side) to unbuffered results on the database server. Whether PDO uses client-side buffering for results depends on the database-specific driver used (and its configuration).

Caution

PDORow will return `NULL` without any error or warning when accessing properties or keys that are not defined. This can make errors such as typos or queries not returning expected data harder to spot and debug.

Caution

The returned PDORow object is updated each time a result is retrieved.

`<?php
$stmt = $db->query("SELECT userid, name, country, referred_by_userid FROM users");
$result = $stmt->fetch(\PDO::FETCH_LAZY);
print "ID: ". $result[0] ."\n";
print "Name: {$result->name}\n";
print "Country: " . $result['country'] ."\n";
// Returns NULL. No warning or error is raised.
print "Does not exist: " . var_export($result->does_not_exist, true) . "\n";
$differentResult = $stmt->fetch(\PDO::FETCH_LAZY);
// The previously retrieved PDORow now points to the newly retrieved result
print "ID: ". $result[0] ."\n";`

The above example will output:

    ID: 104
    Name: Chris
    Country: Ukraine
    Does not exist: NULL
    ID: 105

## PDO::FETCH_GROUP (int)

`PDO::FETCH_GROUP` returns lists of associative arrays, indexed by a (non-unique) column. This fetch mode only works with PDOStatement::fetchAll().

When combined with `PDO::FETCH_UNIQUE`, both modes will use the same column, rendering the combination of these modes useless.

This fetch should be combined with one of `PDO::FETCH_ASSOC`, `PDO::FETCH_BOTH`, `PDO::FETCH_NAMED`, `PDO::FETCH_NUM`, `PDO::FETCH_COLUMN` or `PDO::FETCH_FUNC`.

If no fetch mode from the above list is given, the current default fetch mode for the PDOStatement will be used.

`<?php
$stmt = $pdo->query("SELECT country, userid, name FROM users");
$row = $stmt->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_ASSOC);
print_r($row);`

The above example will output:

    Array
    (
        [Ukraine] => Array
            (
                [0] => Array
                    (
                        [userid] => 104
                        [name] => Chris
                    )

                [1] => Array
                    (
                        [userid] => 108
                        [name] => Sean
                    )

            )
        [England] => Array
            (
                [0] => Array
                    (
                        [userid] => 105
                        [name] => Jamie
                    )

            )

        [Germany] => Array
            (
                [0] => Array
                    (
                        [userid] => 107
                        [name] => Robin
                    )

                [1] => Array
                    (
                        [userid] => 109
                        [name] => Toni
                    )
            )
    )

In the above example one should note that the first column is omitted from the array for each row, only available as the key. It can be included by repeating the column, as in the following example:

`<?php
$stmt = $pdo->query("SELECT country, userid, name, country FROM users");
$row = $stmt->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_ASSOC);
print_r($row);`

The above example will output:

    Array
    (
        [Ukraine] => Array
            (
                [0] => Array
                    (
                        [userid] => 104
                        [name] => Chris
                        [country] => Ukraine
                    )

                [1] => Array
                    (
                        [userid] => 108
                        [name] => Sean
                        [country] => Ukraine
                    )

            )
        [England] => Array
            (
                [0] => Array
                    (
                        [userid] => 105
                        [name] => Jamie
                        [country] => England
                    )

            )

        [Germany] => Array
            (
                [0] => Array
                    (
                        [userid] => 107
                        [name] => Robin
                        [country] => Germany
                    )

                [1] => Array
                    (
                        [userid] => 109
                        [name] => Toni
                        [country] => Germany
                    )
            )
    )

## PDO::FETCH_UNIQUE (int)

`PDO::FETCH_UNIQUE` uses the first column to index records, returning 1 record per index value. This fetch mode only works with PDOStatement::fetchAll().

When combined with `PDO::FETCH_GROUP`, both modes will use the same column, rendering the combination of these modes useless.

This fetch should be combined with one of `PDO::FETCH_ASSOC`, `PDO::FETCH_BOTH`, `PDO::FETCH_NAMED`, `PDO::FETCH_NUM`, `PDO::FETCH_COLUMN` or `PDO::FETCH_FUNC`.

If no fetch mode from the above list is given, the current default fetch mode for the PDOStatement will be used.

When used with a column that is known to be unique (such as record ID), this mode provides the ability to quickly return results indexed by that value.

> Note: If the first column is not unique, values will be lost. Which value(s) are lost should be considered undefined.

Caution

Filtering records should be done in SQL where possible. The database will use indexes to optimize this process and return only the required records. Selecting more records than required from the database may significantly increase memory usage and query time for larger result sets.

`<?php
$stmt = $pdo->query("SELECT userid, name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC);
print_r($row);`

The above example will output:

    Array
    (
        [104] => Array
            (
                [name] => Chris
                [country] => Ukraine
            )

        [105] => Array
            (
                [name] => Jamie
                [country] => England
            )

        [107] => Array
            (
                [name] => Robin
                [country] => Germany
            )

    )

In the above example one should note that the first column is omitted from the array for each row, only available as the key. It can be included by repeating the column, as in the following example:

`<?php
$stmt = $pdo->query("SELECT userid, userid, name, country FROM users LIMIT 3");
$row = $stmt->fetchAll(\PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC);
print_r($row);`

The above example will output:

    Array
    (
        [104] => Array
            (
                [userid] => 104
                [name] => Chris
                [country] => Ukraine
            )

        [105] => Array
            (
                [userid] => 105
                [name] => Jamie
                [country] => England
            )

        [107] => Array
            (
                [userid] => 107
                [name] => Robin
                [country] => Germany
            )

    )

## Cursors

See also `PDO::ATTR_CURSOR_NAME`.

`PDO::FETCH_ORI_NEXT` (int)
  Fetch the next row in the result set. Valid only for scrollable cursors.
`PDO::FETCH_ORI_PRIOR` (int)
  Fetch the previous row in the result set. Valid only for scrollable cursors.
`PDO::FETCH_ORI_FIRST` (int)
  Fetch the first row in the result set. Valid only for scrollable cursors.
`PDO::FETCH_ORI_LAST` (int)
  Fetch the last row in the result set. Valid only for scrollable cursors.
`PDO::FETCH_ORI_ABS` (int)
  Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
`PDO::FETCH_ORI_REL` (int)
  Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
`PDO::CURSOR_FWDONLY` (int)
  Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.
`PDO::CURSOR_SCROLL` (int)
  Create a PDOStatement object with a scrollable cursor. Pass the `PDO::FETCH_ORI_*` constants to control the rows fetched from the result set.

## Other Constants

`PDO::PARAM_BOOL` (int)
  Represents a boolean data type.
`PDO::PARAM_NULL` (int)
  Represents the SQL NULL data type.
`PDO::PARAM_INT` (int)
  Represents the SQL INTEGER data type.
`PDO::PARAM_STR` (int)
  Represents the SQL CHAR, VARCHAR, or other string data type.
`PDO::PARAM_STR_NATL` (int)
  Flag to denote a string uses the national character set. Available as of PHP 7.2.0
`PDO::PARAM_STR_CHAR` (int)
  Flag to denote a string uses the regular character set. Available as of PHP 7.2.0
`PDO::PARAM_LOB` (int)
  Represents the SQL large object data type.
`PDO::PARAM_STMT` (int)
  Represents a recordset type. Not currently supported by any drivers.
`PDO::PARAM_INPUT_OUTPUT` (int)
  Specifies that the parameter is an INOUT parameter for a stored procedure. This constant must be bitwise-ORed with one of the `PDO::PARAM_*` constants.
`PDO::ATTR_AUTOCOMMIT` (int)
  If this value is `false`, PDO attempts to disable autocommit so that the connection begins a transaction.
`PDO::ATTR_PREFETCH` (int)
  Setting the prefetch size allows balancing speed against memory usage for an application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
`PDO::ATTR_TIMEOUT` (int)
  Sets the timeout value in seconds for communications with the database.
`PDO::ATTR_ERRMODE` (int)
  See the Errors and error handling section for more information about this attribute.
`PDO::ATTR_SERVER_VERSION` (int)
  This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
`PDO::ATTR_CLIENT_VERSION` (int)
  This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
`PDO::ATTR_SERVER_INFO` (int)
  This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
`PDO::ATTR_CONNECTION_STATUS` (int)
`PDO::ATTR_CASE` (int)
  Force column names to a specific case specified by the `PDO::CASE_*` constants.
`PDO::ATTR_CURSOR_NAME` (int)
  Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
`PDO::ATTR_CURSOR` (int)
  Selects the cursor type. PDO currently supports either `PDO::CURSOR_FWDONLY` or `PDO::CURSOR_SCROLL`. Unless one has a need for scrollable cursors, one should use the `PDO::CURSOR_FWDONLY` cursor mode.
`PDO::ATTR_DRIVER_NAME` (int)
  Returns the name of the driver.

  Example #1 using `PDO::ATTR_DRIVER_NAME`

  `<?php
  if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
  }
  ?>`
`PDO::ATTR_ORACLE_NULLS` (int)
  Convert empty strings to SQL NULL values on data fetches.
`PDO::ATTR_PERSISTENT` (int)
  Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
`PDO::ATTR_STATEMENT_CLASS` (int)
  Sets the class name of which statements are returned as.
`PDO::ATTR_FETCH_CATALOG_NAMES` (int)
  Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by the driver in use.
`PDO::ATTR_FETCH_TABLE_NAMES` (int)
  Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by the driver in use.
`PDO::ATTR_STRINGIFY_FETCHES` (int)
  Forces all fetched values (except `null`) to be treated as strings. `null` values remain unchanged unless `PDO::ATTR_ORACLE_NULLS` is set to `PDO::NULL_TO_STRING`.
`PDO::ATTR_MAX_COLUMN_LEN` (int)
  Sets the maximum column name length.
`PDO::ATTR_DEFAULT_FETCH_MODE` (int)
`PDO::ATTR_EMULATE_PREPARES` (int)
`PDO::ATTR_DEFAULT_STR_PARAM` (int)
  Sets the default string parameter type, this can be one of `PDO::PARAM_STR_NATL` and `PDO::PARAM_STR_CHAR`. Available as of PHP 7.2.0.
`PDO::ERRMODE_SILENT` (int)
  Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. Prior to PHP 8.0.0, this was the default mode. See Errors and error handling for more information about this attribute.
`PDO::ERRMODE_WARNING` (int)
  Issue a PHP `E_WARNING` message if an error occurs. See Errors and error handling for more information about this attribute.
`PDO::ERRMODE_EXCEPTION` (int)
  Throw a PDOException if an error occurs. This is the default mode as of PHP 8.0.0. See Errors and error handling for more information about this attribute.
`PDO::CASE_NATURAL` (int)
  Leave column names as returned by the database driver.
`PDO::CASE_LOWER` (int)
  Force column names to lower case.
`PDO::CASE_UPPER` (int)
  Force column names to upper case.
`PDO::NULL_NATURAL` (int)
`PDO::NULL_EMPTY_STRING` (int)
`PDO::NULL_TO_STRING` (int)
`PDO::ERR_NONE` (string)
  Corresponds to SQLSTATE `'00000'`, meaning that the SQL statement was successfully issued with no errors or warnings. This constant is a convenience constant to help when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. This is usually known by examining the return code from the method that raised the error condition anyway.
`PDO::PARAM_EVT_ALLOC` (int)
  Allocation event
`PDO::PARAM_EVT_FREE` (int)
  Deallocation event
`PDO::PARAM_EVT_EXEC_PRE` (int)
  Event triggered prior to execution of a prepared statement.
`PDO::PARAM_EVT_EXEC_POST` (int)
  Event triggered subsequent to execution of a prepared statement.
`PDO::PARAM_EVT_FETCH_PRE` (int)
  Event triggered prior to fetching a result from a resultset.
`PDO::PARAM_EVT_FETCH_POST` (int)
  Event triggered subsequent to fetching a result from a resultset.
`PDO::PARAM_EVT_NORMALIZE` (int)
  Event triggered during bound parameter registration allowing the driver to normalize the parameter name.
`PDO::SQLITE_DETERMINISTIC` (int)
  Specifies that a function created with PDO::sqliteCreateFunction() is deterministic, i.e. it always returns the same result given the same inputs within a single SQL statement. (Available as of PHP 7.1.4.)

# Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Example #1 Connecting to MySQL

`<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>`

If there are any connection errors, a `PDOException` object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Example #2 Handling connection errors

`<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
// attempt to retry the connection after some timeout for example
}`
Warning

Just like any other exception, PDOException could be caught either explicitly, via a `catch` statement, or implicitly via set_exception_handler(). Otherwise, the default behaviour of converting an uncaught exception to a `E_FATAL_ERROR` will occur. The fatal error will contain a backtrace that can leak connection details. As such, the php.ini option `display_errors` should be set to `0` on a production server.

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning `null` to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

> Note: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from other variables referencing the same PDO instance), these have to be removed also (for instance, by assigning `null` to the variable that references the PDOStatement).

Example #3 Closing a connection

`<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here
$sth = $dbh->query('SELECT * FROM foo');
// and now we're done; close it
$sth = null;
$dbh = null;
?>`

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Example #4 Persistent connections

`<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>`

The value of the `PDO::ATTR_PERSISTENT` option is converted to bool (enable/disable persistent connections), unless it is a non-numeric string, in which case it allows to use multiple persistent connection pools. This is useful if different connections use incompatible settings, for instance, different values of `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY`.

> Note:

> If you wish to use persistent connections, you must set `PDO::ATTR_PERSISTENT` in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

Warning

PDO does not perform any cleanup of persistent connections. Temporary tables, locks, transactions and other stateful changes may remain from previous usage of the connection, causing unexpected problems. See the Persistent Database Connections section for more information.

> Note:

> If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

# Transactions and auto-commit

Now that you're connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.

Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).

Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO::commit() or PDO::rollBack() to finish it, depending on the success of the code you run during the transaction.

Warning

PDO only checks for transaction capabilities on driver level. If certain runtime conditions mean that transactions are unavailable, PDO::beginTransaction() will still return `true` without error if the database server accepts the request to start a transaction.

An example of this would be trying to use transactions on MyISAM tables on a MySQL database.

Warning

Implicit Commits with DDL Statements: Some databases automatically issue an implicit `COMMIT` when a database definition language (DDL) statement, such as `DROP TABLE` or `CREATE TABLE`, is executed within a transaction. This means that any prior changes made within the same transaction will be automatically committed and cannot be rolled back.

`MySQL` and `Oracle` are example databases that exhibit this behavior.

Example #1 Implicit Commit Example

`<?php
$pdo->beginTransaction();
$pdo->exec("INSERT INTO users (name) VALUES ('Rasmus')");
$pdo->exec("CREATE TABLE test (id INT PRIMARY KEY)"); // Implicit COMMIT occurs here
$pdo->rollBack(); // This will NOT undo the INSERT/CREATE for MySQL or Oracle
?>`

Best Practice: Avoid executing DDL statements inside transactions if using databases that enforce this behavior. If necessary, separate DDL operations from transactional logic.

When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.

Warning

The automatic rollback only happens if you initiate the transaction via PDO::beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens.

Example #2 Executing a batch in a transaction

In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO::beginTransaction() and PDO::commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.

`<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>`

You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. For further reading on transactions, refer to the documentation provided by your database server.

# Prepared statements and stored procedures

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

- The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
- The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that an application will be able to use the same data access paradigm regardless of the capabilities of the database.

Example #1 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a `name` and a `value` for the named placeholders.

`<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>`

Example #2 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a `name` and a `value` for the positional `?` placeholders.

`<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>`

Example #3 Fetching data using prepared statements

This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.

`<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
$stmt->execute([$_GET['name']]);
foreach ($stmt as $row) {
print_r($row);
}
?>`

Example #4 Calling a stored procedure with an output parameter

If the database driver supports it, an application may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that a developer must know how large a given parameter might be when they bind it. If the value turns out to be larger than the size they suggested, an error is raised.

`<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>`

Example #5 Calling a stored procedure with an input/output parameter

Developers may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.

`<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
?>`

Example #6 Invalid use of placeholder

`<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute([$_GET['name']]);
// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(["%$_GET[name]%"]);
?>`

# Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

- `PDO::ERRMODE_SILENT`

  Prior to PHP 8.0.0, this was the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

- `PDO::ERRMODE_WARNING`

  In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.

- `PDO::ERRMODE_EXCEPTION`

  As of PHP 8.0.0, this is the default mode. In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

  Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

  See Exceptions for more information about Exceptions in PHP.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Example #1 Create a PDO instance and set the error mode

`<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This will cause PDO to throw a PDOException (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");`

The above example will output:

    Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testdb.wrongtable' doesn't exist in /tmp/pdo_test.php:10
    Stack trace:
    #0 /tmp/pdo_test.php(10): PDO->query('SELECT wrongcol...')
    #1 {main}
      thrown in /tmp/pdo_test.php on line 10

> Note:

> PDO::__construct() will always throw a PDOException if the connection fails regardless of which `PDO::ATTR_ERRMODE` is currently set.

Example #2 Create a PDO instance and set the error mode from the constructor

`<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");`

The above example will output:

    Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
    /tmp/pdo_test.php on line 9

# Large Objects (LOBs)

At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the `PDO::PARAM_LOB` type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. `PDO::PARAM_LOB` tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

Example #1 Displaying an image from a database

This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.

`<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: $type");
fpassthru($lob);
?>`

Example #2 Inserting an image into a database

This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.

`<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$db->beginTransaction();
$stmt->execute();
$db->commit();
?>`

Example #3 Inserting an image into a database: Oracle

Oracle requires a slightly different syntax for inserting a lob from a file. It's also essential that you perform the insert under a transaction, otherwise your newly inserted LOB will be committed with a zero-length as part of the implicit commit that happens when the query is executed:

`<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$db->beginTransaction();
$stmt->execute();
$db->commit();
?>`

# The PDO class

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

## Introduction

Represents a connection between PHP and a database server.

## Class synopsis

class PDO {
/* Constants */
public const int PARAM_NULL;
public const int PARAM_BOOL = 5;
public const int PARAM_INT = 1;
public const int PARAM_STR = 2;
public const int PARAM_LOB = 3;
public const int PARAM_STMT = 4;
public const int PARAM_INPUT_OUTPUT;
public const int PARAM_STR_NATL;
public const int PARAM_STR_CHAR;
public const int PARAM_EVT_ALLOC;
public const int PARAM_EVT_FREE;
public const int PARAM_EVT_EXEC_PRE;
public const int PARAM_EVT_EXEC_POST;
public const int PARAM_EVT_FETCH_PRE;
public const int PARAM_EVT_FETCH_POST;
public const int PARAM_EVT_NORMALIZE;
public const int FETCH_DEFAULT;
public const int FETCH_LAZY;
public const int FETCH_ASSOC;
public const int FETCH_NUM;
public const int FETCH_BOTH;
public const int FETCH_OBJ;
public const int FETCH_BOUND;
public const int FETCH_COLUMN;
public const int FETCH_CLASS;
public const int FETCH_INTO;
public const int FETCH_FUNC;
public const int FETCH_GROUP;
public const int FETCH_UNIQUE;
public const int FETCH_KEY_PAIR;
public const int FETCH_CLASSTYPE;
public const int FETCH_SERIALIZE;
public const int FETCH_PROPS_LATE;
public const int FETCH_NAMED;
public const int ATTR_AUTOCOMMIT;
public const int ATTR_PREFETCH;
public const int ATTR_TIMEOUT;
public const int ATTR_ERRMODE;
public const int ATTR_SERVER_VERSION;
public const int ATTR_CLIENT_VERSION;
public const int ATTR_SERVER_INFO;
public const int ATTR_CONNECTION_STATUS;
public const int ATTR_CASE;
public const int ATTR_CURSOR_NAME;
public const int ATTR_CURSOR;
public const int ATTR_ORACLE_NULLS;
public const int ATTR_PERSISTENT;
public const int ATTR_STATEMENT_CLASS;
public const int ATTR_FETCH_TABLE_NAMES;
public const int ATTR_FETCH_CATALOG_NAMES;
public const int ATTR_DRIVER_NAME;
public const int ATTR_STRINGIFY_FETCHES;
public const int ATTR_MAX_COLUMN_LEN;
public const int ATTR_EMULATE_PREPARES;
public const int ATTR_DEFAULT_FETCH_MODE;
public const int ATTR_DEFAULT_STR_PARAM;
public const int ERRMODE_SILENT;
public const int ERRMODE_WARNING;
public const int ERRMODE_EXCEPTION;
public const int CASE_NATURAL;
public const int CASE_LOWER;
public const int CASE_UPPER;
public const int NULL_NATURAL;
public const int NULL_EMPTY_STRING;
public const int NULL_TO_STRING;
public const string ERR_NONE;
public const int FETCH_ORI_NEXT;
public const int FETCH_ORI_PRIOR;
public const int FETCH_ORI_FIRST;
public const int FETCH_ORI_LAST;
public const int FETCH_ORI_ABS;
public const int FETCH_ORI_REL;
public const int CURSOR_FWDONLY;
public const int CURSOR_SCROLL;
/* Methods */
public __construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public beginTransaction(): bool
public commit(): bool
public static connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public errorCode(): ?string
public errorInfo(): array
public exec(string `$statement`): int|false
public getAttribute(int `$attribute`): mixed
public static getAvailableDrivers(): array
public inTransaction(): bool
public lastInsertId(?string `$name` = `null`): string|false
public prepare(string `$query`, array `$options` = []): PDOStatement|false
public query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public rollBack(): bool
public setAttribute(int `$attribute`, mixed `$value`): bool
}

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# PDO::beginTransaction

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

### Description

public PDO::beginTransaction(): bool

Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollBack() will roll back all changes to the database and return the connection to autocommit mode.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws a PDOException if there is already a transaction started or the driver does not support transactions.

> Note: An exception is raised even when the `PDO::ATTR_ERRMODE` attribute is not `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

`<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>`

### See Also

- PDO::commit() - Commits a transaction
- PDO::rollBack() - Rolls back a transaction
- Transactions and auto-commit

# PDO::commit

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

### Description

public PDO::commit(): bool

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws a PDOException if there is no active transaction.

> Note: An exception is raised even when the `PDO::ATTR_ERRMODE` attribute is not `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Committing a basic transaction

`<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Insert multiple records on an all-or-nothing basis */
$sql = 'INSERT INTO fruit
(name, colour, calories)
VALUES (?, ?, ?)';
$sth = $dbh->prepare($sql);
foreach ($fruits as $fruit) {
$sth->execute(array(
$fruit->name,
$fruit->colour,
$fruit->calories,
));
}
/* Commit the changes */
$dbh->commit();
/* Database connection is now back in autocommit mode */
?>`

Example #2 Committing a DDL transaction

`<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");
/* Commit the changes */
$dbh->commit();
/* Database connection is now back in autocommit mode */
?>`

> Note: Not all databases will allow transactions to operate on DDL statements: some will generate errors, whereas others (including MySQL) will automatically commit the transaction after the first DDL statement has been encountered.

### See Also

- PDO::beginTransaction() - Initiates a transaction
- PDO::rollBack() - Rolls back a transaction
- Transactions and auto-commit

# PDO::connect

(PHP 8 >= 8.4.0)

PDO::connect — Connect to a database and return a PDO subclass for drivers that support it

### Description

public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static

Creates an instance of a PDO subclass for the database being connection if it exists, otherwise return a generic PDO instance.

### Parameters

`dsn`

  The Data Source Name, or DSN, contains the information required to connect to the database.

  In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

  The `dsn` parameter supports three different methods of specifying the arguments required to create a database connection:

  Driver invocation

    `dsn` contains the full DSN.

  URI invocation

    `dsn` consists of `uri:` followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

    `uri:file:///path/to/dsnfile`

  Aliasing

    `dsn` consists of a name `name` that maps to `pdo.dsn.`name`` in php.ini defining the DSN string.

    > Note:

    > The alias must be defined in php.ini, and not .htaccess or httpd.conf

`username`

  The user name for the DSN string. This parameter is optional for some PDO drivers.

`password`

  The password for the DSN string. This parameter is optional for some PDO drivers.

`options`

  A key=>value array of driver-specific connection options.

### Return Values

Returns an instance of a PDO subclass for the corresponding PDO driver if it exists, or a generic PDO instance.

### Errors/Exceptions

A PDOException is thrown if the attempt to connect to the requested database fails, regardless of which `PDO::ATTR_ERRMODE` is currently set.

### See Also

- Pdo\Dblib
- Pdo\Firebird
- Pdo\Mysql
- Pdo\Odbc
- Pdo\Pgsql
- Pdo\Sqlite
- PDO::__construct() - Creates a PDO instance representing a connection to a database

# PDO::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::__construct — Creates a PDO instance representing a connection to a database

### Description

public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)

Creates a PDO instance to represent a connection to the requested database.

### Parameters

`dsn`

  The Data Source Name, or DSN, contains the information required to connect to the database.

  In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

  The `dsn` parameter supports three different methods of specifying the arguments required to create a database connection:

  Driver invocation

    `dsn` contains the full DSN.

  URI invocation

    `dsn` consists of `uri:` followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

    `uri:file:///path/to/dsnfile`

  Aliasing

    `dsn` consists of a name `name` that maps to `pdo.dsn.`name`` in php.ini defining the DSN string.

    > Note:

    > The alias must be defined in php.ini, and not .htaccess or httpd.conf

`username`

  The user name for the DSN string. This parameter is optional for some PDO drivers.

`password`

  The password for the DSN string. This parameter is optional for some PDO drivers.

`options`

  A key=>value array of driver-specific connection options.

### Errors/Exceptions

A PDOException is thrown if the attempt to connect to the requested database fails, regardless of which `PDO::ATTR_ERRMODE` is currently set.

### Examples

Example #1 Create a PDO instance via driver invocation

`<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
?>`

Example #2 Create a PDO instance via URI invocation

The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

    odbc:DSN=SAMPLE;UID=john;PWD=mypass

The PHP script can then create a database connection by simply passing the `uri:` parameter and pointing to the file URI:

`<?php
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';
$dbh = new PDO($dsn, $user, $password);
?>`

Example #3 Create a PDO instance using an alias

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias `mydb`:

    [PDO]
    pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"

`<?php
$dsn = 'mydb';
$user = '';
$password = '';
$dbh = new PDO($dsn, $user, $password);
?>`

# PDO::errorCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

### Description

public PDO::errorCode(): ?string

### Parameters

This function has no parameters.

### Return Values

Returns an SQLSTATE, a five characters alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two characters class value followed by a three characters subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.

PDO::errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorCode() will not reflect that error. You must call PDOStatement::errorCode() to return the error code for an operation performed on a particular statement handle.

Returns `null` if no operation has been run on the database handle.

### Examples

Example #1 Retrieving an SQLSTATE code

`<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");
echo "\nPDO::errorCode(): ", $dbh->errorCode();
?>`

The above example will output:

    PDO::errorCode(): 42S02

### See Also

- PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
- PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
- PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

# PDO::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

### Description

public PDO::errorInfo(): array

### Parameters

This function has no parameters.

### Return Values

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of at least the following fields:

Element | Information
--- | ---
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

> Note:

> If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to `null`.

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.

### Examples

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

`<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
?>`

The above example will output:

    PDO::errorInfo():
    Array
    (
        [0] => HY000
        [1] => 1
        [2] => near "bogus": syntax error
    )

### See Also

- PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
- PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
- PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

# PDO::exec

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::exec — Execute an SQL statement and return the number of affected rows

### Description

public PDO::exec(string `$statement`): int|false

PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.

PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().

### Parameters

`statement`

  The SQL statement to prepare and execute.

  Data inside the query should be properly escaped.

### Return Values

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns `0`.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

The following example incorrectly relies on the return value of PDO::exec(), wherein a statement that affected 0 rows results in a call to die():

`<?php
$db->exec() or die(print_r($db->errorInfo(), true)); // incorrect
?>`

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

`<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
/* Delete all rows from the FRUIT table */
$count = $dbh->exec("DELETE FROM fruit");
/* Return number of rows that were deleted */
print "Deleted $count rows.\n";
?>`

The above example will output:

    Deleted 1 rows.

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDO::query() - Prepares and executes an SQL statement without placeholders
- PDOStatement::execute() - Executes a prepared statement

# PDO::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

### Description

public PDO::getAttribute(int `$attribute`): mixed

This function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().

Note that some database/driver combinations may not support all of the database connection attributes.

### Parameters

`attribute`

  One of the `PDO::ATTR_*` constants. The generic attributes that apply to database connections are as follows:

  - `PDO::ATTR_AUTOCOMMIT`
  - `PDO::ATTR_CASE`
  - `PDO::ATTR_CLIENT_VERSION`
  - `PDO::ATTR_CONNECTION_STATUS`
  - `PDO::ATTR_DRIVER_NAME`
  - `PDO::ATTR_ERRMODE`
  - `PDO::ATTR_ORACLE_NULLS`
  - `PDO::ATTR_PERSISTENT`
  - `PDO::ATTR_PREFETCH`
  - `PDO::ATTR_SERVER_INFO`
  - `PDO::ATTR_SERVER_VERSION`
  - `PDO::ATTR_TIMEOUT`
  Some drivers may make use of additional driver specific attributes. Note that driver specific attributes must not be used with other drivers.

### Return Values

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns `null`.

### Errors/Exceptions

PDO::getAttribute() may throw a PDOException when the underlying driver does not support the requested `attribute`.

### Examples

Example #1 Retrieving database connection attributes

`<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
"AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
"ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
"TIMEOUT"
);
foreach ($attributes as $val) {
echo "PDO::ATTR_$val: ";
echo $conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>`

### See Also

- PDO::setAttribute() - Set an attribute
- PDOStatement::getAttribute() - Retrieve a statement attribute
- PDOStatement::setAttribute() - Set a statement attribute

# PDO::getAvailableDrivers

# pdo_drivers

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers -- pdo_drivers — Return an array of available PDO drivers

### Description

public static PDO::getAvailableDrivers(): array
pdo_drivers(): array

This function returns all currently available PDO drivers which can be used in `DSN` parameter of PDO::__construct().

### Parameters

This function has no parameters.

### Return Values

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

### Examples

Example #1 A PDO::getAvailableDrivers() example

`<?php
print_r(PDO::getAvailableDrivers());
?>`

The above example will output something similar to:

    Array
    (
        [0] => mysql
        [1] => sqlite
    )

# PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql, PHP 7, PHP 8)

PDO::inTransaction — Checks if inside a transaction

### Description

public PDO::inTransaction(): bool

Checks if a transaction is currently active within the driver. This method only works for database drivers that support transactions.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if a transaction is currently active, and `false` if not.

# PDO::lastInsertId

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value

### Description

public PDO::lastInsertId(?string `$name` = `null`): string|false

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL allows the name of any sequence object to be specified for the `name` parameter.

> Note:

> This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

### Parameters

`name`

  Name of the sequence object from which the ID should be returned.

### Return Values

If a sequence name was not specified for the `name` parameter, PDO::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.

If a sequence name was specified for the `name` parameter, PDO::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.

If the PDO driver does not support this capability, PDO::lastInsertId() triggers an `IM001` SQLSTATE.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

# PDO::prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PHP 8,PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

### Description

public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false

Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. Both named and question mark parameter markers cannot be used within the same statement template; only one or the other parameter style. Use these parameters to bind any user-input, do not include the user-input directly in the query.

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

> Note:

> Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in the IN() clause of an SQL statement.

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information. Also, calling PDO::prepare() and PDOStatement::execute() helps to prevent SQL injection attacks by eliminating the need to manually quote and escape the parameters.

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

> Note: The parser used for emulated prepared statements and for rewriting named or question mark style parameters supports the non standard backslash escapes for single- and double quotes. That means that terminating quotes immediately preceeded by a backslash are not recognized as such, which may result in wrong detection of parameters causing the prepared statement to fail when it is executed. A work-around is to not use emulated prepares for such SQL queries, and to avoid rewriting of parameters by using a parameter style which is natively supported by the driver.

As of PHP 7.4.0, question marks can be escaped by doubling them. That means that the `??` string will be translated to `?` when sending the query to the database.

### Parameters

`query`

  This must be a valid SQL statement template for the target database server.

`options`

  This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the `PDO::ATTR_CURSOR` value to `PDO::CURSOR_SCROLL` to request a scrollable cursor. Some drivers have driver-specific options that may be set at prepare-time.

### Return Values

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns `false` or emits PDOException (depending on error handling).

> Note:

> Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 SQL statement template with named parameters

`<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute(['calories' => 150, 'colour' => 'red']);
$red = $sth->fetchAll();
/* Array keys can be prefixed with colons ":" too (optional) */
$sth->execute([':calories' => 175, ':colour' => 'yellow']);
$yellow = $sth->fetchAll();
?>`

Example #2 SQL statement template with question mark parameters

`<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute([150, 'red']);
$red = $sth->fetchAll();
$sth->execute([175, 'yellow']);
$yellow = $sth->fetchAll();
?>`

Example #3 SQL statement template with question mark escaped

`<?php
/* note: this is only valid on PostgreSQL databases */
$sth = $dbh->prepare('SELECT * FROM issues WHERE tag::jsonb ?? ?');
$sth->execute(['feature']);
$featureIssues = $sth->fetchAll();
$sth->execute(['performance']);
$performanceIssues = $sth->fetchAll();
?>`

### See Also

- PDO::exec() - Execute an SQL statement and return the number of affected rows
- PDO::query() - Prepares and executes an SQL statement without placeholders
- PDOStatement::execute() - Executes a prepared statement

# PDO::query

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::query — Prepares and executes an SQL statement without placeholders

### Description

public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().

If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().

> Note:

> If the `query` contains placeholders, the statement must be prepared and executed separately using PDO::prepare() and PDOStatement::execute() methods.

### Parameters

`query`

  The SQL statement to prepare and execute.

  If the SQL contains placeholders, PDO::prepare() and PDOStatement::execute() must be used instead. Alternatively, the SQL can be prepared manually before calling PDO::query(), with the data properly formatted using PDO::quote() if the driver supports it.

`fetchMode`

  The default fetch mode for the returned PDOStatement. It must be one of the `PDO::FETCH_*` constants.

  If this argument is passed to the function, the remaining arguments will be treated as though PDOStatement::setFetchMode() was called on the resultant statement object. The subsequent arguments vary depending on the selected fetch mode.

### Return Values

Returns a PDOStatement object or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 SQL with no placeholders can be executed using PDO::query()

`<?php
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
?>`

The above example will output:

    apple   red     150
    banana  yellow  250
    kiwi    brown   75
    lemon   yellow  25
    orange  orange  300
    pear    green   150
    watermelon      pink    90

### See Also

- PDO::exec() - Execute an SQL statement and return the number of affected rows
- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement

# PDO::quote

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query

### Description

public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false

PDO::quote() places quotes around the input string and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Caution

# Security: the default character set

The character set must be set either on the server level, or within the database connection itself (depending on the driver) for it to affect PDO::quote(). See the driver-specific documentation for more information.

### Parameters

`string`

  The string to be quoted.

`type`

  Provides a hint to the type of data for drivers that have alternate quoting styles. For example `PDO_PARAM_LOB` will tell the driver to escape binary data.

### Return Values

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns `false` if the driver does not support quoting in this way.

### Examples

Example #1 Quoting a normal string

`<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>`

The above example will output:

    Unquoted string: Nice
    Quoted string: 'Nice'

Example #2 Quoting a dangerous string

`<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>`

The above example will output:

    Unquoted string: Naughty ' string
    Quoted string: 'Naughty '' string'

Example #3 Quoting a complex string

`<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>`

The above example will output:

    Unquoted string: Co'mpl''ex "st'"ring
    Quoted string: 'Co''mpl''''ex "st''"ring'

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement

# PDO::rollBack

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

### Description

public PDO::rollBack(): bool

Rolls back the current transaction, as initiated by PDO::beginTransaction().

If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws a PDOException if there is no active transaction.

> Note: An exception is raised even when the `PDO::ATTR_ERRMODE` attribute is not `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

`<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>`

### See Also

- PDO::beginTransaction() - Initiates a transaction
- PDO::commit() - Commits a transaction
- Transactions and auto-commit

# PDO::setAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

### Description

public PDO::setAttribute(int `$attribute`, mixed `$value`): bool

Sets an attribute on the database handle. Some available generic attributes are listed below; some drivers may make use of additional driver specific attributes. Note that driver specific attributes must not be used with other drivers.

`PDO::ATTR_CASE`

  Force column names to a specific case. Can take one of the following values:

  `PDO::CASE_LOWER`
    Force column names to lower case.
  `PDO::CASE_NATURAL`
    Leave column names as returned by the database driver.
  `PDO::CASE_UPPER`
    Force column names to upper case.
`PDO::ATTR_ERRMODE`

  Error reporting mode of PDO. Can take one of the following values:

  `PDO::ERRMODE_SILENT`
    Only sets error codes.
  `PDO::ERRMODE_WARNING`
    Raises `E_WARNING` diagnostics.
  `PDO::ERRMODE_EXCEPTION`
    Throws PDOExceptions.
`PDO::ATTR_ORACLE_NULLS`

  > Note: This attribute is available with all drivers, not just Oracle.

  Determines if and how `null` and empty strings should be converted. Can take one of the following values:

  `PDO::NULL_NATURAL`
    No conversion takes place.
  `PDO::NULL_EMPTY_STRING`
    Empty strings get converted to `null`.
  `PDO::NULL_TO_STRING`
    `null` gets converted to an empty string.
`PDO::ATTR_STRINGIFY_FETCHES`

  Controls whether fetched values (except `null`) are converted to strings. Takes a value of type bool: `true` to enable and `false` to disable (default). `null` values remain unchanged unless `PDO::ATTR_ORACLE_NULLS` is set to `PDO::NULL_TO_STRING`.

`PDO::ATTR_STATEMENT_CLASS`

  Set user-supplied statement class derived from PDOStatement. Requires `array(string classname, array(mixed constructor_args))`.

  Caution

  Cannot be used with persistent PDO instances.

`PDO::ATTR_TIMEOUT`

  Specifies the timeout duration in seconds. Takes a value of type int.

  > Note:

  > Not all drivers support this option, and its meaning may differ from driver to driver. For example, SQLite will wait for up to this time value before giving up on obtaining a writable lock, but other drivers may interpret this as a connection or a read timeout interval.

`PDO::ATTR_AUTOCOMMIT`

  > Note: Only available for the OCI, Firebird, and MySQL drivers.

  Whether to autocommit every single statement. Takes a value of type bool: `true` to enable and `false` to disable. By default, `true`.

`PDO::ATTR_EMULATE_PREPARES`

  > Note: Only available for the OCI, Firebird, and MySQL drivers.

  Whether enable or disable emulation of prepared statements. Some drivers do not support prepared statements natively or have limited support for them. If set to `true` PDO will always emulate prepared statements, otherwise PDO will attempt to use native prepared statements. In case the driver cannot successfully prepare the current query, PDO will always fall back to emulating the prepared statement.

`PDO::MYSQL_ATTR_USE_BUFFERED_QUERY`

  > Note: Only available for the MySQL driver.

  Whether to use buffered queries. Takes a value of type bool: `true` to enable and `false` to disable. By default, `true`.

`PDO::ATTR_DEFAULT_FETCH_MODE`

  Set the default fetch mode. A description of the modes and how to use them is available in the PDOStatement::fetch() documentation.

### Parameters

`attribute`

  The attribute to modify.

`value`

  The value to set the `attribute`, might require a specific type depending on the attribute.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- PDO::getAttribute() - Retrieve a database connection attribute
- PDOStatement::getAttribute() - Retrieve a statement attribute
- PDOStatement::setAttribute() - Set a statement attribute

## Table of Contents

- PDO::beginTransaction — Initiates a transaction
- PDO::commit — Commits a transaction
- PDO::connect — Connect to a database and return a PDO subclass for drivers that support it
- PDO::__construct — Creates a PDO instance representing a connection to a database
- PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
- PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
- PDO::exec — Execute an SQL statement and return the number of affected rows
- PDO::getAttribute — Retrieve a database connection attribute
- PDO::getAvailableDrivers — Return an array of available PDO drivers
- PDO::inTransaction — Checks if inside a transaction
- PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
- PDO::prepare — Prepares a statement for execution and returns a statement object
- PDO::query — Prepares and executes an SQL statement without placeholders
- PDO::quote — Quotes a string for use in a query
- PDO::rollBack — Rolls back a transaction
- PDO::setAttribute — Set an attribute

# The PDOStatement class

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

## Introduction

Represents a prepared statement and, after the statement is executed, an associated result set.

## Class synopsis

class PDOStatement implements IteratorAggregate {
/* Properties */
public string $queryString;
/* Methods */
public bindColumn(
string|int `$column`,
mixed `&$var`,
int `$type` = `PDO::PARAM_STR`,
int `$maxLength` = 0,
mixed `$driverOptions` = `null`
): bool
public bindParam(
string|int `$param`,
mixed `&$var`,
int `$type` = `PDO::PARAM_STR`,
int `$maxLength` = 0,
mixed `$driverOptions` = `null`
): bool
public bindValue(string|int `$param`, mixed `$value`, int `$type` = `PDO::PARAM_STR`): bool
public closeCursor(): bool
public columnCount(): int
public debugDumpParams(): ?bool
public errorCode(): ?string
public errorInfo(): array
public execute(?array `$params` = `null`): bool
public fetch(int `$mode` = `PDO::FETCH_DEFAULT`, int `$cursorOrientation` = `PDO::FETCH_ORI_NEXT`, int `$cursorOffset` = 0): mixed
public fetchAll(int `$mode` = PDO::FETCH_DEFAULT): array
public fetchAll(int `$mode` = PDO::FETCH_COLUMN, int `$column`): array
public fetchAll(int `$mode` = PDO::FETCH_CLASS, string `$class`, ?array `$constructorArgs`): array
public fetchAll(int `$mode` = PDO::FETCH_FUNC, callable `$callback`): array
public fetchColumn(int `$column` = 0): mixed
public fetchObject(?string `$class` = "stdClass", array `$constructorArgs` = []): object|false
public getAttribute(int `$name`): mixed
public getColumnMeta(int `$column`): array|false
public getIterator(): Iterator
public nextRowset(): bool
public rowCount(): int
public setAttribute(int `$attribute`, mixed `$value`): bool
public setFetchMode(int `$mode`): bool
public setFetchMode(int `$mode` = PDO::FETCH_COLUMN, int `$colno`): bool
public setFetchMode(int `$mode` = PDO::FETCH_CLASS, string `$class`, ?array `$constructorArgs` = `null`): bool
public setFetchMode(int `$mode` = PDO::FETCH_INTO, object `$object`): bool
}

## Properties

queryString

  Used query string.

## Changelog

Version | Description
--- | ---
8.0.0 | PDOStatement implements IteratorAggregate now instead of Traversable.

# PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

### Description

public PDOStatement::bindColumn(
string|int `$column`,
mixed `&$var`,
int `$type` = `PDO::PARAM_STR`,
int `$maxLength` = 0,
mixed `$driverOptions` = `null`
): bool

PDOStatement::bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all the variables that are bound to columns.

> Note:

> Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDOStatement::execute().

> However, to be able to bind a LOB column as a stream when using the PgSQL driver, applications should call this method before calling PDOStatement::execute(), otherwise the large object OID will be returned as an integer.

### Parameters

`column`

  Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.

`var`

  Name of the PHP variable to which the column will be bound.

`type`

  Data type of the parameter, specified by the `PDO::PARAM_*` constants.

`maxLength`

  A hint for pre-allocation.

`driverOptions`

  Optional parameter(s) for the driver.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Binding result set output to PHP variables

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.

`<?php
$stmt = $dbh->prepare('SELECT name, colour, calories FROM fruit');
$stmt->execute();
/* Bind by column number */
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $colour);
/* Bind by column name */
$stmt->bindColumn('calories', $cals);
while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $colour . "\t" . $cals . "\n";
}`

The above example will output something similar to:

    apple   red     150
    banana  yellow  175
    kiwi    green   75
    orange  orange  150
    mango   red     200
    strawberry      red     25

### See Also

- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::fetch() - Fetches the next row from a result set
- PDOStatement::fetchAll() - Fetches the remaining rows from a result set
- PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

# PDOStatement::bindParam

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

### Description

public PDOStatement::bindParam(
string|int `$param`,
mixed `&$var`,
int `$type` = `PDO::PARAM_STR`,
int `$maxLength` = 0,
mixed `$driverOptions` = `null`
): bool

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query (but may nonetheless be cast according to `type`). Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

### Parameters

`param`

  Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

`var`

  Name of the PHP variable to bind to the SQL statement parameter.

`type`

  Explicit data type for the parameter using the `PDO::PARAM_*` constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the `PDO::PARAM_INPUT_OUTPUT` bits for the `type` parameter.

`maxLength`

  Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length. Meaningful only when `type` parameter is `PDO::PARAM_INPUT_OUTPUT`.

`driverOptions`

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Execute a prepared statement with named placeholders

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
/* Names can be prefixed with colons ":" too (optional) */
$sth->bindParam(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>`

Example #2 Execute a prepared statement with question mark placeholders

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>`

Example #3 Call a stored procedure with an INOUT parameter

`<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print "After pureeing fruit, the colour is: $colour";
?>`

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::bindValue() - Binds a value to a parameter

# PDOStatement::bindValue

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

### Description

public PDOStatement::bindValue(string|int `$param`, mixed `$value`, int `$type` = `PDO::PARAM_STR`): bool

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.

### Parameters

`param`

  Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

`value`

  The value to bind to the parameter.

`type`

  Explicit data type for the parameter using the `PDO::PARAM_*` constants.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Execute a prepared statement with named placeholders

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
/* Sets a parameter value using its name */
$sth->bindValue('calories', $calories, PDO::PARAM_INT);
/* Optionally, parameter names can also be prefixed with colons ":" */
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>`

Example #2 Execute a prepared statement with question mark placeholders

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>`

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::bindParam() - Binds a parameter to the specified variable name

# PDOStatement::closeCursor

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again

### Description

public PDOStatement::closeCursor(): bool

PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.

PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:

`<?php
do {
while ($stmt->fetch())
;
if (!$stmt->nextRowset())
break;
} while (true);
?>`

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 A PDOStatement::closeCursor() example

In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement::closeCursor() on $stmt before executing the $otherStmt PDOStatement object.

`<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');
/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');
/* Execute the first statement */
$stmt->execute();
/* Fetch only the first row from the results */
$stmt->fetch();
/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();
/* Now we can execute the second statement */
$otherStmt->execute();
?>`

### See Also

- PDOStatement::execute() - Executes a prepared statement

# PDOStatement::columnCount

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

### Description

public PDOStatement::columnCount(): int

Use PDOStatement::columnCount() to return the number of columns in the result set represented by the PDOStatement object.

If the PDOStatement object was returned from PDO::query(), the column count is immediately available.

If the PDOStatement object was returned from PDO::prepare(), an accurate column count will not be available until you invoke PDOStatement::execute().

### Parameters

This function has no parameters.

### Return Values

Returns the number of columns in the result set represented by the PDOStatement object, even if the result set is empty. If there is no result set, PDOStatement::columnCount() returns `0`.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Counting columns

This example demonstrates how PDOStatement::columnCount() operates with and without a result set.

`<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print "Before execute(), result set has $colcount columns (should be 0)\n";
$sth->execute();
/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print "After execute(), result set has $colcount columns (should be 2)\n";
?>`

The above example will output:

    Before execute(), result set has 0 columns (should be 0)
    After execute(), result set has 2 columns (should be 2)

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

# PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

### Description

public PDOStatement::debugDumpParams(): ?bool

Dumps the information contained by a prepared statement directly on the output. It will provide the `SQL` query in use, the number of parameters used (`Params`), the list of parameters with their key name or position, their name, their position in the query (if this is supported by the PDO driver, otherwise, it will be -1), type (`param_type`) as an integer, and a boolean value `is_param`.

This is a debug function, which dumps the data directly to the normal output.

Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

This will only dump the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.

### Parameters

This function has no parameters.

### Return Values

Returns `null`, or `false` in case of an error.

### Changelog

Version | Description
--- | ---
7.2.0 | PDOStatement::debugDumpParams() now returns the SQL sent to the database, including the full, raw query (including the replaced placeholders with their bounded values). Note, that this will only be available if emulated prepared statements are turned on.

### Examples

Example #1 PDOStatement::debugDumpParams() example with named parameters

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
$sth->debugDumpParams();
?>`

The above example will output:

    SQL: [96] SELECT name, colour, calories
        FROM fruit
        WHERE calories < :calories AND colour = :colour
    Params:  2
    Key: Name: [9] :calories
    paramno=-1
    name=[9] ":calories"
    is_param=1
    param_type=1
    Key: Name: [7] :colour
    paramno=-1
    name=[7] ":colour"
    is_param=1
    param_type=2

Example #2 PDOStatement::debugDumpParams() example with unnamed parameters

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$name = 'apple';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
$sth->debugDumpParams();
?>`

The above example will output:

    SQL: [82] SELECT name, colour, calories
        FROM fruit
        WHERE calories < ? AND colour = ?
    Params:  2
    Key: Position #0:
    paramno=0
    name=[0] ""
    is_param=1
    param_type=1
    Key: Position #1:
    paramno=1
    name=[0] ""
    is_param=1
    param_type=2

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::bindParam() - Binds a parameter to the specified variable name
- PDOStatement::bindValue() - Binds a value to a parameter

# PDOStatement::errorCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

### Description

public PDOStatement::errorCode(): ?string

### Parameters

This function has no parameters.

### Return Values

Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.

### Examples

Example #1 Retrieving an SQLSTATE code

`<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();
echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>`

The above example will output:

    PDOStatement::errorCode(): 42S02

### See Also

- PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
- PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
- PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

# PDOStatement::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle

### Description

public PDOStatement::errorInfo(): array

### Parameters

This function has no parameters.

### Return Values

PDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of at least the following fields:

Element | Information
--- | ---
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver specific error code.
2 | Driver specific error message.

### Examples

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

`<?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>`

The above example will output:

    PDOStatement::errorInfo():
    Array
    (
        [0] => 42S02
        [1] => -204
        [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
    )

### See Also

- PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
- PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
- PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle

# PDOStatement::execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

### Description

public PDOStatement::execute(?array `$params` = `null`): bool

Execute the prepared statement. If the prepared statement included parameter markers, either:

- PDOStatement::bindParam() and/or PDOStatement::bindValue() has to be called to bind either variables or values (respectively) to the parameter markers. Bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

- or an array of input-only parameter values has to be passed

### Parameters

`params`

  An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as `PDO::PARAM_STR`.

  Multiple values cannot be bound to a single parameter; for example, it is not allowed to bind two values to a single named parameter in an IN() clause.

  Binding more values than specified is not possible; if more keys exist in `params` than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Execute a prepared statement with a bound variable and value

`<?php
/* Execute a prepared statement by binding a variable and value */
$calories = 150;
$colour = 'gre';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour LIKE :colour');
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
/* Names can be prefixed with colons ":" too (optional) */
$sth->bindValue(':colour', "%$colour%");
$sth->execute();
?>`

Example #2 Execute a prepared statement with an array of named values

`<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array('calories' => $calories, 'colour' => $colour));
/* Array keys can be prefixed with colons ":" too (optional) */
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>`

Example #3 Execute a prepared statement with an array of positional values

`<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>`

Example #4 Execute a prepared statement with variables bound to positional placeholders

`<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>`

Example #5 Execute a prepared statement using array for IN clause

`<?php
/* Execute a prepared statement using an array of values for an IN clause */
$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = '?' . str_repeat(', ?', count($params) - 1);
/*
This prepares the statement with enough unnamed placeholders for every value
in our $params array. The values of the $params array are then bound to the
placeholders in the prepared statement when the statement is executed.
This is not the same thing as using PDOStatement::bindParam() since this
requires a reference to the variable. PDOStatement::execute() only binds
by value instead.
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>`

### Notes

> Note:

> Some drivers require to close cursor before executing next statement.

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::bindParam() - Binds a parameter to the specified variable name
- PDOStatement::fetch() - Fetches the next row from a result set
- PDOStatement::fetchAll() - Fetches the remaining rows from a result set
- PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

# PDOStatement::fetch

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

### Description

public PDOStatement::fetch(int `$mode` = `PDO::FETCH_DEFAULT`, int `$cursorOrientation` = `PDO::FETCH_ORI_NEXT`, int `$cursorOffset` = 0): mixed

Fetches a row from a result set associated with a PDOStatement object. The `mode` parameter determines how PDO returns the row.

### Parameters

`mode`

  Controls how the next row will be returned to the caller. This value must be one of the `PDO::FETCH_*` constants, defaulting to value of `PDO::ATTR_DEFAULT_FETCH_MODE` (which defaults to `PDO::FETCH_BOTH`).

  - `PDO::FETCH_ASSOC`: returns an array indexed by column name as returned in your result set

  - `PDO::FETCH_BOTH` (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  - `PDO::FETCH_BOUND`: returns `true` and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method

  - `PDO::FETCH_CLASS`: returns a new instance of the requested class. The object is initialized by mapping the columns of the result set to properties in the class. This occurs before the constructor is called, allowing properties to be populated regardless of their visibility or whether they are marked as `readonly`. If a property does not exist in the class, the magic __set() method will be invoked if it exists; otherwise, a dynamic public property will be created. However, when `PDO::FETCH_PROPS_LATE` is also given, the constructor is called before the properties are populated. If `mode` includes `PDO::FETCH_CLASSTYPE` (e.g. `PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE`), the name of the class is determined from the value of the first column.

  - `PDO::FETCH_INTO`: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class

  - `PDO::FETCH_LAZY`: combines `PDO::FETCH_BOTH` and `PDO::FETCH_OBJ`, and is returning a PDORow object which is creating the object property names as they are accessed.

  - `PDO::FETCH_NAMED`: returns an array with the same form as `PDO::FETCH_ASSOC`, except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name

  - `PDO::FETCH_NUM`: returns an array indexed by column number as returned in your result set, starting at column 0

  - `PDO::FETCH_OBJ`: returns an anonymous object with property names that correspond to the column names returned in your result set

  - `PDO::FETCH_PROPS_LATE`: when used with `PDO::FETCH_CLASS`, the constructor of the class is called before the properties are assigned from the respective column values.

`cursorOrientation`

  For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the `PDO::FETCH_ORI_*` constants, defaulting to `PDO::FETCH_ORI_NEXT`. To request a scrollable cursor for your PDOStatement object, you must set the `PDO::ATTR_CURSOR` attribute to `PDO::CURSOR_SCROLL` when you prepare the SQL statement with PDO::prepare().

`cursorOffset`

  For a PDOStatement object representing a scrollable cursor for which the `cursorOrientation` parameter is set to `PDO::FETCH_ORI_ABS`, this value specifies the absolute number of the row in the result set that shall be fetched.

  For a PDOStatement object representing a scrollable cursor for which the `cursorOrientation` parameter is set to `PDO::FETCH_ORI_REL`, this value specifies the row to fetch relative to the cursor position before PDOStatement::fetch() was called.

### Return Values

The return value of this function on success depends on the fetch type. In all cases, `false` is returned on failure or if there are no more rows.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Fetching rows using different fetch styles

`<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Exercise PDOStatement::fetch styles */
print "PDO::FETCH_ASSOC: ";
print "Return next row as an array indexed by column name\n";
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print "\n";
print "PDO::FETCH_BOTH: ";
print "Return next row as an array indexed by both column name and number\n";
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print "\n";
print "PDO::FETCH_LAZY: ";
print "Return next row as a PDORow object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print "\n";
print "PDO::FETCH_OBJ: ";
print "Return next row as an anonymous object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->name;
print "\n";
?>`

The above example will output:

    PDO::FETCH_ASSOC: Return next row as an array indexed by column name
    Array
    (
        [name] => apple
        [colour] => red
    )

    PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
    Array
    (
        [name] => banana
        [0] => banana
        [colour] => yellow
        [1] => yellow
    )

    PDO::FETCH_LAZY: Return next row as a PDORow object with column names as properties
    PDORow Object
    (
        [name] => orange
        [colour] => orange
    )

    PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
    kiwi

Example #2 Fetching rows with a scrollable cursor

`<?php
function readDataForwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
}
}
function readDataBackwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
do {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
} while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
}
print "Reading forwards:\n";
readDataForwards($conn);
print "Reading backwards:\n";
readDataBackwards($conn);
?>`

The above example will output:

    Reading forwards:
    21    10    5
    16    0     5
    19    20    10

    Reading backwards:
    19    20    10
    16    0     5
    21    10    5

Example #3 Construction order

When objects are fetched via `PDO::FETCH_CLASS`, the object properties are assigned first, and then the constructor of the class is invoked. However, when `PDO::FETCH_PROPS_LATE` is also given, this order is reversed, i.e. first the constructor is called, and afterwards the properties are assigned.

`<?php
class Person
{
private $name;
public function __construct()
{
$this->tell();
}
public function tell()
{
if (isset($this->name)) {
echo "I am {$this->name}.\n";
} else {
echo "I don't have a name yet.\n";
}
}
}
$sth = $dbh->query("SELECT * FROM people");
$sth->setFetchMode(PDO::FETCH_CLASS, 'Person');
$person = $sth->fetch();
$person->tell();
$sth->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Person');
$person = $sth->fetch();
$person->tell();
?>`

The above example will output something similar to:

    I am Alice.
    I am Alice.
    I don't have a name yet.
    I am Bob.

### See Also

- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::fetchAll() - Fetches the remaining rows from a result set
- PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
- PDOStatement::fetchObject() - Fetches the next row and returns it as an object
- PDOStatement::setFetchMode() - Set the default fetch mode for this statement

# PDOStatement::fetchAll

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Fetches the remaining rows from a result set

### Description

public PDOStatement::fetchAll(int `$mode` = PDO::FETCH_DEFAULT): array
public PDOStatement::fetchAll(int `$mode` = PDO::FETCH_COLUMN, int `$column`): array
public PDOStatement::fetchAll(int `$mode` = PDO::FETCH_CLASS, string `$class`, ?array `$constructorArgs`): array
public PDOStatement::fetchAll(int `$mode` = PDO::FETCH_FUNC, callable `$callback`): array

### Parameters

`mode`

  Controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to value of `PDO::ATTR_DEFAULT_FETCH_MODE` (which defaults to `PDO::FETCH_BOTH`)

  To return an array consisting of all values of a single column from the result set, specify `PDO::FETCH_COLUMN`. You can specify which column you want with the `column` parameter.

  To index the resulting array by a certain column's value (instead of consecutive numbers), put this column's name first in the column list in SQL, and use `PDO::FETCH_UNIQUE`. This column must contain only unique values or some data will be lost.

  To group results in the form of a 3-dimensional array indexed by values of a specified column, put this column's name first in the column list in SQL and use `PDO::FETCH_GROUP`.

  To group results in the form of a 2-dimensional array use bitwise-OR `PDO::FETCH_GROUP` with `PDO::FETCH_COLUMN`. The results will be grouped by the first column, with the array element's value being a list array of the corresponding entries from the second column.

The following are dynamic parameters that are depending on the fetch mode. They can't be used with named parameters.

`column`

  Used with `PDO::FETCH_COLUMN`. Returns the indicated 0-indexed column.

`class`

  Used with `PDO::FETCH_CLASS`. Returns instances of the specified class, mapping the columns of each row to named properties in the class.

`constructorArgs`

  Arguments of custom class constructor when the `mode` parameter is `PDO::FETCH_CLASS`.

`callback`

  Used with `PDO::FETCH_FUNC`. Returns the results of calling the specified function, using each row's columns as parameters in the call.

### Return Values

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and ORDER BY clauses in SQL to restrict results before retrieving and processing them with PHP.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Changelog

Version | Description
--- | ---
8.0.0 | This method always returns an array now, while previously `false` may have been returned on failure.

### Examples

Example #1 Fetch all remaining rows in a result set

`<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print "Fetch all of the remaining rows in the result set:\n";
$result = $sth->fetchAll();
print_r($result);
?>`

The above example will output something similar to:

    Fetch all of the remaining rows in the result set:
    Array
    (
        [0] => Array
            (
                [name] => apple
                [0] => apple
                [colour] => red
                [1] => red
            )

        [1] => Array
            (
                [name] => pear
                [0] => pear
                [colour] => green
                [1] => green
            )

        [2] => Array
            (
                [name] => watermelon
                [0] => watermelon
                [colour] => pink
                [1] => pink
            )

    )

Example #2 Fetching all values of a single column from a result set

The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.

`<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>`

The above example will output something similar to:

    Array(3)
    (
        [0] =>
        string(5) => apple
        [1] =>
        string(4) => pear
        [2] =>
        string(10) => watermelon
    )

Example #3 Grouping all values by a single column

The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values `apple` and `pear` are returned as arrays that contain two different colours, while `watermelon` is returned as an array that contains only one colour.

`<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>`

The above example will output something similar to:

    array(3) {
      ["apple"]=>
      array(2) {
        [0]=>
        string(5) "green"
        [1]=>
        string(3) "red"
      }
      ["pear"]=>
      array(2) {
        [0]=>
        string(5) "green"
        [1]=>
        string(6) "yellow"
      }
      ["watermelon"]=>
      array(1) {
        [0]=>
        string(5) "pink"
      }
    }

Example #4 Instantiating a class for each result

The following example demonstrates the behaviour of the `PDO::FETCH_CLASS` fetch style.

`<?php
class fruit {
public $name;
public $colour;
}
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>`

The above example will output something similar to:

    array(3) {
      [0]=>
      object(fruit)#1 (2) {
        ["name"]=>
        string(5) "apple"
        ["colour"]=>
        string(5) "green"
      }
      [1]=>
      object(fruit)#2 (2) {
        ["name"]=>
        string(4) "pear"
        ["colour"]=>
        string(6) "yellow"
      }
      [2]=>
      object(fruit)#3 (2) {
        ["name"]=>
        string(10) "watermelon"
        ["colour"]=>
        string(4) "pink"
      }
      [3]=>
      object(fruit)#4 (2) {
        ["name"]=>
        string(5) "apple"
        ["colour"]=>
        string(3) "red"
      }
      [4]=>
      object(fruit)#5 (2) {
        ["name"]=>
        string(4) "pear"
        ["colour"]=>
        string(5) "green"
      }
    }

Example #5 Calling a function for each result

The following example demonstrates the behaviour of the `PDO::FETCH_FUNC` fetch style.

`<?php
function fruit($name, $colour) {
return "{$name}: {$colour}";
}
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit");
var_dump($result);
?>`

The above example will output something similar to:

    array(3) {
      [0]=>
      string(12) "apple: green"
      [1]=>
      string(12) "pear: yellow"
      [2]=>
      string(16) "watermelon: pink"
      [3]=>
      string(10) "apple: red"
      [4]=>
      string(11) "pear: green"
    }

### See Also

- PDO::query() - Prepares and executes an SQL statement without placeholders
- PDOStatement::fetch() - Fetches the next row from a result set
- PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::setFetchMode() - Set the default fetch mode for this statement

# PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn — Returns a single column from the next row of a result set

### Description

public PDOStatement::fetchColumn(int `$column` = 0): mixed

Returns a single column from the next row of a result set or `false` if there are no more rows.

> Note:

> PDOStatement::fetchColumn() should not be used to retrieve boolean columns, as it is impossible to distinguish a value of `false` from there being no more rows to retrieve. Use PDOStatement::fetch() instead.

### Parameters

`column`

  0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.

### Return Values

PDOStatement::fetchColumn() returns a single column from the next row of a result set or `false` if there are no more rows.

Warning

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Return first column of the next row

`<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
print "Fetch the first column from the first row in the result set:\n";
$result = $sth->fetchColumn();
print "name = $result\n";
print "Fetch the second column from the second row in the result set:\n";
$result = $sth->fetchColumn(1);
print "colour = $result\n";
?>`

The above example will output:

    Fetch the first column from the first row in the result set:
    name = lemon
    Fetch the second column from the second row in the result set:
    colour = red

### See Also

- PDO::query() - Prepares and executes an SQL statement without placeholders
- PDOStatement::fetch() - Fetches the next row from a result set
- PDOStatement::fetchAll() - Fetches the remaining rows from a result set
- PDO::prepare() - Prepares a statement for execution and returns a statement object
- PDOStatement::setFetchMode() - Set the default fetch mode for this statement

# PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — Fetches the next row and returns it as an object

### Description

public PDOStatement::fetchObject(?string `$class` = "stdClass", array `$constructorArgs` = []): object|false

Fetches the next row and returns it as an object. This function is an alternative to PDOStatement::fetch() with `PDO::FETCH_CLASS` or `PDO::FETCH_OBJ` style.

When an object is fetched, its properties are assigned from respective column values, and afterwards its constructor is invoked.

### Parameters

`class`

  Name of the created class.

`constructorArgs`

  Elements of this array are passed to the constructor.

### Return Values

Returns an instance of the required class with property names that correspond to the column names or `false` on failure.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### See Also

- PDOStatement::fetch() - Fetches the next row from a result set

# PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

### Description

public PDOStatement::getAttribute(int `$name`): mixed

Gets an attribute of the statement. Currently, no generic attributes exist but only driver specific:

- `PDO::ATTR_CURSOR_NAME` (Firebird and ODBC specific): Get the name of cursor for `UPDATE ... WHERE CURRENT OF`.

Note that driver specific attributes must not be used with other drivers.

### Parameters

`name`

  The attribute to query.

### Return Values

Returns the attribute value.

### See Also

- PDO::getAttribute() - Retrieve a database connection attribute
- PDO::setAttribute() - Set an attribute
- PDOStatement::setAttribute() - Set a statement attribute

# PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

### Description

public PDOStatement::getColumnMeta(int `$column`): array|false

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Warning

Some drivers may not implement PDOStatement::getColumnMeta(), as it is optional. However, all PDO drivers documented in the manual implement this function.

### Parameters

`column`

  The 0-indexed column in the result set.

### Return Values

Returns an associative array containing the following values representing the metadata for a single column:

Column metadata
Name | Value
--- | ---
`native_type` | The PHP native type used to represent the column value.
`driver:decl_type` | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta().
`flags` | Any flags set for this column.
`name` | The name of this column as returned by the database.
`table` | The name of this column's table as returned by the database.
`len` | The length of this column. Normally `-1` for types other than floating point decimals.
`precision` | The numeric precision of this column. Normally `0` for types other than floating point decimals.
`pdo_type` | The type of this column as represented by the `PDO::PARAM_*` constants.

Returns `false` if the requested column does not exist in the result set, or if no result set exists.

### Examples

Example #1 Retrieving column metadata

The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.

`<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>`

The above example will output:

    array(6) {
      ["native_type"]=>
      string(7) "integer"
      ["flags"]=>
      array(0) {
      }
      ["name"]=>
      string(8) "COUNT(*)"
      ["len"]=>
      int(-1)
      ["precision"]=>
      int(0)
      ["pdo_type"]=>
      int(2)
    }

### See Also

- PDOStatement::columnCount() - Returns the number of columns in the result set
- PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

# PDOStatement::getIterator

(PHP 8)

PDOStatement::getIterator — Gets result set iterator

### Description

public PDOStatement::getIterator(): Iterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# PDOStatement::nextRowset

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle

### Description

public PDOStatement::nextRowset(): bool

Some database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement::nextRowset() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Fetching multiple rowsets returned from a stored procedure

The following example shows how to call a stored procedure, `MULTIPLE_ROWSETS`, which returns three rowsets. We use a do-while loop to call the PDOStatement::nextRowset() method until it returns `false` and terminates the loop when no more rowsets are available.

`<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
printResultSet($rowset, $i);
}
$i++;
} while ($stmt->nextRowset());
function printResultSet(&$rowset, $i) {
print "Result set $i:\n";
foreach ($rowset as $row) {
foreach ($row as $col) {
print $col . "\t";
}
print "\n";
}
print "\n";
}
?>`

The above example will output:

    Result set 1:
    apple    red
    banana   yellow

    Result set 2:
    orange   orange    150
    banana   yellow    175

    Result set 3:
    lime     green
    apple    red
    banana   yellow

### See Also

- PDOStatement::columnCount() - Returns the number of columns in the result set
- PDOStatement::execute() - Executes a prepared statement
- PDOStatement::getColumnMeta() - Returns metadata for a column in a result set
- PDO::query() - Prepares and executes an SQL statement without placeholders

# PDOStatement::rowCount

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

### Description

public PDOStatement::rowCount(): int

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding `PDOStatement` object.

For statements that produce result sets, such as `SELECT`, the behavior is undefined and can be different for each driver. Some databases may return the number of rows produced by that statement (e.g. MySQL in buffered mode), but this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

> Note:

> This method returns "0" (zero) with PostgreSQL driver when setting the `PDO::ATTR_CURSOR` statement attribute to `PDO::CURSOR_SCROLL`.

### Parameters

This function has no parameters.

### Return Values

Returns the number of rows.

### Errors/Exceptions

Emits an error with level `E_WARNING` if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_WARNING`.

Throws a PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`.

### Examples

Example #1 Return the number of deleted rows

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

`<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print "Return number of rows that were deleted:\n";
$count = $del->rowCount();
print "Deleted $count rows.\n";
?>`

The above example will output something similar to:

    Return number of rows that were deleted:
    Deleted 9 rows.

Example #2 Counting rows returned by a SELECT statement

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of matching rows.

`<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
$res = $conn->query($sql);
$count = $res->fetchColumn();
print "There are " . $count . " matching records.";`

The above example will output something similar to:

    There are 2 matching records.

### See Also

- PDOStatement::columnCount() - Returns the number of columns in the result set
- PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
- PDO::query() - Prepares and executes an SQL statement without placeholders

# PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — Set a statement attribute

### Description

public PDOStatement::setAttribute(int `$attribute`, mixed `$value`): bool

Sets an attribute on the statement. Currently, no generic attributes are set but only driver specific:

- `PDO::ATTR_CURSOR_NAME` (Firebird and ODBC specific): Set the name of cursor for `UPDATE ... WHERE CURRENT OF`.

Note that driver specific attributes must not be used with other drivers.

### Parameters

`attribute`

  The attribute to modify.

`value`

  The value to set the `attribute`, might require a specific type depending on the attribute.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- PDO::getAttribute() - Retrieve a database connection attribute
- PDO::setAttribute() - Set an attribute
- PDOStatement::getAttribute() - Retrieve a statement attribute

# PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — Set the default fetch mode for this statement

### Description

public PDOStatement::setFetchMode(int `$mode`): bool
public PDOStatement::setFetchMode(int `$mode` = PDO::FETCH_COLUMN, int `$colno`): bool
public PDOStatement::setFetchMode(int `$mode` = PDO::FETCH_CLASS, string `$class`, ?array `$constructorArgs` = `null`): bool
public PDOStatement::setFetchMode(int `$mode` = PDO::FETCH_INTO, object `$object`): bool

### Parameters

`mode`

  The fetch mode must be one of the `PDO::FETCH_*` constants.

`colno`

  Column number.

`class`

  Class name.

`constructorArgs`

  Constructor arguments.

`object`

  Object.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the fetch mode

The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.

`<?php
$stmt = $dbh->query('SELECT name, colour, calories FROM fruit');
$stmt->setFetchMode(PDO::FETCH_NUM);
foreach ($stmt as $row) {
print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
}`

The above example will output something similar to:

    apple   red     150
    banana  yellow  250
    orange  orange  300
    kiwi    brown   75
    lemon   yellow  25
    pear    green   150

## Table of Contents

- PDOStatement::bindColumn — Bind a column to a PHP variable
- PDOStatement::bindParam — Binds a parameter to the specified variable name
- PDOStatement::bindValue — Binds a value to a parameter
- PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again
- PDOStatement::columnCount — Returns the number of columns in the result set
- PDOStatement::debugDumpParams — Dump an SQL prepared command
- PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
- PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle
- PDOStatement::execute — Executes a prepared statement
- PDOStatement::fetch — Fetches the next row from a result set
- PDOStatement::fetchAll — Fetches the remaining rows from a result set
- PDOStatement::fetchColumn — Returns a single column from the next row of a result set
- PDOStatement::fetchObject — Fetches the next row and returns it as an object
- PDOStatement::getAttribute — Retrieve a statement attribute
- PDOStatement::getColumnMeta — Returns metadata for a column in a result set
- PDOStatement::getIterator — Gets result set iterator
- PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle
- PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement
- PDOStatement::setAttribute — Set a statement attribute
- PDOStatement::setFetchMode — Set the default fetch mode for this statement

# The PDORow class

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

## Introduction

Represents a row from a result set returned by PDOStatement::fetch() called with `PDO::FETCH_LAZY` fetch mode.

Objects of this class cannot be instantiated and are not serializable.

The PDORow object allows access to the returned data as if both `PDO::FETCH_OBJ` and `PDO::FETCH_BOTH` mode was used. This means that the returned data can be accessed as object properties, and as an array both indexed by the column name and a column offset number.

Caution

Accessing an undefined property returns `null` without emitting a warning.

## Class synopsis

final class PDORow {
/* Properties */
public string $queryString;
}

## Properties

queryString

  Query string used by the PDOStatement that returned the PDORow object.

## Errors/Exceptions

Throws an Error when trying to write to or unset() any property.

# The PDOException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

## Introduction

Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

## Class synopsis

class PDOException extends RuntimeException {
/* Properties */
protected int|string $code;
public ?array $errorInfo = null;
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

errorInfo

  Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

code

  `SQLSTATE` error code. Use Exception::getCode() to access it.

# PDO Drivers

## Table of Contents

- CUBRID PDO Driver
- MS SQL Server PDO Driver
- Pdo\Dblib
- Firebird PDO Driver
- Pdo\Firebird
- IBM PDO Driver
- Informix PDO Driver
- MySQL PDO Driver
- Pdo\Mysql
- MS SQL Server PDO Driver
- Oracle PDO Driver
- ODBC and DB2 PDO Driver
- Pdo\Odbc
- PostgreSQL PDO Driver
- Pdo\Pgsql
- SQLite PDO Driver
- Pdo\Sqlite

The following drivers currently implement the PDO interface:

Driver name | Supported databases
--- | ---
PDO_CUBRID | Cubrid
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x/5.x/8.x
PDO_OCI | Oracle Call Interface
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL | PostgreSQL
PDO_SQLITE | SQLite 3 and SQLite 2
PDO_SQLSRV | Microsoft SQL Server / SQL Azure

# CUBRID PDO Driver (PDO_CUBRID)

## Introduction

PDO_CUBRID is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to CUBRID databases.

> Note: Current version of PDO_CUBRID doesn't support persistent connection now.

## Installation

To build the PDO_CUBRID extension, the CUBRID DBMS must be installed on the same system as PHP. PDO_CUBRID is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_CUBRID extension. Issue the configure command to point to the location of the CUBRID base dir as follows:

       $ ./configure --with-pdo-cubrid=/path/to/CUBRID[,shared]

The configure command defaults to the value of the CUBRID environment variable.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section. Detailed information about installation on Linux and Windows manually, please read build-guide.html in PECL package CUBRID for reference.

## PDO_CUBRID Features

## Scrollable cursors

PDO_CUBRID supports scrollable cursors. The default cursor type is forward only, and you can use parameter driver_options in PDO::prepare() to change cursor type.

## Timeout

PDO_CUBRID supports sql statement execution timeout setting; You can use PDO::setAttribute() to set timeout value.

## Autocommit_mode and Transaction

PDO_CUBRID supports both autocommit_mode and transaction, and autocommit_mode is enabled by default. You can use PDO::setAttribute() to change its state.

If you use PDO::beginTransaction() to begin a transaction, it will disable autocommit_mode automatically and restore it after PDO::commit() or PDO::rollBack().

> Note: Prior do disabling autocommit_mode any pending work is automatically committed.

## Multiple SQL Statements

PDO_CUBRID supports Multiple SQL statements. Multiple SQL statements are separated by semicolons (`;`).

## Schema Information

PDO_CUBRID implements PDO::cubrid_schema() to get schema information.

## LOBs

PDO_CUBRID supports BLOB/CLOB data type. The LOB in PDO is represented as a stream, so you can insert LOBs by binding a stream, and get LOBs by reading a stream returned by CUBRID PDO. For example:

Example #1 Insert LOBs in CUBRID PDO

`<?php
$fp = fopen('lob_test.png', 'rb');
$sql_stmt = "INSERT INTO lob_test(name, content) VALUES('lob_test.png', ?)";
$stmt = $dbh->prepare($sql_stmt);
$ret = $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$ret = $stmt->execute();
?>`

Example #2 Fetch LOBs in CUBRID PDO

`<?php
$sql_stmt = "SELECT content FROM lob_test WHERE name='lob_test.png'";
$stmt = $dbh->prepare($sql_stmt);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);
header("Content-Type: image/png");
fpassthru($result[0]);
?>`

## Column meta

The PDOStatement::getColumnMeta() in CUBRID PDO will return an associative array containing the following values:

- type
- name
- table
- def
- precision
- scale
- not_null
- auto_increment
- unique_key
- multiple_key
- primary_key
- foreign_key
- reverse_index
- reverse_unique

## Collection Data Type

PDO_CUBRID supports SET/MULTISET/SEQUENCE data type. If you don't specify data type, the default data type is char. For example:

Example #3 Insert set in CUBRID PDO with default data type.

`<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');
$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(VARCHAR))");
$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array("abc","def","ghi");
$ret = $stmt->bindParam(1, $data, PDO::PARAM_NULL);
$ret = $stmt->execute();
var_Dump($ret);
?>`

Example #4 Specify data type when insert set in CUBRID PDO

`<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');
$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(int))");
$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array(1,2,3,4);
$ret = $stmt->bindParam(1, $data, 0,0,"int");
$ret = $stmt->execute();
var_Dump($ret);
?>`

CUBRID Bind Data Types for the fifth parameter of PDOStatement::bindParam():

- CHAR
- STRING
- NCHAR
- VARNCHAR
- BIT
- VARBIT
- NUMERIC
- NUMBER
- INT
- SHORT
- BIGINT
- MONETARY
- FLOAT
- DOUBLE
- DATE
- TIME
- DATETIME
- TIMESTAMP

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

The following constants can be used when setting the database attribute. They can be passed to PDO::getAttribute() or PDO::setAttribute().

PDO::CUBRID attribute flags
Constant | Description
--- | ---
`PDO::CUBRID_ATTR_ISOLATION_LEVEL` | Transaction isolation level for the database connection.
`PDO::CUBRID_ATTR_LOCK_TIMEOUT` | Transaction timeout in seconds.
`PDO::CUBRID_ATTR_MAX_STRING_LENGTH` | Read only. The maximum string length for bit, varbit, char, varchar, nchar, nchar varying data types when using CUBRID PDO API.

The following constants can be used when setting the transaction isolation level. They can be passed to PDO::getAttribute() or returned by PDO::setAttribute().

PDO::CUBRID isolation level flags
Constant | Description
--- | ---
`PDO::TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE` | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
`PDO::TRAN_COMMIT_CLASS_COMMIT_INSTANCE` | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
`PDO::TRAN_REP_CLASS_UNCOMMIT_INSTANCE` | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
`PDO::TRAN_REP_CLASS_COMMIT_INSTANCE` | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
`PDO::TRAN_REP_CLASS_REP_INSTANCE` | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
`PDO::TRAN_SERIALIZABLE` | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to PDO::cubrid_schema().

PDO::CUBRID schema flags
Constant | Description
--- | ---
`PDO::CUBRID_SCH_TABLE` | Get name and type of table in CUBRID.
`PDO::CUBRID_SCH_VIEW` | Get name and type of view in CUBRID.
`PDO::CUBRID_SCH_QUERY_SPEC` | Get the query definition of view.
`PDO::CUBRID_SCH_ATTRIBUTE` | Get the attributes of table column.
`PDO::CUBRID_SCH_TABLE_ATTRIBUTE` | Get the attributes of table.
`PDO::CUBRID_SCH_METHOD` | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
`PDO::CUBRID_SCH_TABLE_METHOD` | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
`PDO::CUBRID_SCH_METHOD_FILE` | Get the information of the file where the method of the table is defined.
`PDO::CUBRID_SCH_SUPER_TABLE` | Get the name and type of table which table inherites attributes from.
`PDO::CUBRID_SCH_SUB_TABLE` | Get the name and type of table which inherites attributes from this table.
`PDO::CUBRID_SCH_CONSTRAINT` | Get the table constraints.
`PDO::CUBRID_SCH_TRIGGER` | Get the table triggers.
`PDO::CUBRID_SCH_TABLE_PRIVILEGE` | Get the privilege information of table.
`PDO::CUBRID_SCH_COL_PRIVILEGE` | Get the privilege information of column.
`PDO::CUBRID_SCH_DIRECT_SUPER_TABLE` | Get the direct super table of table.
`PDO::CUBRID_SCH_PRIMARY_KEY` | Get the table primary key.
`PDO::CUBRID_SCH_IMPORTED_KEYS` | Get imported keys of table.
`PDO::CUBRID_SCH_EXPORTED_KEYS` | Get exported keys of table.
`PDO::CUBRID_SCH_CROSS_REFERENCE` | Get reference relationship of tow tables.

# PDO_CUBRID DSN

(PECL PDO_CUBRID >= 8.3.0.0001)

PDO_CUBRID DSN — Connecting to CUBRID databases

### Description

The PDO_CUBRID Data Source Name (DSN) is composed of the following elements, delimited by semicolons:

DSN prefix

  The DSN prefix is `cubrid:`.

`host`
  The hostname on which the database server resides.
`port`
  The port on which the database server is running.
`dbname`
  The name of the database.

### Notes

> Note: When you estalish the connection to CUBRID, you should give username and password except DSN.

### Examples

Example #1 PDO_CUBRID DSN examples

The following example shows a PDO_CUBRID DSN for connecting to a CUBRID database:

    cubrid:host=localhost;port=33000;dbname=demodb

# PDO::cubrid_schema

(PECL PDO_CUBRID >= 8.3.0.0001)

PDO::cubrid_schema — Get the requested schema information

### Description

public PDO::cubrid_schema(int `$schema_type`, string `$table_name` = ?, string `$col_name` = ?): array

This function is used to get the requested schema information from database. You have to designate `table_name`, if you want to get information on certain table, `col_name`, if you want to get information on certain column (can be used only with PDO::CUBRID_SCH_COL_PRIVILEGE).

The result of this function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
--- | --- | --- | ---
PDO::CUBRID_SCH_TABLE | 1 | NAME |
| 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_VIEW | 1 | NAME |
| 2 | TYPE | 1:view
PDO::CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
PDO::CUBRID_SCH_ATTRIBUTE / PDO::CUBRID_SCH_TABLE_ATTRIBUTE | 1 | ATTR_NAME |
| 2 | DOMAIN |
| 3 | SCALE |
| 4 | PRECISION |
| 5 | INDEXED | 1:indexed
| 6 | NOT NULL | 1:not null
| 7 | SHARED | 1:shared
| 8 | UNIQUE | 1:unique
| 9 | DEFAULT |
| 10 | ATTR_ORDER | base:1
| 11 | CLASS_NAME |
| 12 | SOURCE_CLASS |
| 13 | IS_KEY | 1:key
PDO::CUBRID_SCH_METHOD / PDO::CUBRID_SCH_TABLE_METHOD | 1 | NAME |
| 2 | RET_DOMAIN |
| 3 | ARG_DOMAIN |
PDO::CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
PDO::CUBRID_SCH_SUPER_TABLE / PDO::CUBRID_SCH_DIRECT_SUPER_TABLE / PDO::CUBRID_SCH_SUB_TABLE | 1 | CLASS_NAME |
| 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
| 2 | NAME |
| 3 | ATTR_NAME |
| 4 | NUM_PAGES |
| 5 | NUM_KEYS |
| 6 | PRIMARY_KEY | 1:primary key
| 7 | KEY_ORDER | base:1
PDO::CUBRID_SCH_TRIGGER | 1 | NAME |
| 2 | STATUS |
| 3 | EVENT |
| 4 | TARGET_CLASS |
| 5 | TARGET_ATTR |
| 6 | ACTION_TIME |
| 7 | ACTION |
| 8 | PRIORITY |
| 9 | CONDITION_TIME |
| 10 | CONDITION |
PDO::CUBRID_SCH_TABLE_PRIVILEGE / PDO::CUBRID_SCH_COL_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
| 2 | PRIVILEGE |
| 3 | GRANTABLE |
PDO::CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
| 2 | ATTR_NAME |
| 3 | KEY_SEQ | base:1
| 4 | KEY_NAME |
PDO::CUBRID_SCH_IMPORTED_KEYS / PDO::CUBRID_SCH_EXPORTED_KEYS / PDO::CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
| 2 | PKCOLUMN_NAME |
| 3 | FKTABLE_NAME | base:1
| 4 | FKCOLUMN_NAME |
| 5 | KEY_SEQ | base:1
| 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
| 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
| 8 | FK_NAME |
| 9 | PK_NAME |

### Parameters

`schema_type`
  Schema type that you want to know.
`table_name`
  Table you want to know the schema of.
`col_name`
  Column you want to know the schema of.

### Return Values

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

### Examples

Example #1 A PDO::cubrid_schema() example

This example shows how to get primary key and foreign keys of table game.

`<?php
$pk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_PRIMARY_KEY, "game");
print_r($pk_list);
$fk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, "game");
print_r($fk_list);
?>`

The above example will output:

    Result:
    Array
    (
        [0] => Array
            (
                [CLASS_NAME] => game
                [ATTR_NAME] => athlete_code
                [KEY_SEQ] => 3
                [KEY_NAME] => pk_game_host_year_event_code_athlete_code
            )

        [1] => Array
            (
                [CLASS_NAME] => game
                [ATTR_NAME] => event_code
                [KEY_SEQ] => 2
                [KEY_NAME] => pk_game_host_year_event_code_athlete_code
            )

        [2] => Array
            (
                [CLASS_NAME] => game
                [ATTR_NAME] => host_year
                [KEY_SEQ] => 1
                [KEY_NAME] => pk_game_host_year_event_code_athlete_code
            )

    )
    Array
    (
        [0] => Array
            (
                [PKTABLE_NAME] => athlete
                [PKCOLUMN_NAME] => code
                [FKTABLE_NAME] => game
                [FKCOLUMN_NAME] => athlete_code
                [KEY_SEQ] => 1
                [UPDATE_RULE] => 1
                [DELETE_RULE] => 1
                [FK_NAME] => fk_game_athlete_code
                [PK_NAME] => pk_athlete_code
            )

        [1] => Array
            (
                [PKTABLE_NAME] => event
                [PKCOLUMN_NAME] => code
                [FKTABLE_NAME] => game
                [FKCOLUMN_NAME] => event_code
                [KEY_SEQ] => 1
                [UPDATE_RULE] => 1
                [DELETE_RULE] => 1
                [FK_NAME] => fk_game_event_code
                [PK_NAME] => pk_event_code
            )

    )

## Table of Contents

- PDO_CUBRID DSN — Connecting to CUBRID databases
- PDO::cubrid_schema — Get the requested schema information

# Microsoft SQL Server and Sybase PDO Driver (PDO_DBLIB)

## Introduction

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS library.

This extension is not available anymore on Windows.

On Windows, you should use SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

# PDO_DBLIB DSN

(PECL PDO_DBLIB >= 0.9.0)

PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

### Description

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `sybase:` if PDO_DBLIB was linked against the Sybase ct-lib libraries, `mssql:` if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or `dblib:` if PDO_DBLIB was linked against the FreeTDS libraries.

`host`

  The hostname on which the database server resides. Defaults to 127.0.0.1.

`dbname`

  The name of the database.

`charset`

  The client character set.

`appname`

  The application name (used in sysprocesses). Defaults to "PHP Generic DB-lib" or "PHP freetds".

`secure`

  Currently unused.

### Examples

Example #1 PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:

    mssql:host=localhost;dbname=testdb
    sybase:host=localhost;dbname=testdb
    dblib:host=localhost;dbname=testdb

## Table of Contents

- PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

# The Pdo\Dblib class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the DBLib PDO driver.

## Class synopsis

namespace Pdo;
class Dblib extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int Pdo\Dblib::ATTR_CONNECTION_TIMEOUT;
public const int Pdo\Dblib::ATTR_QUERY_TIMEOUT;
public const int Pdo\Dblib::ATTR_STRINGIFY_UNIQUEIDENTIFIER;
public const int Pdo\Dblib::ATTR_VERSION;
public const int Pdo\Dblib::ATTR_TDS_VERSION;
public const int Pdo\Dblib::ATTR_SKIP_EMPTY_ROWSETS;
public const int Pdo\Dblib::ATTR_DATETIME_CONVERT;
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Dblib::ATTR_CONNECTION_TIMEOUT`
`Pdo\Dblib::ATTR_QUERY_TIMEOUT`
`Pdo\Dblib::ATTR_STRINGIFY_UNIQUEIDENTIFIER`
`Pdo\Dblib::ATTR_VERSION`
`Pdo\Dblib::ATTR_TDS_VERSION`
`Pdo\Dblib::ATTR_SKIP_EMPTY_ROWSETS`
`Pdo\Dblib::ATTR_DATETIME_CONVERT`

# Firebird PDO Driver (PDO_FIREBIRD)

## Introduction

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird database.

## Installation

Use --with-pdo-firebird[=DIR] to install the PDO Firebird extension, where the optional `[=DIR]` is the Firebird base install directory.

    $ ./configure --with-pdo-firebird

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO::FB_ATTR_DATE_FORMAT` (int)

  Alias of `Pdo\Firebird::ATTR_DATE_FORMAT`.

`PDO::FB_ATTR_TIME_FORMAT` (int)

  Alias of `Pdo\Firebird::ATTR_TIME_FORMAT`.

`PDO::FB_ATTR_TIMESTAMP_FORMAT` (int)

  Alias of `Pdo\Firebird::ATTR_TIMESTAMP_FORMAT`.

# PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird databases

### Description

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `firebird:`.

`dbname`

  The name of the database.

`charset`

  The character set.

`role`

  The SQL role name.

`dialect`

  The dialect of the database; either `1` or `3`. If not specified, the dialect defaults to `3`. Available as of PHP 7.4.0.

### Examples

Example #1 PDO_FIREBIRD DSN example with path

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird databases:

    firebird:dbname=/path/to/DATABASE.FDB

Example #2 PDO_FIREBIRD DSN example with port and path

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database using hostname port and path:

    firebird:dbname=hostname/port:/path/to/DATABASE.FDB

Example #3 PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database employee.fdb using localhost:

    firebird:dbname=localhost:/var/lib/firebird/2.5/data/employee.fdb

Example #4 PDO_FIREBIRD DSN to connect to a dialect 1 database

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database test.fdb which has been created using dialect 1. This is only supported as of PHP 7.4.0.

    firebird:dbname=localhost:/var/lib/firebird/2.5/data/test.fdb;charset=utf-8;dialect=1

## Table of Contents

- PDO_FIREBIRD DSN — Connecting to Firebird databases

# The Pdo\Firebird class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the Firebird PDO driver.

## Class synopsis

namespace Pdo;
class Firebird extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int Pdo\Firebird::ATTR_DATE_FORMAT;
public const int Pdo\Firebird::ATTR_TIME_FORMAT;
public const int Pdo\Firebird::ATTR_TIMESTAMP_FORMAT;
public const int Pdo\Firebird::TRANSACTION_ISOLATION_LEVEL;
public const int Pdo\Firebird::READ_COMMITTED;
public const int Pdo\Firebird::REPEATABLE_READ;
public const int Pdo\Firebird::SERIALIZABLE;
public const int Pdo\Firebird::WRITABLE_TRANSACTION;
/* Methods */
public static Pdo\Firebird::getApiVersion(): int
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Firebird::ATTR_DATE_FORMAT`
  Sets the date format.
`Pdo\Firebird::ATTR_TIME_FORMAT`
  Sets the time format.
`Pdo\Firebird::ATTR_TIMESTAMP_FORMAT`
  Sets the timestamp format.
`Pdo\Firebird::TRANSACTION_ISOLATION_LEVEL`
  Attribute to sets the transaction isolation level. This can be one of `Pdo\Firebird::READ_COMMITTED`, `Pdo\Firebird::REPEATABLE_READ`, or `Pdo\Firebird::SERIALIZABLE`.
`Pdo\Firebird::READ_COMMITTED`
  Flag denoting the ANSI transaction isolation level is read committed. This is the default behavior.
`Pdo\Firebird::REPEATABLE_READ`
  Flag denoting the ANSI transaction isolation level is repeatable read. This corresponds to Firebird's "snapshot" isolation level.
`Pdo\Firebird::SERIALIZABLE`
  Flag denoting the ANSI transaction isolation level is serializable. This corresponds to Firebird's "snapshot table stability" isolation level.
`Pdo\Firebird::WRITABLE_TRANSACTION`
  Boolean attribute used to toggle the transaction access mode between `READ ONLY` and `READ WRITE`. By default, it is `true` indicating `READ WRITE`.

# Pdo\Firebird::getApiVersion

(PHP 8 >= 8.4.0)

Pdo\Firebird::getApiVersion — Get the API version

### Description

public static Pdo\Firebird::getApiVersion(): int

Returns the Firebird API version as defined by the C constant `FB_API_VER` in ibase.h.

### Parameters

This function has no parameters.

### Return Values

Returns the FireBird API as an int.

## Table of Contents

- Pdo\Firebird::getApiVersion — Get the API version

# IBM PDO Driver (PDO_IBM)

## Introduction

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.

## Installation

To build the PDO_IBM extension, the DB2 Client v9.1 or later must be installed on the same system as PHP. The DB2 Client can be downloaded from the IBM » Application Development Site.

> Note: Note

> The DB2 Client v9.1 or later supports direct access to DB2 for Linux, UNIX, and Windows v8 and v9.1 servers.

> The DB2 Client v9.1 also supports access to DB2 UDB for i5 and DB2 UDB for z/OS servers using the separately purchased » DB2 Connect product.

PDO_IBM is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_IBM extension. Issue the configure command to point to the location of the DB2 Client header files and libraries as follows:

    bash$ ./configure --with-pdo-ibm=/path/to/sqllib[,shared]

The configure command defaults to the value of the DB2DIR environment variable.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO_IBM Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
pdo_ibm.i5_dbcs_alloc | "0" | `INI_SYSTEM` | Added in PDO_IBM 1.5.0
pdo_ibm.i5_override_ccsid | "0" | `INI_SYSTEM` | Added in PDO_IBM 1.5.0

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`pdo_ibm.i5_dbcs_alloc` int

  This options affects the internal buffer allocation strategy on IBM i. By default, this option is 0. When this option is set, buffers are allocated with a much larger size, in case the database is misleading about character size when converting between encodings. This option uses six times as much memory for buffers (to account for the largest possible UTF-8 sequences), but may be needed if truncated data is returned.

  - 0 - Minimum size buffers are allocated.

  - 1 - Larger size buffers are allocated.

`pdo_ibm.i5_override_ccsid` int

  The ASCII CCSID to use for conversion from EBCDIC on IBM i. Setting this to 1208 will use UTF-8. By default, this is 0, which will select the default ASCII job CCSID.

  To learn more about CCSIDs on IBM i, consult the » IBM documentation.

# PDO_IBM DSN

(PECL PDO_IBM >= 0.9.0)

PDO_IBM DSN — Connecting to IBM databases

### Description

The PDO_IBM Data Source Name (DSN) is based on the IBM CLI DSN. The major components of the PDO_IBM DSN are:

DSN prefix

  The DSN prefix is `ibm:`.

DSN

  The DSN can be any of the following:

  - a) Data source setup using db2cli.ini or odbc.ini

  - b) Catalogued database name i.e. database alias in the DB2 client catalog

  - c) Complete connection string in the following format: `DRIVER={IBM DB2 ODBC DRIVER};DATABASE=`database`;HOSTNAME=`hostname`;PORT=`port`;PROTOCOL=TCPIP;UID=`username`;PWD=`password`;` where the parameters represent the following values:

    `database`

      The name of the database.

    `hostname`

      The hostname or IP address of the database server.

    `port`

      The TCP/IP port on which the database is listening for requests.

    `username`

      The username with which you are connecting to the database.

    `password`

      The password with which you are connecting to the database.

### Examples

Example #1 PDO_IBM DSN example using db2cli.ini

The following example shows a PDO_IBM DSN for connecting to an DB2 database cataloged as DB2_9 in db2cli.ini:

    $db = new PDO("ibm:DSN=DB2_9", "", "");

    [DB2_9]
    Database=testdb
    Protocol=tcpip
    Hostname=11.22.33.444
    Servicename=56789

Example #2 PDO_IBM DSN example using a connection string

The following example shows a PDO_IBM DSN for connecting to an DB2 database named `testdb` using the DB2 CLI connection string syntax.

    $db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
      "HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");

## Table of Contents

- PDO_IBM DSN — Connecting to IBM databases

# Informix PDO Driver (PDO_INFORMIX)

## Introduction

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

## Installation

To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or higher must be installed on the same system as PHP. The Informix Client SDK is available from the » IBM Informix Support Site.

PDO_INFORMIX is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_INFORMIX extension. Issue the configure command to point to the location of the Informix Client SDK header files and libraries as follows:

       bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]

The configure command defaults to the value of the INFORMIXDIR environment variable.

## Scrollable cursors

PDO_INFORMIX supports scrollable cursors; however, they are not enabled by default. To enable scrollable cursor support, you must either set `ENABLESCROLLABLECURSORS=1` in the corresponding ODBC connection settings in odbc.ini or pass the `EnableScrollableCursors=1` clause in the DSN connection string.

# PDO_INFORMIX DSN

(PECL PDO_INFORMIX >= 0.1.0)

PDO_INFORMIX DSN — Connecting to Informix databases

### Description

The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN string. Details on configuring an Informix ODBC DSN are available from the » Informix Dynamic Server Information Center. The major components of the PDO_INFORMIX DSN are:

DSN prefix

  The DSN prefix is `informix:`.

DSN

  The DSN can be either a data source setup using odbc.ini or a complete » connection string.

### Examples

Example #1 PDO_INFORMIX DSN example using odbc.ini

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database cataloged as Infdrv33 in odbc.ini:

    $db = new PDO("informix:DSN=Infdrv33", "", "");

    [ODBC Data Sources]
    Infdrv33=INFORMIX 3.3 32-BIT

    [Infdrv33]
    Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
    Description=INFORMIX 3.3 32-BIT
    Database=common_db
    LogonID=testuser
    pwd=testpass
    Servername=ids_server
    DB_LOCALE=en_US.819
    OPTIMIZEAUTOCOMMIT=1
    ENABLESCROLLABLECURSORS=1

Example #2 PDO_INFORMIX DSN example using a connection string

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database named `common_db` using the Informix connection string syntax.

    $db = new PDO("informix:host=host.domain.com; service=9800;
        database=common_db; server=ids_server; protocol=onsoctcp;
        EnableScrollableCursors=1", "testuser", "tespass");

## Table of Contents

- PDO_INFORMIX DSN — Connecting to Informix databases

# MySQL PDO Driver (PDO_MYSQL)

## Introduction

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL databases.

PDO_MYSQL uses emulated prepares by default.

MySQL 8

When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password plugin to mysql_native_password or else you will see errors similar to The server requested authentication method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.

This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP (mysqlnd) releases. Instead, change it by setting `default_authentication_plugin=mysql_native_password` in my.cnf. The caching_sha2_password plugin is fully supported as of PHP 7.4.4. For older releases, the mysql_xdevapi extension does support it.

Warning

Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.

> Note:

> The MySQL driver does not properly support `PDO::PARAM_INPUT_OUTPUT` via PDOStatement::bindParam(); while such parameters can be used, they are not updated (i.e. the actual output is ignored).

## Installation

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for the MySQL extensions, the extension libraries themselves may need to be installed using an additional package. Check the package manager that comes with your chosen distribution for availability.

For example, on Ubuntu the `php5-mysql` package installs the ext/mysql, ext/mysqli, and PDO_MYSQL PHP extensions. On CentOS, the `php-mysql` package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

When compiling, use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the optional `[=DIR]` is the MySQL base library. Mysqlnd is the default library. For details about choosing a library, see Choosing a MySQL library.

Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions, including PDO_MYSQL. If unspecified, the default locations are searched.

Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.

    $ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock

SSL support is enabled using the appropriate `Pdo\Mysql::ATTR_SSL_*`, which is equivalent to calling the » MySQL C API function mysql_ssl_set(). Also, SSL cannot be enabled with PDO::setAttribute() because the connection already exists. See also the MySQL documentation about » connecting to MySQL with SSL.

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` (int)
  Alias of `Pdo\Mysql::ATTR_USE_BUFFERED_QUERY`
`PDO::MYSQL_ATTR_LOCAL_INFILE` (int)
  Alias of `Pdo\Mysql::ATTR_LOCAL_INFILE`
`PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY` (int)
  Alias of `Pdo\Mysql::ATTR_LOCAL_INFILE_DIRECTORY`. Available as of PHP 8.1.0.
`PDO::MYSQL_ATTR_INIT_COMMAND` (int)
  Alias of `Pdo\Mysql::ATTR_INIT_COMMAND`
`PDO::MYSQL_ATTR_READ_DEFAULT_FILE` (int)
  Alias of `Pdo\Mysql::ATTR_READ_DEFAULT_FILE`
`PDO::MYSQL_ATTR_READ_DEFAULT_GROUP` (int)
  Alias of `Pdo\Mysql::ATTR_READ_DEFAULT_GROUP`
`PDO::MYSQL_ATTR_MAX_BUFFER_SIZE` (int)
  Alias of `Pdo\Mysql::ATTR_MAX_BUFFER_SIZE`
`PDO::MYSQL_ATTR_DIRECT_QUERY` (int)
  Alias of `PDO::ATTR_EMULATE_PREPARES`
`PDO::MYSQL_ATTR_FOUND_ROWS` (int)
  Alias of `Pdo\Mysql::ATTR_FOUND_ROWS`
`PDO::MYSQL_ATTR_IGNORE_SPACE` (int)
  Alias of `Pdo\Mysql::ATTR_IGNORE_SPACE`
`PDO::MYSQL_ATTR_COMPRESS` (int)
  Alias of `Pdo\Mysql::ATTR_COMPRESS`
`PDO::MYSQL_ATTR_SERVER_PUBLIC_KEY` (int)
  Alias of `Pdo\Mysql::ATTR_SERVER_PUBLIC_KEY`
`PDO::MYSQL_ATTR_SSL_CA` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_CA`
`PDO::MYSQL_ATTR_SSL_CAPATH` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_CAPATH`
`PDO::MYSQL_ATTR_SSL_CERT` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_CERT`
`PDO::MYSQL_ATTR_SSL_CIPHER` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_CIPHER`
`PDO::MYSQL_ATTR_SSL_KEY` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_KEY`
`PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT` (int)
  Alias of `Pdo\Mysql::ATTR_SSL_VERIFY_SERVER_CERT` Available as of PHP 7.0.18 and PHP 7.1.4.
`PDO::MYSQL_ATTR_MULTI_STATEMENTS` (int)
  Alias of `Pdo\Mysql::ATTR_MULTI_STATEMENTS`

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO_MYSQL Configuration Options
Name | Default | Changeable
--- | --- | ---
pdo_mysql.default_socket | "/tmp/mysql.sock" | `INI_SYSTEM`
pdo_mysql.debug | NULL | `INI_SYSTEM`

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`pdo_mysql.default_socket` string

  Sets a Unix domain socket. This value can either be set at compile time if a domain socket is found at configure. This ini setting is Unix only.

`pdo_mysql.debug` bool

  Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.

# PDO_MYSQL DSN

(PECL PDO_MYSQL >= 0.1.0)

PDO_MYSQL DSN — Connecting to MySQL databases

### Description

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `mysql:`.

`host`

  The hostname on which the database server resides.

`port`

  The port number where the database server is listening.

`dbname`

  The name of the database.

`unix_socket`

  The MySQL Unix socket (shouldn't be used with `host` or `port`).

`charset`

  The character set. See the character set concepts documentation for more information.

### Examples

Example #1 PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:

    mysql:host=localhost;dbname=testdb

More complete examples:

    mysql:host=localhost;port=3307;dbname=testdb
    mysql:unix_socket=/tmp/mysql.sock;dbname=testdb

### Notes

> Note: Unix only:

> When the host name is set to `"localhost"`, then the connection to the server is made through a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set through the pdo_mysql.default_socket setting.

## Table of Contents

- PDO_MYSQL DSN — Connecting to MySQL databases

# The Pdo\Mysql class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the MySQL PDO driver.

This driver supports a dedicated SQL query parser for the MySQL dialect. It can handle the following:

- Single and double-quoted literals with both doubling and backslash as escaping mechanisms
- Backtick literals with doubling as escaping mechanism
- Two-dashes, C-style comments, and Hash-comments.

## Class synopsis

class Pdo\Mysql extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int ATTR_USE_BUFFERED_QUERY;
public const int ATTR_LOCAL_INFILE;
public const int ATTR_LOCAL_INFILE_DIRECTORY;
public const int ATTR_INIT_COMMAND;
public const int ATTR_MAX_BUFFER_SIZE;
public const int ATTR_READ_DEFAULT_FILE;
public const int ATTR_READ_DEFAULT_GROUP;
public const int ATTR_COMPRESS;
public const int ATTR_DIRECT_QUERY;
public const int ATTR_FOUND_ROWS;
public const int ATTR_IGNORE_SPACE;
public const int ATTR_MULTI_STATEMENTS;
public const int ATTR_SERVER_PUBLIC_KEY;
public const int ATTR_SSL_KEY;
public const int ATTR_SSL_CERT;
public const int ATTR_SSL_CA;
public const int ATTR_SSL_CAPATH;
public const int ATTR_SSL_CIPHER;
public const int ATTR_SSL_VERIFY_SERVER_CERT;
/* Methods */
public getWarningCount(): int
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Mysql::ATTR_USE_BUFFERED_QUERY`
  By default all statements are executed in buffered mode. If this attribute is set to `false` on a Pdo\Mysql object, the MySQL driver will use the unbuffered mode.

  Example #1 Setting MySQL unbuffered mode

  `<?php
  $pdo = new Pdo\Mysql("mysql:host=localhost;dbname=world", 'my_user', 'my_password');
  $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
  $unbufferedResult = $pdo->query("SELECT Name FROM City");
  foreach ($unbufferedResult as $row) {
  echo $row['Name'] . PHP_EOL;
  }
  ?>`
`Pdo\Mysql::ATTR_LOCAL_INFILE`
  Enable `LOAD LOCAL INFILE`.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_LOCAL_INFILE_DIRECTORY`
  Allows restricting LOCAL DATA loading to files located in this designated directory.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_INIT_COMMAND`
  Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_READ_DEFAULT_FILE`
  Read options from the named option file instead of from my.cnf.

  > Note: This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

`Pdo\Mysql::ATTR_READ_DEFAULT_GROUP`
  Read options from the named group from my.cnf or the file specified with `Pdo\Mysql::ATTR_READ_DEFAULT_FILE`.

  > Note: This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

`Pdo\Mysql::ATTR_COMPRESS`
  Enable network communication compression.
`Pdo\Mysql::ATTR_DIRECT_QUERY`
  Alias of `PDO::ATTR_EMULATE_PREPARES`.
`Pdo\Mysql::ATTR_FOUND_ROWS`
  Return the number of found (matched) rows, not the number of changed rows.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_IGNORE_SPACE`
  Permit spaces after SQL function names. Makes all SQL functions names reserved words.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_MAX_BUFFER_SIZE`
  Maximum buffer size. Defaults to 1 MiB.

  > Note: This constant is not supported when compiled against mysqlnd.

`Pdo\Mysql::ATTR_MULTI_STATEMENTS`
  Disables multi query execution in both PDO::prepare() and PDO::query() when set to `false`.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SERVER_PUBLIC_KEY`
  RSA public key file used with the SHA-256 based authentication.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_KEY`
  The file path to the SSL key.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_CERT`
  The file path to the SSL certificate.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_CA`
  The file path to the SSL certificate authority.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_CAPATH`
  The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM format.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_CIPHER`
  A list of one or more permissible ciphers to use for SSL encryption, in a format understood by OpenSSL. For example: `DHE-RSA-AES256-SHA:AES128-SHA`

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

`Pdo\Mysql::ATTR_SSL_VERIFY_SERVER_CERT`
  Provides a way to disable verification of the server SSL certificate.

  > Note: This option is available only with mysqlnd.

  > Note: Can only be used in the `driver_options` array when constructing a new database handle.

# Pdo\Mysql::getWarningCount

(PHP 8 >= 8.4.0)

Pdo\Mysql::getWarningCount — Returns the number of warnings from the last executed query

### Description

public Pdo\Mysql::getWarningCount(): int

Returns the number of warnings from the last executed query.

> Note: For retrieving warning messages the following SQL command can be used: `SHOW WARNINGS [limit row_count]`.

### Parameters

This function has no parameters.

### Return Values

Returns an int representing the number of warnings generated by the last query.

### Examples

Example #1 Pdo\Mysql::getWarningCount() example

`<?php
$conn = PDO::connect("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password');
$conn->query('SELECT 42/0');
if ($conn->getWarningCount() > 0) {
$result = $conn->query("SHOW WARNINGS");
$row = $result->fetch();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}
?>`

The above example will output:

    Warning (1365): Division by 0

## Table of Contents

- Pdo\Mysql::getWarningCount — Returns the number of warnings from the last executed query

# Microsoft SQL Server PDO Driver (PDO_SQLSRV)

## Introduction

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

## Installation

The most recent version of the driver is available for download here: » SQLSRV download. The driver sources are hosted in a » public repository.

For more information about system requirements, see » SQLSRV System Requirements.

On Windows the PDO_SQLSRV extension is enabled by downloading and adding appropriate DLL files to the PHP extension directory and the corresponding entry to the php.ini file.

On Linux and macOS, the PDO_SQLSRV extension can be installed using » PECL. See the » installation tutorial for details.

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO::SQLSRV_TXN_READ_UNCOMMITTED` (int)
  This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Uncommitted.
`PDO::SQLSRV_TXN_READ_COMMITTED` (int)
  This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Committed.
`PDO::SQLSRV_TXN_REPEATABLE_READ` (int)
  This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Repeateable Read.
`PDO::SQLSRV_TXN_SNAPSHOT` (int)
  This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Snapshot.
`PDO::SQLSRV_TXN_SERIALIZABLE` (int)
  This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Serializable.
`PDO::SQLSRV_ENCODING_BINARY` (int)
  Specifies that data is sent/retrieved as a raw byte stream to/from the server without performing encoding or translation. This constant can be passed to PDOStatement::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
`PDO::SQLSRV_ENCODING_SYSTEM` (int)
  Specifies that data is sent/retrieved to/from the server as 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
`PDO::SQLSRV_ENCODING_UTF8` (int)
  Specifies that data is sent/retrieved to/from the server in UTF-8 encoding. This is the default encoding. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
`PDO::SQLSRV_ENCODING_DEFAULT` (int)
  Specifies that data is sent/retrieved to/from the server according to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The connection's encoding is used if specified in a prepare statement. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
`PDO::SQLSRV_ATTR_QUERY_TIMEOUT` (int)
  A non-negative integer representing the timeout period, in seconds. Zero (0) is the default and means no timeout. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, and PDO::prepare.
`PDO::SQLSRV_ATTR_DIRECT_QUERY` (int)
  Indicates that a query should be executed directly, without being prepared. This constant can be passed to PDO::setAttribute, and PDO::prepare. For more information, see » Direct and Prepared Statement Execution.

# PDO_SQLSRV DSN

(PECL pdo_sqlsrv >= 2.0.1)

PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

### Description

The PDO_SQLSRV Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `sqlsrv:`.

`APP`
  The application name used in tracing.
`ConnectionPooling`
  Specifies whether the connection is assigned from a connection pool (1 or `true`) or not (0 or `false`).
`Database`
  The name of the database.
`Encrypt`
  Specifies whether the communication with SQL Server is encrypted (1 or `true`) or unencrypted (0 or `false`).
`Failover_Partner`
  Specifies the server and instance of the database's mirror (if enabled and configured) to use when the primary server is unavailable.
`LoginTimeout`
  Specifies the number of seconds to wait before failing the connection attempt.
`MultipleActiveResultSets`
  Disables or explicitly enables support for multiple active Result sets (MARS).
`QuotedId`
  Specifies whether to use SQL-92 rules for quoted identifiers (1 or `true`) or to use legacy Transact-SQL rules (0 or `false`).
`Server`
  The name of the database server.
`TraceFile`
  Specifies the path for the file used for trace data.
`TraceOn`
  Specifies whether ODBC tracing is enabled (1 or `true`) or disabled (0 or `false`) for the connection being established.
`TransactionIsolation`
  Specifies the transaction isolation level. The accepted values for this option are PDO::SQLSRV_TXN_READ_UNCOMMITTED, PDO::SQLSRV_TXN_READ_COMMITTED, PDO::SQLSRV_TXN_REPEATABLE_READ, PDO::SQLSRV_TXN_SNAPSHOT, and PDO::SQLSRV_TXN_SERIALIZABLE.
`TrustServerCertificate`
  Specifies whether the client should trust (1 or `true`) or reject (0 or `false`) a self-signed server certificate.
`WSID`
  Specifies the name of the computer for tracing.

### Examples

Example #1 PDO_SQLSRV DSN examples

The following example shows how to connect to a specified MS SQL Server database:

    $c = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");

The following example shows how to connect to a MS SQL Server database on a specified port:

    $c = new PDO("sqlsrv:Server=localhost,1521;Database=testdb", "UserName", "Password");

The following example shows how to connect to a SQL Azure database with server ID 12345abcde. Note that when you connect to SQL Azure with PDO, your username will be UserName@12345abcde (UserName@ServerId).

    $c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");

## Table of Contents

- PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

# Oracle PDO Driver (PDO_OCI)

## Installation

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries. For details refer to the OCI8 Requirements section.

## PHP 8.4

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 8.4.0

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: » https://pecl.php.net/package/PDO_OCI.

## PHP < 8.4

Use --with-pdo-oci[=DIR] to install the PDO Oracle OCI extension, where the optional `[=DIR]` is the Oracle Home directory. `[=DIR]` defaults to the $ORACLE_HOME environment variable.

Use --with-pdo-oci=instantclient,prefix,version for an Oracle Instant Client SDK, where prefix and version are configured.

    // Using $ORACLE_HOME
    $ ./configure --with-pdo-oci

    // Using OIC for Linux with 10.2.0.3 RPMs with a /usr prefix
    $ ./configure --with-pdo-oci=instantclient,/usr,10.2.0.3

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO::OCI_ATTR_ACTION` (int)

  Provides a way to specify the action on the database session.

  This exists as of PHP 7.2.16 and 7.3.3

`PDO::OCI_ATTR_CLIENT_INFO` (int)

  Provides a way to specify the client info on the database session.

  This exists as of PHP 7.2.16 and 7.3.3

`PDO::OCI_ATTR_CLIENT_IDENTIFIER` (int)

  Provides a way to specify the client identifier on the database session.

  This exists as of PHP 7.2.16 and 7.3.3

`PDO::OCI_ATTR_MODULE` (int)

  Provides a way to specify the module on the database session.

  This exists as of PHP 7.2.16 and 7.3.3

# PDO_OCI DSN

(PECL PDO_OCI >= 0.1.0)

PDO_OCI DSN — Connecting to Oracle databases

### Description

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `oci:`.

`dbname` (Oracle Instant Client)

  The URI for the Oracle Instant Client connection takes the form of `dbname=//hostname:port-number/database`. If you are connecting to a database defined in tnsnames.ora, use only the name of the database: `dbname=database`.

`charset`

  The client-side character set for the current environment handle.

### Examples

Example #1 PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:

    // Connect to a database defined in tnsnames.ora
    oci:dbname=mydb

    // Connect using the Oracle Instant Client
    oci:dbname=//localhost:1521/mydb

## Table of Contents

- PDO_OCI DSN — Connecting to Oracle databases

# ODBC and DB2 PDO Driver (PDO_ODBC)

## Introduction

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:

ibm-db2

  Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 express-C client.

unixODBC

  Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

  Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN.

## Installation

PDO_ODBC on UNIX systems

1. PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.

   ibm_db2

         ./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/

     To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM developerWorks » website.

     If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

   unixODBC

         ./configure --with-pdo-odbc=unixODBC,/usr/local

     If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.
   generic

         ./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO_ODBC_TYPE` (string)

`PDO::ODBC_ATTR_USE_CURSOR_LIBRARY` (int)
  Alias of `Pdo\Odbc::ATTR_USE_CURSOR_LIBRARY`.
`PDO::ODBC_SQL_USE_IF_NEEDED` (int)
  Alias of `Pdo\Odbc::SQL_USE_IF_NEEDED`.
`PDO::ODBC_SQL_USE_DRIVER` (int)
  Alias of `Pdo\Odbc::SQL_USE_DRIVER`.
`PDO::ODBC_SQL_USE_ODBC` (int)
  Alias of `Pdo\Odbc::SQL_USE_ODBC`.
`PDO::ODBC_ATTR_ASSUME_UTF8` (bool)
  Alias of `Pdo\Odbc::ATTR_ASSUME_UTF8`.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO_ODBC Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
pdo_odbc.connection_pooling | "strict" | `INI_ALL` |
pdo_odbc.db2_instance_name | NULL | `INI_SYSTEM` | This deprecated feature will certainly be removed in the future.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`pdo_odbc.connection_pooling` string

  Whether to pool ODBC connections. Can be one of `"strict"`, `"relaxed"` or `"off"` (equals to `""`). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. `strict` is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. `relaxed` will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

  This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

  Warning

  `relaxed` matching should not be used on a shared server, for security reasons.

  Tip

  Leave this setting at the default `strict` setting unless you have good reason to change it.

`pdo_odbc.db2_instance_name` string

  If you compile PDO_ODBC using the `db2` flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

  This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

  This setting has no effect on Windows.

# PDO_ODBC DSN

(PECL PDO_ODBC >= 0.1.0)

PDO_ODBC DSN — Connecting to ODBC or DB2 databases

### Description

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

  The DSN prefix is `odbc:`. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

DSN

  The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at » http://www.connectionstrings.com/.

`UID`

  The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

`PWD`

  The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

### Changelog

Version | Description
--- | ---
8.4.0 | When passing an empty string to the password argument in the PDO constructor, `pwd` was not included in the connection string created until now, but the behavior has been changed to include it as an empty string. Passing `null` for the password argument in the PDO constructor results in the same behavior as before.
8.4.0 | Changed the behavior to ignore the user name argument and the password argument in the PDO constructor separately when the DSN contains `uid` or `pwd`. Previously, if included only either `uid` or `pwd` in the DSN, both the user name argument and the password argument in the PDO constructor were ignored.

### Examples

Example #1 PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

    odbc:testdb

Example #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named `SAMPLE` using the full ODBC DSN syntax:

    odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Example #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at `C:\db.mdb` using the full ODBC DSN syntax:

    odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

## Table of Contents

- PDO_ODBC DSN — Connecting to ODBC or DB2 databases

# The Pdo\Odbc class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the ODBC PDO driver.

## Class synopsis

namespace Pdo;
class Odbc extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int Pdo\Odbc::ATTR_USE_CURSOR_LIBRARY;
public const int Pdo\Odbc::ATTR_ASSUME_UTF8;
public const int Pdo\Odbc::SQL_USE_IF_NEEDED;
public const int Pdo\Odbc::SQL_USE_DRIVER;
public const int Pdo\Odbc::SQL_USE_ODBC;
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Odbc::ATTR_USE_CURSOR_LIBRARY`

  This option controls whether the ODBC cursor library is used. The ODBC cursor library supports some advanced ODBC features (e.g. block scrollable cursors), which may not be implemented by the driver. The following values are supported:

  `Pdo\Odbc::SQL_USE_IF_NEEDED`
    Use the ODBC cursor library when needed. This is the default.
  `Pdo\Odbc::SQL_USE_DRIVER`
    Never use the ODBC cursor library.
  `Pdo\Odbc::SQL_USE_ODBC`
    Always use the ODBC cursor library.
`Pdo\Odbc::ATTR_ASSUME_UTF8`
  Windows only. If `true`, UTF-16 encoded character data (`CHAR`, `VARCHAR` and `LONGVARCHAR`) is converted to UTF-8 when reading from or writing data to the database. If `false` (the default), character encoding conversion may be done by the driver.

# PostgreSQL PDO Driver (PDO_PGSQL)

## Introduction

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

## Resource Types

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

## Installation

Use --with-pdo-pgsql[=DIR] to install the PDO PostgreSQL extension, where the optional `[=DIR]` is the PostgreSQL base install directory, or the path to pg_config.

    $ ./configure --with-pdo-pgsql

## Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the `PDO::ATTR_DRIVER_NAME` attribute to check the driver, if your code can run against multiple drivers.

`PDO::PGSQL_ATTR_DISABLE_PREPARES` (int)
  Alias of `Pdo\Pgsql::ATTR_DISABLE_PREPARES`.

## General notes

> Note:

> `bytea` fields are returned as streams.

# PDO_PGSQL DSN

(PHP 5 >= 5.1.0, PHP 7, PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

### Description

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces or semicolons:

DSN prefix

  The DSN prefix is `pgsql:`.

`host`

  The hostname on which the database server resides.

`port`

  The port on which the database server is running.

`dbname`

  The name of the database.

`user`

  The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

`password`

  The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

`sslmode`

  The SSL mode. Supported values and their meaning are listed in the » PostgreSQL Documentation.

> Note: All semicolons in the DSN string are replaced by spaces, because PostgreSQL expects this format. This implies that semicolons in any of the components (e.g. `password` or `dbname`) are not supported.

### Examples

Example #1 PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:

    pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database via unix socket /tmp/.s.PGSQL.5432:

    pgsql:host=/tmp;port=5432;dbname=testdb;user=bruce;password=mypass

# PDO::pgsqlCopyFromArray

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyFromArray — Alias of Pdo\Pgsql::copyFromArray()

### Description

public PDO::pgsqlCopyFromArray(
string `$tableName`,
array `$rows`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

This method is an alias of: Pdo\Pgsql::copyFromArray().

# PDO::pgsqlCopyFromFile

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyFromFile — Alias of Pdo\Pgsql::copyFromFile()

### Description

public PDO::pgsqlCopyFromFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

This method is an alias of: Pdo\Pgsql::copyFromFile().

# PDO::pgsqlCopyToArray

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyToArray — Alias of Pdo\Pgsql::copyToArray()

### Description

public PDO::pgsqlCopyToArray(
string `$tableName`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): array|false

This method is an alias of: Pdo\Pgsql::copyToArray().

# PDO::pgsqlCopyToFile

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyToFile — Alias of Pdo\Pgsql::copyToFile()

### Description

public PDO::pgsqlCopyToFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

This method is an alias of: Pdo\Pgsql::copyToFile().

# PDO::pgsqlGetNotify

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

PDO::pgsqlGetNotify — Alias of Pdo\Pgsql::getNotify()

### Description

public PDO::pgsqlGetNotify(int `$fetchMode` = PDO::FETCH_DEFAULT, int `$timeoutMilliseconds` = 0): array|false

This method is an alias of: Pdo\Pgsql::getNotify().

# PDO::pgsqlGetPid

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

PDO::pgsqlGetPid — Alias of Pdo\Pgsql::getPid()

### Description

public PDO::pgsqlGetPid(): int

This method is an alias of: Pdo\Pgsql::getPid().

# PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Alias of Pdo\Pgsql::lobCreate()

### Description

public PDO::pgsqlLOBCreate(): string

This method is an alias of: Pdo\Pgsql::lobCreate().

# PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Alias of Pdo\Pgsql::lobOpen()

### Description

public PDO::pgsqlLOBOpen(string `$oid`, string `$mode` = "rb"): resource|false

This method is an alias of: Pdo\Pgsql::lobOpen().

# PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Alias of Pdo\Pgsql::lobUnlink()

### Description

public PDO::pgsqlLOBUnlink(string `$oid`): bool

This method is an alias of: Pdo\Pgsql::lobUnlink().

## Table of Contents

- PDO_PGSQL DSN — Connecting to PostgreSQL databases
- PDO::pgsqlCopyFromArray — Alias of Pdo\Pgsql::copyFromArray
- PDO::pgsqlCopyFromFile — Alias of Pdo\Pgsql::copyFromFile
- PDO::pgsqlCopyToArray — Alias of Pdo\Pgsql::copyToArray
- PDO::pgsqlCopyToFile — Alias of Pdo\Pgsql::copyToFile
- PDO::pgsqlGetNotify — Alias of Pdo\Pgsql::getNotify
- PDO::pgsqlGetPid — Alias of Pdo\Pgsql::getPid
- PDO::pgsqlLOBCreate — Alias of Pdo\Pgsql::lobCreate
- PDO::pgsqlLOBOpen — Alias of Pdo\Pgsql::lobOpen
- PDO::pgsqlLOBUnlink — Alias of Pdo\Pgsql::lobUnlink

# The Pdo\Pgsql class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the PostgreSQL PDO driver.

This driver supports a dedicated SQL query parser for the PostgreSQL dialect. It can handle the following:

- Single and double-quoted literals, with doubling as escaping mechanism
- C-style “escape” string literals
- Dollar-quoted string literals
- Two-dashes and C-style comments (non-nested).
- Support for `??` as escape sequence for the `?` operator.

## Class synopsis

namespace Pdo;
class Pgsql extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int Pdo\Pgsql::ATTR_DISABLE_PREPARES;
public const int Pdo\Pgsql::ATTR_RESULT_MEMORY_SIZE;
public const int Pdo\Pgsql::TRANSACTION_IDLE;
public const int Pdo\Pgsql::TRANSACTION_ACTIVE;
public const int Pdo\Pgsql::TRANSACTION_INTRANS;
public const int Pdo\Pgsql::TRANSACTION_INERROR;
public const int Pdo\Pgsql::TRANSACTION_UNKNOWN;
/* Methods */
public Pdo\Pgsql::copyFromArray(
string `$tableName`,
array `$rows`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool
public Pdo\Pgsql::copyFromFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool
public Pdo\Pgsql::copyToArray(
string `$tableName`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): array|false
public Pdo\Pgsql::copyToFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool
public Pdo\Pgsql::escapeIdentifier(string `$input`): string
public Pdo\Pgsql::getNotify(int `$fetchMode` = `PDO::FETCH_DEFAULT`, int `$timeoutMilliseconds` = 0): array|false
public Pdo\Pgsql::getPid(): int
public Pdo\Pgsql::lobCreate(): string|false
public Pdo\Pgsql::lobOpen(string `$oid`, string `$mode` = "rb"): resource|false
public Pdo\Pgsql::lobUnlink(string `$oid`): bool
public Pdo\Pgsql::setNoticeCallback(?callable `$callback`): void
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Pgsql::ATTR_DISABLE_PREPARES`
  Send the query and the parameters to the server together in a single call, avoiding the need to create a named prepared statement separately. If the query is only going to be executed once this can reduce latency by avoiding an unnecessary server round-trip.
`Pdo\Pgsql::ATTR_RESULT_MEMORY_SIZE`
  Returns the amount of memory, in bytes, allocated to the specified query result PDOStatement instance, or `null` if no results exist before the query is executed.
`Pdo\Pgsql::TRANSACTION_IDLE`
`Pdo\Pgsql::TRANSACTION_ACTIVE`
`Pdo\Pgsql::TRANSACTION_INTRANS`
`Pdo\Pgsql::TRANSACTION_INERROR`
`Pdo\Pgsql::TRANSACTION_UNKNOWN`

# Pdo\Pgsql::copyFromArray

(PHP 8 >= 8.4.0)

Pdo\Pgsql::copyFromArray — Copy data from a PHP array into a table

### Description

public Pdo\Pgsql::copyFromArray(
string `$tableName`,
array `$rows`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

Copies data from `rows` array to table `tableName` using `separator` as fields delimiter and `fields` list.

### Parameters

`tableName`
  String containing table name.
`rows`
  An indexed array of strings with fields separated by `separator`.
`separator`
  Delimiter used to separate fields in an entry of the `rows` array.
`nullAs`
  How to interpret SQL `NULL` values.
`fields`
  List of fields to insert.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- Pdo\Pgsql::copyToArray() - Copy data from database table into PHP array
- Pdo\Pgsql::copyFromFile() - Copy data from file into table
- Pdo\Pgsql::copyToFile() - Copy data from table into file

# Pdo\Pgsql::copyFromFile

(PHP 8 >= 8.4.0)

Pdo\Pgsql::copyFromFile — Copy data from file into table

### Description

public Pdo\Pgsql::copyFromFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

Copies data from file specified by `filename` into table `tableName` using `separator` as fields delimiter and `fields` list

### Parameters

`tableName`
  String containing table name.
`filename`
  Filename containing the data to import.
`separator`
  Delimiter used to separate fields in an entry of the `rows` array.
`nullAs`
  How to interpret SQL `NULL` values.
`fields`
  List of fields to insert.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- Pdo\Pgsql::copyToFile() - Copy data from table into file
- Pdo\Pgsql::copyFromArray() - Copy data from a PHP array into a table
- Pdo\Pgsql::copyToArray() - Copy data from database table into PHP array

# Pdo\Pgsql::copyToArray

(PHP 8 >= 8.4.0)

Pdo\Pgsql::copyToArray — Copy data from database table into PHP array

### Description

public Pdo\Pgsql::copyToArray(
string `$tableName`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): array|false

Copies data from `tableName` into array using `separator` as fields delimiter and `fields` list

### Parameters

`tableName`
  String containing table name.
`separator`
  Delimiter used to separate fields in an entry of the `rows` array.
`nullAs`
  How to interpret SQL `NULL` values.
`fields`
  List of fields to export.

### Return Values

Returns an array of rows, or `false` on failure.

### See Also

- Pdo\Pgsql::copyFromArray() - Copy data from a PHP array into a table
- Pdo\Pgsql::copyFromFile() - Copy data from file into table
- Pdo\Pgsql::copyToFile() - Copy data from table into file

# Pdo\Pgsql::copyToFile

(PHP 8 >= 8.4.0)

Pdo\Pgsql::copyToFile — Copy data from table into file

### Description

public Pdo\Pgsql::copyToFile(
string `$tableName`,
string `$filename`,
string `$separator` = "\t",
string `$nullAs` = "\\\\N",
?string `$fields` = `null`
): bool

Copies data from table into file specified by `filename` using `separator` as fields delimiter and `fields` list.

### Parameters

`tableName`
  String containing table name.
`filename`
  Filename to export data.
`separator`
  Delimiter used to separate fields in an entry of the `rows` array.
`nullAs`
  How to interpret SQL `NULL` values.
`fields`
  List of fields to insert.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- Pdo\Pgsql::copyFromFile() - Copy data from file into table
- Pdo\Pgsql::copyFromArray() - Copy data from a PHP array into a table
- Pdo\Pgsql::copyToArray() - Copy data from database table into PHP array

# Pdo\Pgsql::escapeIdentifier

(PHP 8 >= 8.4.0)

Pdo\Pgsql::escapeIdentifier — Escapes a string for use as an SQL identifier

### Description

public Pdo\Pgsql::escapeIdentifier(string `$input`): string

Escapes a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved.

### Parameters

`input`
  A string containing text to be escaped.

### Return Values

A string containing the escaped data.

### Examples

Example #1 Pdo\Pgsql::escapeIdentifier() example

`<?php
$pdo = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$unescapedTableName = 'UnescapedTableName';
$pdo->exec("CREATE TABLE $unescapedTableName ()");
$escapedTableName = $pdo->escapeIdentifier('EscapedTableName');
$pdo->exec("CREATE TABLE $escapedTableName ()");
$statement = $pdo->query(
"SELECT relname FROM pg_stat_user_tables WHERE relname ilike '%tablename'"
);
var_export($statement->fetchAll(PDO::FETCH_COLUMN, 0));
$tableNameWithSymbols = 'Table-Name-With-Symbols';
$pdo->exec("CREATE TABLE $tableNameWithSymbols ()");
?>`

The above example will output something similar to:

    array (
      0 => 'unescapedtablename',
      1 => 'EscapedTableName',
    )
    Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near "Table"
    LINE 1: CREATE TABLE Table-Name-With-Symbols ()

### See Also

- PDO::quote() - Quotes a string for use in a query

# Pdo\Pgsql::getNotify

(PHP 8 >= 8.4.0)

Pdo\Pgsql::getNotify — Get asynchronous notification

### Description

public Pdo\Pgsql::getNotify(int `$fetchMode` = `PDO::FETCH_DEFAULT`, int `$timeoutMilliseconds` = 0): array|false

Returns a result set representing a pending asynchronous notification.

### Parameters

`fetchMode`

  The format the result set should be returned as, one of the following constants:

  - `PDO::FETCH_DEFAULT`
  - `PDO::FETCH_BOTH`
  - `PDO::FETCH_ASSOC`
  - `PDO::FETCH_NUM`
`timeoutMilliseconds`
  The length of time to wait for a response, in milliseconds.

### Return Values

If one or more notifications is pending, returns a single row, with fields `message` and `pid`, otherwise returns `false`.

### Errors/Exceptions

A ValueError is thrown if `fetchMode` is not one of the valid `PDO::FETCH_*` constants.

A ValueError is thrown if `timeoutMilliseconds` is less than `0`.

A `E_WARNING` is raised when `timeoutMilliseconds` is greater than the value that can be contained in a signed 32-bit integer, in which case it will be the maximum value of a signed 32-bit integer.

### See Also

- PDO::query() - Prepares and executes an SQL statement without placeholders
- PDOStatement::fetch() - Fetches the next row from a result set
- PDOStatement::fetchAll() - Fetches the remaining rows from a result set

# Pdo\Pgsql::getPid

(PHP 8 >= 8.4.0)

Pdo\Pgsql::getPid — Get the PID of the backend process handling this connection

### Description

public Pdo\Pgsql::getPid(): int

Returns the PID of the backend process handling this connection. Note that the PID belongs to a process executing on the database server host, not the local host.

### Parameters

This function has no parameters.

### Return Values

Returns the PID as an int.

# Pdo\Pgsql::lobCreate

(PHP 8 >= 8.4.0)

Pdo\Pgsql::lobCreate — Creates a new large object

### Description

public Pdo\Pgsql::lobCreate(): string|false

Pdo\Pgsql::lobCreate() creates a large object and returns the OID which refers to it. It can be opened to read or write data with Pdo\Pgsql::lobOpen().

The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling Pdo\Pgsql::lobUnlink().

Large objects are cumbersome to use. Indeed, it is required that Pdo\Pgsql::lobUnlink() is called prior to deleting the last row referencing the OID in the entire database; otherwise, unreferenced large objects will remain on the server indefinitely. Moreover, large objects have no access controls. An alternative is the bytea column type, which can be up to 1GB in size, and this column type transparently manages the storage for optimal row size.

> Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

### Parameters

This function has no parameters.

### Return Values

Returns the OID of the newly created large object on success, or `false` on failure.

### Examples

Example #1 Pdo\Pgsql::lobCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

`<?php
$db = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->lobCreate();
$stream = $db->lobOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute([$some_id, $oid]);
$db->commit();
?>`

### See Also

- Pdo\Pgsql::lobOpen() - Opens an existing large object stream
- Pdo\Pgsql::lobUnlink() - Deletes the large object
- pg_lo_create() - Create a large object
- pg_lo_open() - Open a large object

# Pdo\Pgsql::lobOpen

(PHP 8 >= 8.4.0)

Pdo\Pgsql::lobOpen — Opens an existing large object stream

### Description

public Pdo\Pgsql::lobOpen(string `$oid`, string `$mode` = "rb"): resource|false

Pdo\Pgsql::lobOpen() opens a stream to access the data referenced by `oid`. All usual filesystem functions, such as fread(), fwrite() or fgets() can be used to manipulate the contents of the stream.

> Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

### Parameters

`oid`
  A large object identifier.
`mode`
  If mode is `r`, open the stream for reading. If mode is `w`, open the stream for writing.

### Return Values

Returns a stream resource on success, or `false` on failure.

### Examples

Example #1 Pdo\Pgsql::lobOpen() example

Following on from the Pdo\Pgsql::lobCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

`<?php
$db = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT oid FROM BLOBS WHERE ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $oid, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $db->pgsqlLOBOpen($oid, 'r');
header("Content-type: application/octet-stream");
fpassthru($stream);
?>`

### See Also

- Pdo\Pgsql::lobCreate() - Creates a new large object
- Pdo\Pgsql::lobUnlink() - Deletes the large object
- pg_lo_create() - Create a large object
- pg_lo_open() - Open a large object

# Pdo\Pgsql::lobUnlink

(PHP 8 >= 8.4.0)

Pdo\Pgsql::lobUnlink — Deletes the large object

### Description

public Pdo\Pgsql::lobUnlink(string `$oid`): bool

Deletes a large object from the database identified by OID.

> Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

### Parameters

`oid`
  A large object identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Pdo\Pgsql::lobUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table are used in the examples of Pdo\Pgsql::lobCreate() and Pdo\Pgsql::lobOpen().

`<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>`

### See Also

- Pdo\Pgsql::lobCreate() - Creates a new large object
- Pdo\Pgsql::lobOpen() - Opens an existing large object stream
- pg_lo_create() - Create a large object
- pg_lo_open() - Open a large object

# Pdo\Pgsql::setNoticeCallback

(PHP 8 >= 8.4.0)

Pdo\Pgsql::setNoticeCallback — Set a callback to handle notice and warning messages generated by the backend

### Description

public Pdo\Pgsql::setNoticeCallback(?callable `$callback`): void

Set a callback to handle notice and warning messages generated by the backend. This includes messages emitted by PostgreSQL itself, as well as those raised by user-defined SQL functions using `RAISE`. Please note that the actual receipt of these messages depends on the backend setting `client_min_messages`.

### Parameters

`callback`
  If `null` is passed, the handler is reset to its default state.

  Otherwise, the handler is a callback with the following signature:

  handler(string `$message`): void
  `message`
    A message generated by the backend.

### Return Values

No value is returned.

### Examples

Example #1 Pdo\Pgsql::setNoticeCallback() example

`<?php
$pdo = new Pdo\Pgsql('pgsql:dbname=test host=localhost', $user, $pass);
$pdo->exec('CREATE TABLE parent(id int primary key)');
$pdo->exec('CREATE TABLE child(id int references parent)');
$pdo->setNoticeCallback(function ($message) {
echo $message;
});
$pdo->exec('TRUNCATE parent CASCADE');
?>`

The above example will output something similar to:

    NOTICE:  truncate cascades to table "child"

## Table of Contents

- Pdo\Pgsql::copyFromArray — Copy data from a PHP array into a table
- Pdo\Pgsql::copyFromFile — Copy data from file into table
- Pdo\Pgsql::copyToArray — Copy data from database table into PHP array
- Pdo\Pgsql::copyToFile — Copy data from table into file
- Pdo\Pgsql::escapeIdentifier — Escapes a string for use as an SQL identifier
- Pdo\Pgsql::getNotify — Get asynchronous notification
- Pdo\Pgsql::getPid — Get the PID of the backend process handling this connection
- Pdo\Pgsql::lobCreate — Creates a new large object
- Pdo\Pgsql::lobOpen — Opens an existing large object stream
- Pdo\Pgsql::lobUnlink — Deletes the large object
- Pdo\Pgsql::setNoticeCallback — Set a callback to handle notice and warning messages generated by the backend

# SQLite PDO Driver (PDO_SQLITE)

## Introduction

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

> Note:

> PDO_SQLITE allows using strings apart from streams together with `PDO::PARAM_LOB`.

## Installation

The PDO_SQLITE PDO driver is enabled by default. To disable, --without-pdo-sqlite[=DIR] may be used, where the optional `[=DIR]` is the sqlite base install directory. As of PHP 7.4.0 » libsqlite ≥ 3.5.0 is required. Formerly, the bundled libsqlite could have been used instead, and was the default, if `[=DIR]` has been omitted.

> Note: Additional setup on Windows as of PHP 7.4.0

> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsqlite3.dll.

# PDO_SQLITE DSN

(PHP 5 >= 5.1.0, PHP 7, PECL PDO_SQLITE >= 0.2.0)

PDO_SQLITE DSN — Connecting to SQLite databases

### Description

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

  The DSN prefix is `sqlite:`.

  - To access a database on disk, the absolute path has to be appended to the DSN prefix.

  - To create a database in memory, `:memory:` has to be appended to the DSN prefix.

  - If the DSN consists of the DSN prefix only, a temporary database is used, which is deleted when the connection is closed.

### Examples

Example #1 PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:

    sqlite:/opt/databases/mydb.sq3
    sqlite::memory:
    sqlite:

# PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Alias of Pdo\Sqlite::createAggregate()

### Description

public PDO::sqliteCreateAggregate(
string `$name`,
callable `$step`,
callable `$finalize`,
int `$numArgs` = -1
): bool

This method is an alias of: Pdo\Sqlite::createAggregate().

# PDO::sqliteCreateCollation

(PHP 5 >= 5.3.11, PHP 7, PHP 8)

PDO::sqliteCreateCollation — Alias of Pdo\Sqlite::createCollation()

### Description

public PDO::sqliteCreateCollation(string `$name`, callable `$callback`): bool

This method is an alias of: Pdo\Sqlite::createCollation().

# PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Alias of Pdo\Sqlite::createFunction()

### Description

public PDO::sqliteCreateFunction(
string `$function_name`,
callable `$callback`,
int `$num_args` = -1,
int `$flags` = 0
): bool

This method is an alias of: Pdo\Sqlite::createFunction().

### Changelog

Version | Description
--- | ---
7.1.4 | The `flags` parameter has been added.

## Table of Contents

- PDO_SQLITE DSN — Connecting to SQLite databases
- PDO::sqliteCreateAggregate — Alias of Pdo\Sqlite::createAggregate
- PDO::sqliteCreateCollation — Alias of Pdo\Sqlite::createCollation
- PDO::sqliteCreateFunction — Alias of Pdo\Sqlite::createFunction

# The Pdo\Sqlite class

(PHP 8 >= 8.4.0)

## Introduction

A PDO subclass representing a connection using the SQLite PDO driver.

This driver supports a dedicated SQL query parser for the SQLite dialect. It can handle the following:

- Single, double-quoted, and backtick literals, with doubling as escaping mechanism.
- Square brackets quoting for identifiers.
- Two-dashes and C-style comments (non-nested).

## Class synopsis

class Pdo\Sqlite extends PDO {
/* Inherited constants */
public const int PDO::PARAM_NULL;
public const int PDO::PARAM_BOOL = 5;
public const int PDO::PARAM_INT = 1;
public const int PDO::PARAM_STR = 2;
public const int PDO::PARAM_LOB = 3;
public const int PDO::PARAM_STMT = 4;
public const int PDO::PARAM_INPUT_OUTPUT;
public const int PDO::PARAM_STR_NATL;
public const int PDO::PARAM_STR_CHAR;
public const int PDO::PARAM_EVT_ALLOC;
public const int PDO::PARAM_EVT_FREE;
public const int PDO::PARAM_EVT_EXEC_PRE;
public const int PDO::PARAM_EVT_EXEC_POST;
public const int PDO::PARAM_EVT_FETCH_PRE;
public const int PDO::PARAM_EVT_FETCH_POST;
public const int PDO::PARAM_EVT_NORMALIZE;
public const int PDO::FETCH_DEFAULT;
public const int PDO::FETCH_LAZY;
public const int PDO::FETCH_ASSOC;
public const int PDO::FETCH_NUM;
public const int PDO::FETCH_BOTH;
public const int PDO::FETCH_OBJ;
public const int PDO::FETCH_BOUND;
public const int PDO::FETCH_COLUMN;
public const int PDO::FETCH_CLASS;
public const int PDO::FETCH_INTO;
public const int PDO::FETCH_FUNC;
public const int PDO::FETCH_GROUP;
public const int PDO::FETCH_UNIQUE;
public const int PDO::FETCH_KEY_PAIR;
public const int PDO::FETCH_CLASSTYPE;
public const int PDO::FETCH_SERIALIZE;
public const int PDO::FETCH_PROPS_LATE;
public const int PDO::FETCH_NAMED;
public const int PDO::ATTR_AUTOCOMMIT;
public const int PDO::ATTR_PREFETCH;
public const int PDO::ATTR_TIMEOUT;
public const int PDO::ATTR_ERRMODE;
public const int PDO::ATTR_SERVER_VERSION;
public const int PDO::ATTR_CLIENT_VERSION;
public const int PDO::ATTR_SERVER_INFO;
public const int PDO::ATTR_CONNECTION_STATUS;
public const int PDO::ATTR_CASE;
public const int PDO::ATTR_CURSOR_NAME;
public const int PDO::ATTR_CURSOR;
public const int PDO::ATTR_ORACLE_NULLS;
public const int PDO::ATTR_PERSISTENT;
public const int PDO::ATTR_STATEMENT_CLASS;
public const int PDO::ATTR_FETCH_TABLE_NAMES;
public const int PDO::ATTR_FETCH_CATALOG_NAMES;
public const int PDO::ATTR_DRIVER_NAME;
public const int PDO::ATTR_STRINGIFY_FETCHES;
public const int PDO::ATTR_MAX_COLUMN_LEN;
public const int PDO::ATTR_EMULATE_PREPARES;
public const int PDO::ATTR_DEFAULT_FETCH_MODE;
public const int PDO::ATTR_DEFAULT_STR_PARAM;
public const int PDO::ERRMODE_SILENT;
public const int PDO::ERRMODE_WARNING;
public const int PDO::ERRMODE_EXCEPTION;
public const int PDO::CASE_NATURAL;
public const int PDO::CASE_LOWER;
public const int PDO::CASE_UPPER;
public const int PDO::NULL_NATURAL;
public const int PDO::NULL_EMPTY_STRING;
public const int PDO::NULL_TO_STRING;
public const string PDO::ERR_NONE;
public const int PDO::FETCH_ORI_NEXT;
public const int PDO::FETCH_ORI_PRIOR;
public const int PDO::FETCH_ORI_FIRST;
public const int PDO::FETCH_ORI_LAST;
public const int PDO::FETCH_ORI_ABS;
public const int PDO::FETCH_ORI_REL;
public const int PDO::CURSOR_FWDONLY;
public const int PDO::CURSOR_SCROLL;
/* Constants */
public const int DETERMINISTIC;
public const int OPEN_READONLY;
public const int OPEN_READWRITE;
public const int OPEN_CREATE;
public const int ATTR_OPEN_FLAGS;
public const int ATTR_READONLY_STATEMENT;
public const int ATTR_EXTENDED_RESULT_CODES;
/* Methods */
public createAggregate(
string `$name`,
callable `$step`,
callable `$finalize`,
int `$numArgs` = -1
): bool
public createCollation(string `$name`, callable `$callback`): bool
public createFunction(
string `$function_name`,
callable `$callback`,
int `$num_args` = -1,
int `$flags` = 0
): bool
public loadExtension(string `$name`): void
public openBlob(
string `$table`,
string `$column`,
int `$rowid`,
?string `$dbname` = "main",
int `$flags` = `Pdo\Sqlite::OPEN_READONLY`
): resource|false
/* Inherited methods */
public PDO::__construct(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
)
public PDO::beginTransaction(): bool
public PDO::commit(): bool
public static PDO::connect(
string `$dsn`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?array `$options` = `null`
): static
public PDO::errorCode(): ?string
public PDO::errorInfo(): array
public PDO::exec(string `$statement`): int|false
public PDO::getAttribute(int `$attribute`): mixed
public static PDO::getAvailableDrivers(): array
public PDO::inTransaction(): bool
public PDO::lastInsertId(?string `$name` = `null`): string|false
public PDO::prepare(string `$query`, array `$options` = []): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = `null`): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_COLUMN, int `$colno`): PDOStatement|false
public PDO::query(
string `$query`,
?int `$fetchMode` = PDO::FETCH_CLASS,
string `$classname`,
array `$constructorArgs`
): PDOStatement|false
public PDO::query(string `$query`, ?int `$fetchMode` = PDO::FETCH_INTO, object `$object`): PDOStatement|false
public PDO::quote(string `$string`, int `$type` = `PDO::PARAM_STR`): string|false
public PDO::rollBack(): bool
public PDO::setAttribute(int `$attribute`, mixed `$value`): bool
}

## Predefined Constants

`Pdo\Sqlite::DETERMINISTIC`
`Pdo\Sqlite::OPEN_READONLY`
`Pdo\Sqlite::OPEN_READWRITE`
`Pdo\Sqlite::OPEN_CREATE`
`Pdo\Sqlite::ATTR_OPEN_FLAGS`
`Pdo\Sqlite::ATTR_READONLY_STATEMENT`
`Pdo\Sqlite::ATTR_EXTENDED_RESULT_CODES`

# Pdo\Sqlite::createAggregate

(PHP 8 >= 8.4.0)

Pdo\Sqlite::createAggregate — Registers an aggregating user-defined function for use in SQL statements

### Description

public Pdo\Sqlite::createAggregate(
string `$name`,
callable `$step`,
callable `$finalize`,
int `$numArgs` = -1
): bool

This method is similar to Pdo\Sqlite::createFunction() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this method and Pdo\Sqlite::createFunction() is that two functions are required to manage the aggregate.

Tip

By using this method it is possible to override native SQL functions.

### Parameters

`name`
  The name of the function used in SQL statements.
`step`
  Callback function called for each row of the result set. The callback should accumulate the result and store it in the aggregation context.

  This function need to be defined as:

  step(
  mixed `$context`,
  int `$rownumber`,
  mixed `$value`,
  mixed `...$values`
  ): mixed
  `context`
    `null` for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.
  `rownumber`
    The current row number.
  `value`
    The first argument passed to the aggregate.
  `values`
    Further arguments passed to the aggregate.
  The return value of this function will be used as the `context` argument in the next call of the step or finalize functions.
`finalize`
  Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called, and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).

  This function need to be defined as:

  fini(mixed `$context`, int `$rowcount`): mixed
  `context`

    Holds the return value from the very last call to the step function.

  `rowcount`

    Holds the number of rows over which the aggregate was performed.

  The return value of this function will be used as the return value for the aggregate.
`numArgs`
  Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Pdo\Sqlite::createAggregate() example

In this example we will create a custom aggregate function named `max_length` that can be used in SQL queries.

In this example, we are creating an aggregating function, named `max_length`, that will calculate the length of the longest string in one of the columns of the table. For each row, the `max_len_step` function is called and passed a `$context` parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object. In this example, we are using it to hold the maximum length we have seen so far; if the $string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all the rows have been processed, SQLite calls the `max_len_finalize` function to determine the aggregate result. It is possible to perform some kind of calculation based on the data in `$context`. In this basic example the result was calculated as the query progressed, thus so the context value can be directly returned.

`<?php
$data = [
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
];
$db = new Pdo\Sqlite('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->execute(array($str));
}
$insert = null;
function max_len_step($context, $row_number, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}
function max_len_finalize($context, $row_count)
{
return $context === null ? 0 : $context;
}
$db->createAggregate('max_len', 'max_len_step', 'max_len_finalize');
var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());
?>`
Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

### See Also

- Pdo\Sqlite::createFunction() - Registers a user-defined function for use in SQL statements
- Pdo\Sqlite::createCollation() - Registers a user-defined function for use as a collating function in SQL statements
- sqlite_create_function()
- sqlite_create_aggregate()

# Pdo\Sqlite::createCollation

(PHP 8 >= 8.4.0)

Pdo\Sqlite::createCollation — Registers a user-defined function for use as a collating function in SQL statements

### Description

public Pdo\Sqlite::createCollation(string `$name`, callable `$callback`): bool

This method is similar to Pdo\Sqlite::createFunction() except that it registers functions that are used to collate strings.

### Parameters

`name`
  Name of the SQL collating function to be created or redefined.
`callback`
  Callback function that defines the behaviour of a collation. It must accept two strings and return `-1`, `0`, or `1` if the first string sorts before, sorts identically, or sorts after the second string respectively. An internal function that behaves like this is strcmp().

  This function need to be defined as:

  collation(string `$string1`, string `$string2`): int

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Pdo\Sqlite::createCollation() example

`<?php
$db = new Pdo\Sqlite('sqlite::memory:');
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");
$db->sqliteCreateCollation('NATURAL_CMP', 'strnatcmp');
foreach ($db->query("SELECT col1 FROM test ORDER BY col1") as $row) {
echo $row['col1'] . "\n";
}
echo "\n";
foreach ($db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP") as $row) {
echo $row['col1'] . "\n";
}
?>`

The above example will output:

    a1
    a10
    a2

    a1
    a2
    a10

### See Also

- Pdo\Sqlite::createFunction() - Registers a user-defined function for use in SQL statements
- Pdo\Sqlite::createAggregate() - Registers an aggregating user-defined function for use in SQL statements
- sqlite_create_function()
- sqlite_create_aggregate()

# Pdo\Sqlite::createFunction

(PHP 8 >= 8.4.0)

Pdo\Sqlite::createFunction — Registers a user-defined function for use in SQL statements

### Description

public Pdo\Sqlite::createFunction(
string `$function_name`,
callable `$callback`,
int `$num_args` = -1,
int `$flags` = 0
): bool

This method allows PHP function to be registered with SQLite as a user-defined function, so that it can be called within SQL queries. The defined function can be used in any SQL query that allows function calls, for example `SELECT`, `UPDATE`, or triggers.

Tip

By using this method it is possible to override native SQL functions.

### Parameters

`function_name`
  The name of the function used in SQL statements.
`callback`
  Callback function to handle the defined SQL function.

  > Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

  This function need to be defined as:

  callback(mixed `$value`, mixed `...$values`): mixed
  `value`

    The first argument passed to the SQL function.

  `values`

    Further arguments passed to the SQL function.

`num_args`
  The number of arguments that the SQL function takes. If this parameter is `-1`, then the SQL function may take any number of arguments.
`flags`
  A bitmask of flags. Currently, only `Pdo\Sqlite::DETERMINISTIC` is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Pdo\Sqlite::createFunction() example

In this example, we have a function that calculates the SHA256 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that there is no need to process the result using a `foreach` loop after the query.

`<?php
function sha256_and_reverse($string)
{
return strrev(hash('sha256', $string));
}
$db = new Pdo\Sqlite('sqlite::sqlitedb');
$db->createFunction('sha256rev', 'sha256_and_reverse', 1);
$rows = $db->query('SELECT sha256rev(filename) FROM files')->fetchAll();
?>`

### See Also

- Pdo\Sqlite::createAggregate() - Registers an aggregating user-defined function for use in SQL statements
- Pdo\Sqlite::createCollation() - Registers a user-defined function for use as a collating function in SQL statements
- sqlite_create_function()
- sqlite_create_aggregate()

# Pdo\Sqlite::loadExtension

(PHP 8 >= 8.4.0)

Pdo\Sqlite::loadExtension — Description

### Description

public Pdo\Sqlite::loadExtension(string `$name`): void
Warning

This function is currently not documented; only its argument list is available.

Description.

### Parameters

`name`
  Description.

### Return Values

No value is returned.

### Errors/Exceptions

When does this function issue `E_*` level errors, and/or throw Exceptions.

### Examples

Example #1 Pdo\Sqlite::loadExtension() example

Description.

`<?php
echo "Code example";
?>`

The above example will output:

    Code example

### Notes

> Note: Any notes that don't fit anywhere else should go here.

### See Also

- ClassName::otherMethodName()
- some_function()

# Pdo\Sqlite::openBlob

(PHP 8 >= 8.4.0)

Pdo\Sqlite::openBlob — Description

### Description

public Pdo\Sqlite::openBlob(
string `$table`,
string `$column`,
int `$rowid`,
?string `$dbname` = "main",
int `$flags` = `Pdo\Sqlite::OPEN_READONLY`
): resource|false
Warning

This function is currently not documented; only its argument list is available.

Description.

### Parameters

`table`
  Description.
`column`
  Description.
`rowid`
  Description.
`dbname`
  Description.
`flags`
  One of the `Pdo\Sqlite::OPEN_*`

### Return Values

Description.

### Errors/Exceptions

When does this function issue `E_*` level errors, and/or throw Exceptions.

### Examples

Example #1 Pdo\Sqlite::openBlob() example

Description.

`<?php
echo "Code example";
?>`

The above example will output:

    Code example

### Notes

> Note: Any notes that don't fit anywhere else should go here.

### See Also

- ClassName::otherMethodName()
- some_function()

## Table of Contents

- Pdo\Sqlite::createAggregate — Registers an aggregating user-defined function for use in SQL statements
- Pdo\Sqlite::createCollation — Registers a user-defined function for use as a collating function in SQL statements
- Pdo\Sqlite::createFunction — Registers a user-defined function for use in SQL statements
- Pdo\Sqlite::loadExtension — Description
- Pdo\Sqlite::openBlob — Description

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Predefined Constants
  - Fetch Modes
- Connections and Connection management
- Transactions and auto-commit
- Prepared statements and stored procedures
- Errors and error handling
- Large Objects (LOBs)
- PDO — The PDO class
  - PDO::beginTransaction — Initiates a transaction
  - PDO::commit — Commits a transaction
  - PDO::connect — Connect to a database and return a PDO subclass for drivers that support it
  - PDO::__construct — Creates a PDO instance representing a connection to a database
  - PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
  - PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
  - PDO::exec — Execute an SQL statement and return the number of affected rows
  - PDO::getAttribute — Retrieve a database connection attribute
  - PDO::getAvailableDrivers — Return an array of available PDO drivers
  - PDO::inTransaction — Checks if inside a transaction
  - PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
  - PDO::prepare — Prepares a statement for execution and returns a statement object
  - PDO::query — Prepares and executes an SQL statement without placeholders
  - PDO::quote — Quotes a string for use in a query
  - PDO::rollBack — Rolls back a transaction
  - PDO::setAttribute — Set an attribute
- PDOStatement — The PDOStatement class
  - PDOStatement::bindColumn — Bind a column to a PHP variable
  - PDOStatement::bindParam — Binds a parameter to the specified variable name
  - PDOStatement::bindValue — Binds a value to a parameter
  - PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again
  - PDOStatement::columnCount — Returns the number of columns in the result set
  - PDOStatement::debugDumpParams — Dump an SQL prepared command
  - PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
  - PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle
  - PDOStatement::execute — Executes a prepared statement
  - PDOStatement::fetch — Fetches the next row from a result set
  - PDOStatement::fetchAll — Fetches the remaining rows from a result set
  - PDOStatement::fetchColumn — Returns a single column from the next row of a result set
  - PDOStatement::fetchObject — Fetches the next row and returns it as an object
  - PDOStatement::getAttribute — Retrieve a statement attribute
  - PDOStatement::getColumnMeta — Returns metadata for a column in a result set
  - PDOStatement::getIterator — Gets result set iterator
  - PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle
  - PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement
  - PDOStatement::setAttribute — Set a statement attribute
  - PDOStatement::setFetchMode — Set the default fetch mode for this statement
- PDORow — The PDORow class
- PDOException — The PDOException class
- PDO Drivers
  - CUBRID PDO Driver — CUBRID PDO Driver (PDO_CUBRID)
  - MS SQL Server PDO Driver — Microsoft SQL Server and Sybase PDO Driver (PDO_DBLIB)
  - Pdo\Dblib — The Pdo\Dblib class
  - Firebird PDO Driver — Firebird PDO Driver (PDO_FIREBIRD)
  - Pdo\Firebird — The Pdo\Firebird class
  - IBM PDO Driver — IBM PDO Driver (PDO_IBM)
  - Informix PDO Driver — Informix PDO Driver (PDO_INFORMIX)
  - MySQL PDO Driver — MySQL PDO Driver (PDO_MYSQL)
  - Pdo\Mysql — The Pdo\Mysql class
  - MS SQL Server PDO Driver — Microsoft SQL Server PDO Driver (PDO_SQLSRV)
  - Oracle PDO Driver — Oracle PDO Driver (PDO_OCI)
  - ODBC and DB2 PDO Driver — ODBC and DB2 PDO Driver (PDO_ODBC)
  - Pdo\Odbc — The Pdo\Odbc class
  - PostgreSQL PDO Driver — PostgreSQL PDO Driver (PDO_PGSQL)
  - Pdo\Pgsql — The Pdo\Pgsql class
  - SQLite PDO Driver — SQLite PDO Driver (PDO_SQLITE)
  - Pdo\Sqlite — The Pdo\Sqlite class

- DBA — Database (dbm-style) Abstraction Layer
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Dba\Connection — The Dba\Connection class
  - DBA Functions
- ODBC — ODBC (Unified)
  - Installing/Configuring
  - Predefined Constants
  - ODBC Functions
- PDO — PHP Data Objects
  - Installing/Configuring
  - Predefined Constants
  - Connections and Connection management
  - Transactions and auto-commit
  - Prepared statements and stored procedures
  - Errors and error handling
  - Large Objects (LOBs)
  - PDO — The PDO class
  - PDOStatement — The PDOStatement class
  - PDORow — The PDORow class
  - PDOException — The PDOException class
  - PDO Drivers

# Vendor Specific Database Extensions

# CUBRID

# Introduction

These functions allow you to access CUBRID database servers. More information about CUBRID can be found at » CUBRID.

Documentation for CUBRID can be found at » CUBRID Documentation.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

In order to have these functions available, you must install CUBRID, and compile CUBRID PHP Library with CUBRID support.

## Installation

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: » https://pecl.php.net/package/cubrid.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

For information about manual installation on Linux and Windows systems, please read the file build-guide.html included in the package.

## Runtime Configuration

There is no runtime configuration now.

## Resource Types

There are four resource types used in CUBRID. The first one is the link identifier for a database connection, the second is the a resource which holds the result of a query, and the last two a resource which holds the query results of BLOB/CLOB data types.

## connection identifier

A connection identifier returned by cubrid_connect(), cubrid_connect_with_url(), cubrid_pconnect() and cubrid_pconnect_with_url().

## request identifier

A request identifier returned by cubrid_prepare() and cubrid_execute().

## LOB identifier

A LOB identifier returned by cubrid_lob_get().

## LOB2 identifier

A LOB identifier returned by cubrid_lob2_new() or get from the result set.

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

The following constants can be used when executing SQL statement. They can be passed to cubrid_prepare() and cubrid_execute().

CUBRID SQL execution flags
Constant | Description
--- | ---
`CUBRID_INCLUDE_OID` | Determine whether to get OID during query execution.
`CUBRID_ASYNC` | Execute the query in asynchronous mode.
`CUBRID_EXEC_QUERY_ALL` | Execute the query in synchronous mode. This flag must be set when executing multiple SQL statements.

The following constants can be used when fetching the results to specify fetch behaviour. They can be passed to cubrid_fetch() and cubrid_fetch_array().

CUBRID fetch flags
Constant | Description
--- | ---
`CUBRID_NUM` | Get query result as a numeric array (0-default).
`CUBRID_ASSOC` | Get query result as an associative array.
`CUBRID_BOTH` | Get query result as both numeric and associative arrays (default value).
`CUBRID_OBJECT` | Get query result an object.
`CUBRID_LOB` | The constant CUBRID_LOB can be used when you want to operate the lob object. It can be passed to cubrid_fetch(), cubrid_fetch_row(), cubrid_fetch_array(), cubrid_fetch_assoc() and cubrid_fetch_object().

The following constants can be used when positioning the cursor in query results. They can be passed to or returned by cubrid_move_cursor().

CUBRID cursor position flags
Constant | Description
--- | ---
`CUBRID_CURSOR_FIRST` | Move current cursor to the first position in the result.
`CUBRID_CURSOR_CURRENT` | Move current cursor as a default value if the origin is not specified.
`CUBRID_CURSOR_LAST` | Move current cursor to the last position in the result.
`CUBRID_CURSOR_SUCCESS` | Returned value of cubrid_move_cursor() function in case of success. This flag has been removed from 8.4.1.
`CUBRID_NO_MORE_DATA` | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.
`CUBRID_CURSOR_ERROR` | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.

The following constants can be used when setting the auto-commit mode for the database connection. They can be passed to cubrid_set_autocommit() or returned by cubrid_get_autocommit().

CUBRID auto-commit mode flags
Constant | Description
--- | ---
`CUBRID_AUTOCOMMIT_TRUE` | Enable the auto-commit mode.
`CUBRID_AUTOCOMMIT_FALSE` | Disable the auto-commit mode.

The following constants can be used when setting the database parameter. They can be passed to cubrid_set_db_parameter().

CUBRID parameter flags
Constant | Description
--- | ---
`CUBRID_PARAM_ISOLATION_LEVEL` | Transaction isolation level for the database connection.
`CUBRID_PARAM_LOCK_TIMEOUT` | Transaction timeout in seconds.

The following constants can be used when setting the transaction isolation level. They can be passed to cubrid_set_db_parameter() or returned by cubrid_get_db_parameter().

CUBRID isolation level flags
Constant | Description
--- | ---
`TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE` | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
`TRAN_COMMIT_CLASS_COMMIT_INSTANCE` | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
`TRAN_REP_CLASS_UNCOMMIT_INSTANCE` | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
`TRAN_REP_CLASS_COMMIT_INSTANCE` | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
`TRAN_REP_CLASS_REP_INSTANCE` | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
`TRAN_SERIALIZABLE` | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to cubrid_schema().

CUBRID schema flags
Constant | Description
--- | ---
`CUBRID_SCH_CLASS` | Get name and type of table in CUBRID.
`CUBRID_SCH_VCLASS` | Get name and type of view in CUBRID.
`CUBRID_SCH_QUERY_SPEC` | Get the query definition of view.
`CUBRID_SCH_ATTRIBUTE` | Get the attributes of table column.
`CUBRID_SCH_CLASS_ATTRIBUTE` | Get the attributes of table.
`CUBRID_SCH_METHOD` | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
`CUBRID_SCH_CLASS_METHOD` | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
`CUBRID_SCH_METHOD_FILE` | Get the information of the file where the method of the table is defined.
`CUBRID_SCH_SUPERCLASS` | Get the name and type of table which table inherites attributes from.
`CUBRID_SCH_SUBCLASS` | Get the name and type of table which inherites attributes from this table.
`CUBRID_SCH_CONSTRAINT` | Get the table constraints.
`CUBRID_SCH_TRIGGER` | Get the table triggers.
`CUBRID_SCH_CLASS_PRIVILEGE` | Get the privilege information of table.
`CUBRID_SCH_ATTR_PRIVILEGE` | Get the privilege information of column.
`CUBRID_SCH_DIRECT_SUPER_CLASS` | Get the direct super table of table.
`CUBRID_SCH_PRIMARY_KEY` | Get the table primary key.
`CUBRID_SCH_IMPORTED_KEYS` | Get imported keys of table.
`CUBRID_SCH_EXPORTED_KEYS` | Get exported keys of table.
`CUBRID_SCH_CROSS_REFERENCE` | Get reference relationship of two tables.

The following constants can be used when reporting errors. They can be returned from cubrid_error_code_facility().

CUBRID error facility code
Constant | Description
--- | ---
`CUBRID_FACILITY_DBMS` | The error occurred in CUBRID dbms.
`CUBRID_FACILITY_CAS` | The error occurred in CUBRID broker cas.
`CUBRID_FACILITY_CCI` | The error occurred in CUBRID cci.
`CUBRID_FACILITY_CLIENT` | The error occurred in CUBRID PHP client.

# Examples

The following is a simple example that establishes a connection between PHP and CUBRID. This section will cover the most basic and notable features. The following code required to connect to CUBRID database, which means CUBRID Server and CUBRID Broker have to be running.

The example below uses the demodb database as an examples. By default it is created during the installation. Make sure it has been created.

Example #1 Example of Data Retrieval

`<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr">
</head>
<body>
<center>
<table border=2>
<?php
/**
* Set server information for CUBRID connection. host_ip is the IP
* address where the CUBRID Broker is installed (localhost in this
* example), and host_port is the port number of the CUBRID Broker.
* The port number is the default given during the installation.
* For details, see "Administrator's Guide."
*/
$host_ip = "localhost";
$host_port = 33000;
$db_name = "demodb";
/**
* Connect to CUBRID Server. Do not make the actual connection, but
* only retain the connection information. The reason for not making
* the actual connection is to handle transaction more efficiently
* in the 3-tier architecture.
*/
$cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);
if (!$cubrid_con) {
echo "Database Connection Error";
exit;
}
?>
<?php
$sql = "select sports, count(players) as players from event group by sports";
/**
* Request the CUBRID Server for the results of the SQL statement.
* Now make the actual connection to the CUBRID Server.
*/
$result = cubrid_execute($cubrid_con, $sql);
if ($result) {
/**
* Get the column names from the result set created by the SQL query.
*/
$columns = cubrid_column_names($result);
/**
* Get the number of columns in the result set created by the SQL query.
*/
$num_fields = cubrid_num_cols($result);
/**
* List the column names of the result set on the screen.
*/
echo "<tr>";
while (list($key, $colname) = each($columns)) {
echo "<td align=center>$colname</td>";
}
echo "</tr>";
/**
* Get the results from the result set.
*/
while ($row = cubrid_fetch($result)) {
echo "<tr>";
for ($i = 0; $i < $num_fields; $i++) {
echo "<td align=center>";
echo $row[$i];
echo "</td>";
}
echo "</tr>";
}
}
/**
* The PHP module in the CUBRID runs in a 3-tier architecture. Even when
* calling SELECT for transaction processing, it is processed as a part
* of the transaction. Therefore, the transaction needs to be rolled back
* by calling commit or rollback even though SELECT was called for smooth
* performance.
*/
cubrid_commit($cubrid_con);
cubrid_disconnect($cubrid_con);
?>
</body>
</html>`

Example #2 Example of Data Insertion

`<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc- kr">
</head>
<body>
<center>
<table border=2>
<?php
/**
* host_ip is the IP address where the CUBRID Broker is installed
* host_port is the port number of the CUBRID Broker
* db_name is the name of CUBRID Database
*/
$host_ip = "localhost";
$host_port = 33000;
$db_name = "demodb";
$cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);
if (!$cubrid_con) {
echo "Database Connection Error";
exit;
}
?>
<?php
$sql = "insert into olympic (host_year,host_nation,host_city,"
. "opening_date,closing_date) values (2008, 'China', 'Beijing',"
. "to_date('08-08-2008','mm-dd- yyyy'),to_date('08-24-2008','mm-dd-yyyy')) ;";
$result = cubrid_execute($cubrid_con, $sql);
if ($result) {
/**
* Handled successfully, so commit.
*/
cubrid_commit($cubrid_con);
echo "Inserted successfully ";
} else {
/**
* Error occurred, so the error message is output and rollback is called.
*/
echo cubrid_error_msg();
cubrid_rollback($cubrid_con);
}
cubrid_disconnect($cubrid_con);
?>
</body>
</html>`

# CUBRID Functions

# cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

### Description

cubrid_bind(
resource `$req_identifier`,
int `$bind_index`,
mixed `$bind_value`,
string `$bind_value_type` = ?
): bool

The cubrid_bind() function is used to bind values to a corresponding named or question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If `bind_value_type` is not given, string will be the default.

> Note: If the type of data to be bound is BLOB/CLOB, CUBRID will try to map the data as a PHP stream. If the actually bind value type is not stream, CUBRID will convert it to string, and use it as the full path and file name of a file on the client filesystem. If the type of data to be bound explicitly is ENUM, the `bind_value` argument should be the enum element which is in string format. In CUBRID shard envrioment, the `bind_value_type` must be included in the cubrid_bind() function.

The following table shows the types of substitute values.

CUBRID Bind Date Types
Support | Bind Type | Corresponding SQL Type
--- | --- | ---
Supported | STRING | CHAR, VARCHAR
| NCHAR | NCHAR, NVARCHAR
| BIT | BIT, VARBIT
| NUMERIC or NUMBER | SHORT, INT, NUMERIC
| FLOAT | FLOAT
| DOUBLE | DOUBLE
| TIME | TIME
| DATE | DATE
| TIMESTAMP | TIMESTAMP
| OBJECT | OBJECT
| ENUM | ENUM
| BLOB | BLOB
| CLOB | CLOB
| NULL | NULL
Not supported | SET | SET
| MULTISET | MULTISET
| SEQUENCE | SEQUENCE

### Parameters

`req_identifier`
  Request identifier as a result of cubrid_prepare().
`bind_index`
  Location of binding parameters. It starts with 1.
`bind_value`
  Actual value for binding.
`bind_value_type`
  A type of the value to bind. (It is omitted by default. Thus, the system internally uses string by default. However, you need to specify the exact type of the value as an argument when they are NCHAR, BIT, or BLOB/CLOB).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.1 | Added BLOB/CLOB data types support.

### Examples

Example #1 cubrid_bind() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT code FROM event WHERE sports='Basketball' and gender='M'");
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];
cubrid_close_request($result);
$game_req = cubrid_prepare($conn, "SELECT athlete_code FROM game WHERE host_year=1992 and event_code=? and nation_code='USA'");
cubrid_bind($game_req, 1, $event_code, "number");
cubrid_execute($game_req);
printf("--- Dream Team (1992 United States men's Olympic basketball team) ---\n");
while ($athlete_code = cubrid_fetch_array($game_req, CUBRID_NUM)) {
$athlete_req = cubrid_prepare($conn, "SELECT name FROM athlete WHERE code=? AND nation_code='USA' AND event='Basketball' AND gender='M'");
cubrid_bind($athlete_req, 1, $athlete_code[0], "number");
cubrid_execute($athlete_req);
$row = cubrid_fetch_assoc($athlete_req);
printf("%s\n", $row["name"]);
}
cubrid_close_request($game_req);
cubrid_close_request($athlete_req);
cubrid_disconnect($conn);
?>`

The above example will output:

    --- Dream Team (1992 United States men's Olympic basketball team) ---
    Stockton John
    Robinson David
    Pippen Scottie
    Mullin C.
    Malone Karl
    Laettner C.
    Jordan Michael
    Johnson Earvin
    Ewing Patrick
    Drexler Clyde
    Bird Larry
    Barkley Charles

Example #2 cubrid_bind() BLOB/CLOB example

`<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (doc_content CLOB)");
$sql = "INSERT INTO php_cubrid_lob_test(doc_content) VALUES(?)";
$req = cubrid_prepare($con, $sql);
$fp = fopen("book.txt", "rb");
cubrid_bind($req, 1, $fp, "clob");
cubrid_execute($req);
}
?>`

Example #3 cubrid_bind() BLOB/CLOB example

`<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (image BLOB)");
$sql = "INSERT INTO php_cubrid_lob_test(image) VALUES(?)";
$req = cubrid_prepare($con, $sql);
cubrid_bind($req, 1, "cubrid_logo.png", "blob");
cubrid_execute($req);
}
?>`

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_prepare() - Prepare a SQL statement for execution

# cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

### Description

cubrid_close_prepare(resource `$req_identifier`): bool

The cubrid_close_prepare() function closes the request handle given by the `req_identifier` argument, and releases the memory region related to the handle. It is an alias of cubrid_close_request().

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Return `true` on success.

### Examples

Example #1 cubrid_close_prepare() example

`<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "select * from members",
CUBRID_INCLUDE_OID | CUBRID_ASYNC);
if ($req) {
while ( list ($id, $name) = cubrid_fetch ($req) ){
echo $id;
echo $name;
}
cubrid_close_prepare($req); // or you can use cubrid_close_request($req)
}
cubrid_disconnect($con);
}
?>`

### See Also

- cubrid_close_request() - Close the request handle

# cubrid_close_request

(PECL CUBRID >= 8.3.0)

cubrid_close_request — Close the request handle

### Description

cubrid_close_request(resource `$req_identifier`): bool

The cubrid_close_request() function closes the request handle given by the `req_identifier` argument, and releases the memory region related to the handle. It is an alias of cubrid_close_prepare().

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Return `true` on success.

### Examples

Example #1 cubrid_close_request() example

`<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "select * from members",
CUBRID_INCLUDE_OID | CUBRID_ASYNC);
if ($req) {
while ( list ($id, $name) = cubrid_fetch ($req) ){
echo $id;
echo $name;
}
cubrid_close_request($req); // or you can use cubrid_close_prepare($req)
}
cubrid_disconnect($con);
}
?>`

### See Also

- cubrid_close_prepare() - Close the request handle

# cubrid_col_get

(PECL CUBRID >= 8.3.0)

cubrid_col_get — Get contents of collection type column using OID

### Description

cubrid_col_get(resource `$conn_identifier`, string `$oid`, string `$attr_name`): array

The cubrid_col_get() function is used to get contents of the elements of the collection type (set, multiset, sequence) attribute you requested as an array.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to read.
`attr_name`
  Attribute name that you want to read from the instance.

### Return Values

Array (0-based numerical array) containing the elements you requested, when process is successful;

`false` (to distinguish the error from the situation of attribute having empty collection or NULL, in case of error, a warning message is shown; in such case you can check the error by using cubrid_error_code()), when process is unsuccessful.

### Examples

Example #1 cubrid_col_get() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    int(3)

# cubrid_col_size

(PECL CUBRID >= 8.3.0)

cubrid_col_size — Get the number of elements in collection type column using OID

### Description

cubrid_col_size(resource `$conn_identifier`, string `$oid`, string `$attr_name`): int

The cubrid_col_size() function is used to get the number of elements in a collection type (set, multiset, sequence) attribute.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID the instance that you want to work with.
`attr_name`
  Name of the attribute that you want to work with.

### Return Values

Number of elements, when process is successful, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

### Examples

Example #1 cubrid_col_size() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    int(3)

# cubrid_column_names

(PECL CUBRID >= 8.3.0)

cubrid_column_names — Get the column names in result

### Description

cubrid_column_names(resource `$req_identifier`): array

The cubrid_column_names() function is used to get the column names of the query result by using `req_identifier`.

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Array of string values containing the column names, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_column_names() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);
printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Column Names                   Column Types                   Column Maxlen
    host_year                      integer                        11
    event_code                     integer                        11
    athlete_code                   integer                        11
    stadium_code                   integer                        11
    nation_code                    char                           3
    medal                          char                           1
    game_date                      date                           10

### See Also

- cubrid_prepare() - Prepare a SQL statement for execution
- cubrid_execute() - Execute a prepared SQL statement
- cubrid_column_types() - Get column types in result

# cubrid_column_types

(PECL CUBRID >= 8.3.0)

cubrid_column_types — Get column types in result

### Description

cubrid_column_types(resource `$req_identifier`): array

The cubrid_column_types() function gets column types of query results by using `req_identifier`.

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Array of string values containing the column types, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_column_types() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);
printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Column Names                   Column Types                   Column Maxlen
    host_year                      integer                        11
    event_code                     integer                        11
    athlete_code                   integer                        11
    stadium_code                   integer                        11
    nation_code                    char                           3
    medal                          char                           1
    game_date                      date                           10

### See Also

- cubrid_column_names() - Get the column names in result
- cubrid_prepare() - Prepare a SQL statement for execution
- cubrid_execute() - Execute a prepared SQL statement

# cubrid_commit

(PECL CUBRID >= 8.3.0)

cubrid_commit — Commit a transaction

### Description

cubrid_commit(resource `$conn_identifier`): bool

The cubrid_commit() function is used to execute commit on the transaction pointed by `conn_identifier`, currently in progress. Connection to the server is closed after the cubrid_commit() function is called; However, the connection handle is still valid.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. You can set it by using cubrid_set_autocommit(). You can get its status by using cubrid_get_autocommit(). Before you start a transaction, remember to disable the auto-commit mode.

### Parameters

`conn_identifier`
  Connection identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_commit() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE publishers");
$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;
cubrid_set_autocommit($conn,false);
if (!cubrid_execute($conn, $sql)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());
cubrid_disconnect($conn);
exit;
}
$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");
$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");
for ($i = 0, $size = count($id_list); $i < $size; $i++) {
cubrid_bind($req, 1, $id_list[$i]);
cubrid_bind($req, 2, $name_list[$i]);
cubrid_bind($req, 3, $city_list[$i]);
cubrid_bind($req, 4, $state_list[$i]);
cubrid_bind($req, 5, $country_list[$i]);
if (!($ret = cubrid_execute($req))) {
break;
}
}
if (!$ret) {
cubrid_rollback($conn);
} else {
cubrid_commit($conn);
$req = cubrid_execute($conn, "SELECT * FROM publishers");
while ($result = cubrid_fetch_assoc($req)) {
printf("%-3s %-20s %-15s %-3s %-15s\n",
$result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
}
}
cubrid_disconnect($conn);
?>`

The above example will output:

    P01 Abatis Publishers    New York        NY  USA
    P02 Core Dump Books      San Francisco   CA  USA
    P03 Schadenfreude Press  Hamburg             Germany
    P04 Tenterhooks Press    Berkeley        CA  USA

### See Also

- cubrid_rollback() - Roll back a transaction
- cubrid_get_autocommit() - Get auto-commit mode of the connection
- cubrid_set_autocommit() - Set autocommit mode of the connection

# cubrid_connect

(PECL CUBRID >= 8.3.1)

cubrid_connect — Open a connection to a CUBRID Server

### Description

cubrid_connect(
string `$host`,
int `$port`,
string `$dbname`,
string `$userid` = ?,
string `$passwd` = ?,
bool `$new_link` = `false`
): resource

The cubrid_connect() function is used to establish the environment for connecting to your server by using your server address, port number, database name, user name, and password. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

### Parameters

`host`
  Host name or IP address of CUBRID CAS server.
`port`
  Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).
`dbname`
  Name of database.
`userid`
  User name for the database. If not given, the default value is "public".
`passwd`
  User password. If not given, the default value is "".
`new_link`
  If a second call is made to cubrid_connect() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The `new_link` parameter modifies this behavior and makes cubrid_connect() always open a new connection, even if cubrid_connect() was called before with the same parameters.

### Return Values

Connection identifier, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_connect() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

### See Also

- cubrid_pconnect() - Open a persistent connection to a CUBRID server
- cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
- cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
- cubrid_disconnect() - Close a database connection
- cubrid_close() - Close CUBRID connection

# cubrid_connect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_connect_with_url — Establish the environment for connecting to CUBRID server

### Description

cubrid_connect_with_url(
string `$conn_url`,
string `$userid` = ?,
string `$passwd` = ?,
bool `$new_link` = `false`
): resource

The cubrid_connect_with_url() function is used to establish the environment for connecting to your server by using connection information passed with an url string argument. If the HA feature is enabled in CUBRID, you must specify the connection information of the standby server, which is used for failover when failure occurs, in the url string argument of this function. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

- host : A host name or IP address of the master database
- db_name : A name of the database
- db_user : A name of the database user
- db_password : A database user password
- alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
- rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
- login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
- query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
- disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

> Note: `?` and `:` that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "`?:`". $url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100"; Passwords that contain `?` or `:` may be passed as a separate parameter. $url = "CUBRID:localhost:33000:tbd:::?login_timeout=100"; $conn = cubrid_connect_with_url($url, "dba", "12?"); If user or password is empty,you can't delete "`:`",the following is an example. $url = "CUBRID:localhost:33000:demodb:::";

### Parameters

`conn_url`
  A character string that contains server connection information.
`userid`
  User name for the database.
`passwd`
  User password.
`new_link`
  If a second call is made to cubrid_connect_with_url() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The `new_link` parameter modifies this behavior and makes cubrid_connect_with_url() always open a new connection, even if cubrid_connect_with_url() was called before with the same parameters.

### Return Values

Connection identifier, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_connect_with_url() url without properties example

`<?php
$conn_url = "CUBRID:localhost:33000:demodb:dba::";
$con = cubrid_connect_with_url($conn_url);
if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>`

Example #2 cubrid_connect_with_url() url with properties example

`<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?login_timeout=100";
$con = cubrid_connect_with_url ($conn_url);
if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>`

### See Also

- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_pconnect() - Open a persistent connection to a CUBRID server
- cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
- cubrid_disconnect() - Close a database connection
- cubrid_close() - Close CUBRID connection

# cubrid_current_oid

(PECL CUBRID >= 8.3.0)

cubrid_current_oid — Get OID of the current cursor location

### Description

cubrid_current_oid(resource `$req_identifier`): string

The cubrid_current_oid() function is used to get the oid of the current cursor location from the query result. To use cubrid_current_oid(), the query executed must be a updatable query, and the `CUBRID_INCLUDE_OID` option must be included during the query execution.

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Oid of current cursor location, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_current_oid() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$res = cubrid_get($conn, $oid);
print_r($res);
cubrid_disconnect($conn);
?>`

The above example will output:

    Array
    (
        [s_name] => X
        [f_name] => Mixed
    )

### See Also

- cubrid_execute() - Execute a prepared SQL statement

# cubrid_disconnect

(PECL CUBRID >= 8.3.0)

cubrid_disconnect — Close a database connection

### Description

cubrid_disconnect(resource `$conn_identifier` = ?): bool

The cubrid_disconnect() function closes the connection handle and disconnects from server. If any request handle is not closed at this point, it will be closed. It is similar to the CUBRID MySQL compatible function cubrid_close().

### Parameters

`conn_identifier`
  Connection identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_disconnect() example

`<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
echo "connected successfully";
$req = cubrid_execute( $con, "create table person(id int,name char(10))");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
$req = cubrid_execute( $con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>`

### See Also

- cubrid_close() - Close CUBRID connection
- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

# cubrid_drop

(PECL CUBRID >= 8.3.0)

cubrid_drop — Delete an instance using OID

### Description

cubrid_drop(resource `$conn_identifier`, string `$oid`): bool

The cubrid_drop() function is used to delete an instance from database by using the `oid` of the instance.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  Oid of the instance that you want to delete.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_drop() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
printf("--- Before Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);
if (cubrid_drop($conn, $oid)) {
cubrid_commit($conn);
} else {
cubrid_rollback($conn);
}
cubrid_close_request($req);
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
printf("\n--- After Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    --- Before Drop: ---
    array(4) {
      ["a"]=>
      string(1) "1"
      ["b"]=>
      array(3) {
        [0]=>
        string(1) "1"
        [1]=>
        string(1) "2"
        [2]=>
        string(1) "3"
      }
      ["c"]=>
      array(4) {
        [0]=>
        string(2) "11"
        [1]=>
        string(2) "22"
        [2]=>
        string(2) "33"
        [3]=>
        string(3) "333"
      }
      ["d"]=>
      string(10) "a         "
    }

    --- After Drop: ---
    array(4) {
      ["a"]=>
      string(1) "2"
      ["b"]=>
      array(3) {
        [0]=>
        string(1) "4"
        [1]=>
        string(1) "5"
        [2]=>
        string(1) "7"
      }
      ["c"]=>
      array(4) {
        [0]=>
        string(2) "44"
        [1]=>
        string(2) "55"
        [2]=>
        string(2) "66"
        [3]=>
        string(3) "666"
      }
      ["d"]=>
      string(10) "b         "
    }

### See Also

- cubrid_is_instance() - Check whether the instance pointed by OID exists

# cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

### Description

cubrid_error_code(): int

The cubrid_error_code() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

### Parameters

This function has no parameters.

### Return Values

Error code of the error that occurred, or `0` (zero) if no error occurred.

### Examples

Example #1 cubrid_error_code() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_prepare($conn , "SELECT * FROM code WHERE s_name=?");
$req = @cubrid_execute($req);
if (!$req) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());
cubrid_disconnect($conn);
exit;
}
?>`

The above example will output:

    Error facility: 4
    Error code: -30015
    Error msg: Some parameter not binded

### See Also

- cubrid_error_code_facility() - Get the facility code of error
- cubrid_error_msg() - Get last error message for the most recent function call

# cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

### Description

cubrid_error_code_facility(): int

The cubrid_error_code_facility() function is used to get the facility code (level in which the error occurred) from the error code of the error that occurred during the API execution. Usually, you can get the error code when API returns false as its return value.

### Parameters

This function has no parameters.

### Return Values

Facility code of the error code that occurred: `CUBRID_FACILITY_DBMS`, `CUBRID_FACILITY_CAS`, `CUBRID_FACILITY_CCI`, `CUBRID_FACILITY_CLIENT`.

### Examples

Example #1 cubrid_error_code_facility() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = @cubrid_execute($conn, "SELECT * FROM unknown");
if (!$req) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());
cubrid_disconnect($conn);
exit;
}
?>`

The above example will output:

    Error facility: 1
    Error code: -493
    Error msg: Syntax: In line 1, column 15 before END OF STATEMENT
    Syntax error: unexpected 'unknown'

### See Also

- cubrid_error_code() - Get error code for the most recent function call
- cubrid_error_msg() - Get last error message for the most recent function call

# cubrid_error_msg

(PECL CUBRID >= 8.3.0)

cubrid_error_msg — Get last error message for the most recent function call

### Description

cubrid_error_msg(): string

The cubrid_error_msg() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

### Parameters

This function has no parameters.

### Return Values

Error message that occurred.

### Examples

Example #1 cubrid_error_msg() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
if (!@cubrid_schema($conn, 100000)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());
cubrid_disconnect($conn);
exit;
}
?>`

The above example will output:

    Error facility: 2
    Error code: -10015
    Error msg: Invalid T_CCI_SCH_TYPE value

### See Also

- cubrid_error_code() - Get error code for the most recent function call
- cubrid_error_code_facility() - Get the facility code of error

# cubrid_execute

(PECL CUBRID >= 8.3.0)

cubrid_execute — Execute a prepared SQL statement

### Description

cubrid_execute(resource `$conn_identifier`, string `$sql`, int `$option` = 0): resource
cubrid_execute(resource `$request_identifier`, int `$option` = 0): bool

The cubrid_execute() function is used to execute the given SQL statement. It executes the query by using `conn_identifier` and SQL, and then returns the request identifier created. It is used for simple execution of query, where the parameter binding is not needed. In addition, the cubrid_execute() function is used to execute the prepared statement by means of cubrid_prepare() and cubrid_bind(). At this time, you need to specify arguments of `request_identifier` and `option`.

The `option` is used to determine whether to get OID after query execution and whether to execute the query in synchronous or asynchronous mode. `CUBRID_INCLUDE_OID` and `CUBRID_ASYNC` (or `CUBRID_EXEC_QUERY_ALL` if you want to execute multiple SQL statements) can be specified by using a bitwise OR operator. If not specified, neither of them isselected. If the flag `CUBRID_EXEC_QUERY_ALL` is set, a synchronous mode (sync_mode) is used to retrieve query results, and in such cases the following rules are applied:

- The return value is the result of the first query.
- If an error occurs in any query, the execution is processed as a failure.
- In a query composed of q1 q2 q3, if an error occurs in q2 after q1 succeeds the execution, the result of q1 remains valid. That is, the previous successful query executions are not rolled back when an error occurs.
- If a query is executed successfully, the result of the second query can be obtained using cubrid_next_result().

If the first argument is `request_identifier` to execute the cubrid_prepare() function, you can specify an option, `CUBRID_ASYNC` only.

### Parameters

`conn_identifier`
  Connection identifier.
`sql`
  SQL to be executed.
`option`
  Query execution option `CUBRID_INCLUDE_OID`, `CUBRID_ASYNC`, `CUBRID_EXEC_QUERY_ALL`.
`request_identifier`
  cubrid_prepare() identifier.

### Return Values

Request identifier, when process is successful and first param is conn_identifier; `true`, when process is successful and first argument is request_identifier, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | Add new option `CUBRID_EXEC_QUERY_ALL`.

### Examples

Example #1 cubrid_execute() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT code FROM event WHERE name='100m Butterfly' and gender='M'", CUBRID_ASYNC);
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];
cubrid_close_request($result);
$history_req = cubrid_prepare($conn, "SELECT * FROM history WHERE event_code=?");
cubrid_bind($history_req, 1, $event_code, "number");
cubrid_execute($history_req);
printf("%-20s %-9s %-10s %-5s\n", "athlete", "host_year", "score", "unit");
while ($row = cubrid_fetch_array($history_req, CUBRID_ASSOC)) {
printf("%-20s %-9s %-10s %-5s\n",
$row["athlete"], $row["host_year"], $row["score"], $row["unit"]);
}
cubrid_close_request($history_req);
cubrid_disconnect($conn);
?>`

The above example will output:

    athlete              host_year score      unit
    Phelps Michael       2004      51.25      time

### See Also

- cubrid_prepare() - Prepare a SQL statement for execution
- cubrid_bind() - Bind variables to a prepared statement as parameters
- cubrid_next_result() - Get result of next query when executing multiple SQL statements
- cubrid_close_request() - Close the request handle
- cubrid_commit() - Commit a transaction
- cubrid_rollback() - Roll back a transaction

# cubrid_fetch

(PECL CUBRID >= 8.3.0)

cubrid_fetch — Fetch the next row from a result set

### Description

cubrid_fetch(resource `$result`, int `$type` = CUBRID_BOTH): mixed

The cubrid_fetch() function is used to get a single row from the query result. The cursor automatically moves to the next row after getting the result.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`type`
  Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH, CUBRID_OBJECT. If you want to operate the lob object, you can use CUBRID_LOB.

### Return Values

Result array or object, when process is successful.

`false`, when there are no more rows; NULL, when process is unsuccessful.

The result can be received either as an array or as an object, and you can decide which data type to use by setting the `type` argument. The `type` variable can be set to one of the following values:

- CUBRID_NUM : Numerical array (0-based)
- CUBRID_ASSOC : Associative array
- CUBRID_BOTH : Numerical & Associative array (default)
- CUBRID_OBJECT : object that has the attribute name as the column name of query result

When `type` argument is omitted, the result will be received using CUBRID_BOTH option as default. When you want to receive query result in object data type, the column name of the result must obey the naming rules for identifiers in PHP. For example, column name such as "count(*)" cannot be received in object type.

### Examples

Example #1 cubrid_fetch() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM stadium WHERE nation_code='GRE' AND seats > 10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}
// if you want to operate lob object, you can use cubrid_fetch($req, CUBRID_LOB)
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    name                                     area       seats  address
    Panathinaiko Stadium                     86300.00   50000  Athens, Greece
    Olympic Stadium                          54700.00   13000  Athens, Greece
    Olympic Indoor Hall                      34100.00   18800  Athens, Greece
    Olympic Hall                             52400.00   21000  Athens, Greece
    Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
    Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
    Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
    Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
    Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- cubrid_fetch_row() - Return a numerical array with the values of the current row
- cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
- cubrid_fetch_object() - Fetch the next row and return it as an object

# cubrid_free_result

(PECL CUBRID >= 8.3.0)

cubrid_free_result — Free the memory occupied by the result data

### Description

cubrid_free_result(resource `$req_identifier`): bool

This function frees the memory occupied by the result data. It returns `true` on success or `false` on failure. Note that it can only frees the client fetch buffer now, and if you want free all memory, use function cubrid_close_request().

### Parameters

`req_identifier`
  This is the request identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_free_result() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM history WHERE host_year=2004 ORDER BY event_code");
$row = cubrid_fetch_assoc($req);
var_dump($row);
cubrid_free_result($req);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(5) {
      ["event_code"]=>
      string(5) "20005"
      ["athlete"]=>
      string(12) "Hayes Joanna"
      ["host_year"]=>
      string(4) "2004"
      ["score"]=>
      string(5) "12.37"
      ["unit"]=>
      string(4) "time"
    }

# cubrid_get

(PECL CUBRID >= 8.3.0)

cubrid_get — Get a column using OID

### Description

cubrid_get(resource `$conn_identifier`, string `$oid`, mixed `$attr` = ?): mixed

The cubrid_get() function is used to get the attribute of the instance of the given `oid`. You can get single attribute by using string data type for the `attr` argument, or many attributes by using array data type for the `attr` argument.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to read.
`attr`
  Name of the attribute that you want to read.

### Return Values

Content of the requested attribute, when process is successful; When `attr` is set with string data type, the result is returned as a string; when `attr` is set with array data type (0-based numerical array), then the result is returned in associative array. When `attr` is omitted, then all attributes are received in array form.

`false` when process is unsuccessful or result is NULL (If error occurs to distinguish empty string from NULL, then it prints the warning message. You can check the error by using cubrid_error_code())

### Examples

Example #1 cubrid_get() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);
$attr = cubrid_get($conn, $oid);
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    string(9) "{1, 2, 3}"
    array(4) {
      ["a"]=>
      string(1) "1"
      ["b"]=>
      array(3) {
        [0]=>
        string(1) "1"
        [1]=>
        string(1) "2"
        [2]=>
        string(1) "3"
      }
      ["c"]=>
      array(4) {
        [0]=>
        string(2) "11"
        [1]=>
        string(2) "22"
        [2]=>
        string(2) "33"
        [3]=>
        string(3) "333"
      }
      ["d"]=>
      string(10) "a         "
    }

### See Also

- cubrid_put() - Update a column using OID

# cubrid_get_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_get_autocommit — Get auto-commit mode of the connection

### Description

cubrid_get_autocommit(resource `$conn_identifier`): bool

The cubrid_get_autocommit() function is used to get the status of CUBRID database connection auto-commit mode.

For CUBRID 8.4.0, auto-commit mode is disabled by default for transaction management.

For CUBRID 8.4.1, auto-commit mode is enabled by default for transaction management.

### Parameters

`conn_identifier`
  Connection identifier.

### Return Values

`true`, when auto-commit is on.

`false`, when auto-commit is off.

`null` on error.

### See Also

- cubrid_set_autocommit() - Set autocommit mode of the connection
- cubrid_commit() - Commit a transaction

# cubrid_get_charset

(PECL CUBRID >= 8.3.0)

cubrid_get_charset — Return the current CUBRID connection charset

### Description

cubrid_get_charset(resource `$conn_identifier`): string

This function returns the current CUBRID connection charset and is similar to the CUBRID MySQL compatible function cubrid_client_encoding().

### Parameters

`conn_identifier`
  The CUBRID connection.

### Return Values

A string that represents the CUBRID connection charset on success, or `false` on failure.

### Examples

Example #1 cubrid_get_charset() example

`<?php
$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
die('Could not connect.');
}
printf("CUBRID current charset: %s\n", cubrid_get_charset($con));
?>`

The above example will output:

    CUBRID current charset: iso8859-1

### See Also

- cubrid_client_encoding() - Return the current CUBRID connection charset

# cubrid_get_class_name

(PECL CUBRID >= 8.3.0)

cubrid_get_class_name — Get the class name using OID

### Description

cubrid_get_class_name(resource `$conn_identifier`, string `$oid`): string

The cubrid_get_class_name() function is used to get the class name from `oid`. It doesn't work when selecting data from the system tables, for example db_class.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to check the existence.

### Return Values

Class name when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_get_class_name() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$class_name = cubrid_get_class_name($conn, $oid);
print_r($class_name);
cubrid_disconnect($conn);
?>`

The above example will output:

    code

### See Also

- cubrid_is_instance() - Check whether the instance pointed by OID exists
- cubrid_drop() - Delete an instance using OID

# cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

### Description

cubrid_get_client_info(): string

This function returns a string that represents the client library version.

### Parameters

### Return Values

A string that represents the client library version on success, or `false` on failure.

### Examples

Example #1 cubrid_get_client_info() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_connect("localhost", 33088, "demodb");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

# cubrid_get_db_parameter

(PECL CUBRID >= 8.3.0)

cubrid_get_db_parameter — Returns the CUBRID database parameters

### Description

cubrid_get_db_parameter(resource `$conn_identifier`): array

This function returns the CUBRID database parameters, or `false` on failure. It returns an associative array with the values for the following parameters:

- `PARAM_ISOLATION_LEVEL`
- `PARAM_LOCK_TIMEOUT`
- `PARAM_MAX_STRING_LENGTH`
- `PARAM_AUTO_COMMIT`

Database parameters
Parameter | Description
--- | ---
PARAM_ISOLATION_LEVEL | The transaction isolation level.
LOCK_TIMEOUT | CUBRID provides the lock timeout feature, which sets the waiting time (in seconds) for the lock until the transaction lock setting is allowed. The default value of the lock_timeout_in_secs parameter is -1, which means the application client will wait indefinitely until the transaction lock is allowed.
PARAM_AUTO_COMMIT | In CUBRID PHP, auto-commit mode is disabled by default for transaction management. It can be set by using cubrid_set_autocommit().

The following table shows the isolation levels from 1 to 6. It consists of table schema (row) and isolation level:

Levels of Isolation Supported by CUBRID
Name | Description
--- | ---
SERIALIZABLE (6) | In this isolation level, problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.
REPEATABLE READ CLASS with REPEATABLE READ INSTANCES (5) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience phantom read for the record R that was inserted by another transaction T2 when it is repeatedly retrieving a specific record.
REPEATABLE READ CLASS with READ COMMITTED INSTANCES (or CURSOR STABILITY) (4) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R read (non-repeatable read) that was updated and committed by another transaction T2 when it is repeatedly retrieving the record R.
REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES (3) | Default isolation level. Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.
READ COMMITTED CLASS with READ COMMITTED INSTANCES (2) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is viewing table A repeatedly. Transaction T1 may experience R' read (non-repeatable read) for the record that was updated and committed by another transaction T2 while it is retrieving the record R repeatedly.
READ COMMITTED CLASS with READ UNCOMMITTED INSTANCES (1) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is repeatedly viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.

### Parameters

`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

### Return Values

An associative array with CUBRID database parameters; on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to PARAM_MAX_STRING_LENGTH in result.

### Examples

Example #1 cubrid_get_db_parameter() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_connect("localhost", 33088, "demodb");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

### See Also

- cubrid_set_db_parameter() - Sets the CUBRID database parameters
- cubrid_get_autocommit() - Get auto-commit mode of the connection

# cubrid_get_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_get_query_timeout — Get the query timeout value of the request

### Description

cubrid_get_query_timeout(resource `$req_identifier`): int

The cubrid_get_query_timeout() function is used to get the query timeout of the request.

### Parameters

`req_identifier`
  Request identifier.

### Return Values

Returns the query timeout value in milliseconds of the current request on success, or `false` on failure.

### Examples

Example #1 cubrid_get_query_timeout() example

`<?php
$host = "localhost";
$port = 33000;
$db = "demodb";
$conn =
cubrid_connect_with_url("CUBRID:$host:$port:$db:::?login_timeout=50000&query_timeout=5000&disconnect_on_query_timeout=yes");
$req = cubrid_prepare($conn, "SELECT * FROM code");
$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);
cubrid_set_query_timeout($req, 1000);
$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);
cubrid_close($conn);
?>`

The above example will output:

    int(5000)
    int(1000)

### See Also

- cubrid_set_query_timeout() - Set the timeout time of query execution

# cubrid_get_server_info

(PECL CUBRID >= 8.3.0)

cubrid_get_server_info — Return the CUBRID server version

### Description

cubrid_get_server_info(resource `$conn_identifier`): string

This function returns a string that represents the CUBRID server version.

### Parameters

`conn_identifier`
  The CUBRID connection.

### Return Values

A string that represents the CUBRID server version on success, or `false` on failure.

### Examples

Example #1 cubrid_get_server_info() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_connect("localhost", 33088, "demodb");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

# cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the last updated `AUTO_INCREMENT` column

### Description

cubrid_insert_id(resource `$conn_identifier` = ?): string

The cubrid_insert_id() function retrieves the ID generated for the AUTO_INCREMENT column which is updated by the previous INSERT query. It returns 0 if the previous query does not generate new rows, or FALSE on failure.

> Note: CUBRID supports AUTO_INCREMENT for more than one columns in a table. In most cases, there will be a single AUTO_INCREMENT column in a table. If there are multiple AUTO_INCREMENT columns, this function should not be used even if it will return a value.

### Parameters

`conn_identifier`
  The connection identifier previously obtained by a call to cubrid_connect().

### Return Values

A string representing the ID generated for an AUTO_INCREMENT column by the previous query, on success.

0, if the previous query does not generate new rows.

`false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | Change the return value from an array to string; Remove the first parameter class_name.

### Examples

Example #1 cubrid_insert_id() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d int AUTO_INCREMENT(1, 2), t varchar)");
for ($i = 0; $i < 10; $i++) {
cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}
$id = cubrid_insert_id();
var_dump($id);
cubrid_disconnect($conn);
?>`

The above example will output:

    string(2) "19"

# cubrid_is_instance

(PECL CUBRID >= 8.3.0)

cubrid_is_instance — Check whether the instance pointed by OID exists

### Description

cubrid_is_instance(resource `$conn_identifier`, string `$oid`): int

The cubrid_is_instance() function is used to check whether the instance pointed by the given `oid` exists or not.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to check the existence.

### Return Values

1, if such instance exists;

0, if such instance does not exist;

-1, in case of error

### Examples

Example #1 cubrid_is_instance() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$sql = <<<EOD
SELECT host_year, medal, game_date
FROM game
WHERE athlete_code IN
(SELECT code FROM athlete WHERE name='Thorpe Ian');
EOD;
$req = cubrid_execute($conn, $sql, CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$res = cubrid_is_instance ($conn, $oid);
if ($res == 1) {
echo "Instance pointed by $oid exists.\n";
} else if ($res == 0){
echo "Instance pointed by $oid doesn't exist.\n";
} else {
echo "error\n";
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Instance pointed by @0|0|0 doesn't exist.

### See Also

- cubrid_drop() - Delete an instance using OID
- cubrid_get_class_name() - Get the class name using OID

# cubrid_lob_close

(PECL CUBRID >= 8.3.1)

cubrid_lob_close — Close BLOB/CLOB data

### Description

cubrid_lob_close(array `$lob_identifier_array`): bool

cubrid_lob_close() is used to close all BLOB/CLOB returned from cubrid_lob_get().

### Parameters

`lob_identifier_array`
  LOB identifier array returned from cubrid_lob_get().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob_close() example

`<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");
cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");
$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob_get() - Get BLOB/CLOB data
- cubrid_lob_size() - Get BLOB/CLOB data size
- cubrid_lob_export() - Export BLOB/CLOB data to file
- cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

# cubrid_lob_export

(PECL CUBRID >= 8.3.1)

cubrid_lob_export — Export BLOB/CLOB data to file

### Description

cubrid_lob_export(resource `$conn_identifier`, resource `$lob_identifier`, string `$path_name`): bool

cubrid_lob_export() is used to get BLOB/CLOB data from CUBRID database, and saves its contents to a file. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

### Parameters

`conn_identifier`
  Connection identifier.
`lob_identifier`
  LOB identifier.
`path_name`
  Path name of the file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob_export() example

`<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");
cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");
$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob_get() - Get BLOB/CLOB data
- cubrid_lob_close() - Close BLOB/CLOB data
- cubrid_lob_size() - Get BLOB/CLOB data size
- cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

# cubrid_lob_get

(PECL CUBRID >= 8.3.1)

cubrid_lob_get — Get BLOB/CLOB data

### Description

cubrid_lob_get(resource `$conn_identifier`, string `$sql`): array

cubrid_lob_get() is used to get BLOB/CLOB meta info from CUBRID database, CUBRID gets BLOB/CLOB by executing the SQL statement, and returns all LOBs as a resource array. Be sure that the SQL retrieves only one column and its data type is BLOB or CLOB.

Remember to use cubrid_lob_close() to release the LOBs if you don't need it any more.

### Parameters

`conn_identifier`
  Connection identifier.
`sql`
  SQL statement to be executed.

### Return Values

Return an array of LOB resources, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_lob_get() example

`<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");
cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");
$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob_close() - Close BLOB/CLOB data
- cubrid_lob_size() - Get BLOB/CLOB data size
- cubrid_lob_export() - Export BLOB/CLOB data to file
- cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

# cubrid_lob_send

(PECL CUBRID >= 8.3.1)

cubrid_lob_send — Read BLOB/CLOB data and send straight to browser

### Description

cubrid_lob_send(resource `$conn_identifier`, resource `$lob_identifier`): bool

cubrid_lob_send() reads BLOB/CLOB data and passes it straight through to the browser. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

### Parameters

`conn_identifier`
  Connection identifier.
`lob_identifier`
  LOB identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob_send() example

`<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");
cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");
$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob_get() - Get BLOB/CLOB data
- cubrid_lob_close() - Close BLOB/CLOB data
- cubrid_lob_size() - Get BLOB/CLOB data size
- cubrid_lob_export() - Export BLOB/CLOB data to file

# cubrid_lob_size

(PECL CUBRID >= 8.3.1)

cubrid_lob_size — Get BLOB/CLOB data size

### Description

cubrid_lob_size(resource `$lob_identifier`): string

cubrid_lob_size() is used to get BLOB/CLOB data size.

### Parameters

`lob_identifier`
  LOB identifier.

### Return Values

A string representing LOB data size, when process is successful, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | Change return value type from int to string.

### Examples

Example #1 cubrid_lob_size() example

`<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
echo "Doc size:".cubrid_lob_size($lobs[0]);
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>`

### See Also

- cubrid_lob_get() - Get BLOB/CLOB data
- cubrid_lob_close() - Close BLOB/CLOB data
- cubrid_lob_export() - Export BLOB/CLOB data to file
- cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

# cubrid_lob2_bind

(PECL CUBRID >= 8.4.1)

cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters

### Description

cubrid_lob2_bind(
resource `$req_identifier`,
int `$bind_index`,
mixed `$bind_value`,
string `$bind_value_type` = ?
): bool

The cubrid_lob2_bind() function is used to bind BLOB/CLOB datas to a corresponding question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If `bind_value_type` is not given, string will be "BLOB" as the default. But if you use cubrid_lob2_new() before, `bind_value_type` will be consistent with `type` in cubrid_lob2_new() as the default.

### Parameters

`req_identifier`
  Request identifier as a result of cubrid_prepare().
`bind_index`
  Location of binding parameters. It starts with 1.
`bind_value`
  Actual value for binding.
`bind_value_type`
  It must be "BLOB" or "CLOB" and it won't be case-sensitive. If it not be given, the default value is "BLOB".

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_bind() example

`<?php
// Table: test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req,1, 3);
$lob = cubrid_lob2_new($conn, 'CLOB');
cubrid_lob2_bind($req, 2, $lob);
cubrid_execute($req);
cubrid_bind($req, 1, 4);
cubrid_lob2_bind($req, 2, 'CUBRID LOB2 TEST', 'CLOB');
cubrid_execute($req);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_new() - Create a lob object
- cubrid_lob2_close() - Close LOB object

# cubrid_lob2_close

(PECL CUBRID >= 8.4.1)

cubrid_lob2_close — Close LOB object

### Description

cubrid_lob2_close(resource `$lob_identifier`): bool

The cubrid_lob2_close() function is used to close LOB object returned from cubrid_lob2_new() or got from the result set.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- cubrid_lob2_new() - Create a lob object

# cubrid_lob2_export

(PECL CUBRID >= 8.4.1)

cubrid_lob2_export — Export the lob object to a file

### Description

cubrid_lob2_export(resource `$lob_identifier`, string `$file_name`): bool

The cubrid_lob2_export() function is used to save the contents of BLOB/CLOB data to a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`filename`
  File name you want to store BLOB/CLOB data. It also supports the path of the file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_export() example

`<?php
// Table: test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");
$req = cubrid_prepare($conn, "select * from doc");
cubrid_execute($req);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$row = cubrid_fetch($req, CUBRID_NUM | CUBRID_LOB);
cubrid_lob2_export($row[1], "doc_3.txt");
cubrid_lob2_close($row[1]);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_new() - Create a lob object
- cubrid_lob2_close() - Close LOB object
- cubrid_lob2_import() - Import BLOB/CLOB data from a file
- cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters

# cubrid_lob2_import

(PECL CUBRID >= 8.4.1)

cubrid_lob2_import — Import BLOB/CLOB data from a file

### Description

cubrid_lob2_import(resource `$lob_identifier`, string `$file_name`): bool

The cubrid_lob2_import() function is used to save the contents of BLOB/CLOB data from a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`filename`
  File name you want to import BLOB/CLOB data. It also supports the path of the file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_export() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);
$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);
cubrid_execute($req);
cubrid_lob2_close($lob);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_new() - Create a lob object
- cubrid_lob2_close() - Close LOB object
- cubrid_lob2_export() - Export the lob object to a file
- cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters

# cubrid_lob2_new

(PECL CUBRID >= 8.4.1)

cubrid_lob2_new — Create a lob object

### Description

cubrid_lob2_new(resource `$conn_identifier` = ?, string `$type` = "BLOB"): resource

The cubrid_lob2_new() function is used to create a lob object (both BLOB and CLOB). This function should be used before you bind a lob object.

### Parameters

`conn_identifier`
  Connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() or cubrid_connect_with_url() is assumed.
`type`
  It may be "BLOB" or "CLOB", it won't be case-sensitive. The default value is "BLOB".

### Return Values

Lob identifier when it is successful, or `false` on failure.

### See Also

- cubrid_lob2_close() - Close LOB object

# cubrid_lob2_read

(PECL CUBRID >= 8.4.1)

cubrid_lob2_read — Read from BLOB/CLOB data

### Description

cubrid_lob2_read(resource `$lob_identifier`, int `$len`): string

The cubrid_lob2_read() function reads `len` bytes from the LOB data and returns the bytes read.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`len`
  Length from buffer you want to read from the lob data.

### Return Values

Returns the contents as a string, `false` when there is no more data, or `null` on failure.

### Examples

Example #1 cubrid_lob2_read() example 1

`<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "public", "");
$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
print "position now is " . cubrid_lob2_tell($row[1]) . "\n";
cubrid_lob2_seek($row[1], 10, CUBRID_CURSOR_FIRST);
print "\nposition after moving farword is " . cubrid_lob2_tell($row[1]) . "\n";
$data = cubrid_lob2_read($row[1], 12);
print "\nposition after reading is " . cubrid_lob2_tell($row[1]) . "\n";
print $data . "\n";
cubrid_lob2_seek($row[1], 5, CUBRID_CURSOR_CURRENT);
print "\nposition after moving again is " . cubrid_lob2_tell($row[1]) . "\n";
$data = cubrid_lob2_read($row[1], 20);
print $data . "\n";
cubrid_disconnect($conn);
?>`

Example #2 cubrid_lob2_read() example 2

`<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
while (true) {
if ($data = cubrid_lob2_read($row[1], 1024)) {
print $data . "\n";
}
elseif ($data === false) {
print "There is no more data\n";
break;
}
else {
print "There must some errors\n";
break;
}
}
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_seek

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek — Move the cursor of a lob object

### Description

cubrid_lob2_seek(resource `$lob_identifier`, int `$offset`, int `$origin` = CUBRID_CURSOR_CURRENT): bool

The cubrid_lob2_seek() function is used to move the cursor position of a lob object by the value set in the `offset` argument, to the direction set in the `origin` argument.

To set the `origin` argument, you can use `CUBRID_CURSOR_FIRST` to set the cursor position moving forward `offset` units from the first beginning. In this case, `offset` must be a positive value.

If you use `CUBRID_CURSOR_CURRENT` for `origin`, you can move forward or backward. and `offset` can be positive or negative.

If you use `CUBRID_CURSOR_LAST` for `origin`, you can move backward `offset` units from the end of LOB object and `offset` only can be positive.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`offset`
  Number of units you want to move the cursor.
`origin`
  This parameter can be the following values: CUBRID_CURSOR_FIRST: move forward from the first beginning. CUBRID_CURSOR_CURRENT: move forward or backward from the current position. CUBRID_CURSOR_LAST: move backward at the end of LOB object.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_seek() example

`<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");
$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");
cubrid_lob2_seek($lob, 0, CUBRID_CURSOR_LAST);
cubrid_lob2_write($lob, "beautiful");
cubrid_lob2_seek($lob, 15, CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 5);
echo $data."\n";
cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_seek64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek64 — Move the cursor of a lob object

### Description

cubrid_lob2_seek64(resource `$lob_identifier`, string `$offset`, int `$origin` = CUBRID_CURSOR_CURRENT): bool

The cubrid_lob2_seek64() function is used to move the cursor position of a lob object by the value set in the `offset` argument, to the direction set in the `origin` argument. If the `offset` you want to move is larger than an integer data can be stored, you can use this function.

To set the `origin` argument, you can use `CUBRID_CURSOR_FIRST` to set the cursor position moving forward `offset` units from the first beginning. In this case, `offset` must be a positive value.

If you use `CUBRID_CURSOR_CURRENT` for `origin`, you can move forward or backward. and `offset` can be positive or negative.

If you use `CUBRID_CURSOR_LAST` for `origin`, you can move backward `offset` units from the end of LOB object and `offset` only can be positive.

> Note: If you use this function to move the cursor position of the lob object, you should pass `offset` as a string.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`offset`
  Number of units you want to move the cursor.
`origin`
  This parameter can be the following values: CUBRID_CURSOR_FIRST: move forward from the first beginning. CUBRID_CURSOR_CURRENT: move forward or backward from the current position. CUBRID_CURSOR_LAST: move backward at the end of LOB object.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_seek64() example

`<?php
// test_lob (id INT, contents CLOB)
// Data length of doc_1.txt should be greater than 20101029056306120215.
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);
$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);
cubrid_execute($req);
cubrid_lob2_close($lob);
$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob = $row[1];
cubrid_lob2_seek64($lob, "20101029056306120215", CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 20);
echo $data."\n";
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_size

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size — Get a lob object's size

### Description

cubrid_lob2_size(resource `$lob_identifier`): int

The cubrid_lob2_size() function is used to get the size of a lob object.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.

### Return Values

It will return the size of the LOB object when it processes successfully, or `false` on failure.

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_size64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size64 — Get a lob object's size

### Description

cubrid_lob2_size64(resource `$lob_identifier`): string

The cubrid_lob2_size64() function is used to get the size of a lob object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the size as a string.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.

### Return Values

It will return the size of the LOB object as a string when it processes successfully, or `false` on failure.

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size

# cubrid_lob2_tell

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell — Tell the cursor position of the LOB object

### Description

cubrid_lob2_tell(resource `$lob_identifier`): int

The cubrid_lob2_tell() function is used to tell the cursor position of the LOB object.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.

### Return Values

It will return the cursor position on the LOB object when it processes successfully, or `false` on failure.

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_tell64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell64 — Tell the cursor position of the LOB object

### Description

cubrid_lob2_tell64(resource `$lob_identifier`): string

The cubrid_lob2_tell64() function is used to tell the cursor position of the LOB object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the position information as a string.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.

### Return Values

It will return the cursor position on the LOB object as a string when it processes successfully, or `false` on failure.

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_write() - Write to a lob object
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lob2_write

(PECL CUBRID >= 8.4.1)

cubrid_lob2_write — Write to a lob object

### Description

cubrid_lob2_write(resource `$lob_identifier`, string `$buf`): bool

The cubrid_lob2_write() function reads as much as data from `buf` and stores it to the LOB object. Note that this function can only append characters now.

### Parameters

`lob_identifier`
  Lob identifier as a result of cubrid_lob2_new() or get from the result set.
`buf`
  Data that need to be written to the lob object.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lob2_write() example 1

`<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");
$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");
cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);
cubrid_disconnect($conn);
?>`

Example #2 cubrid_lob2_write() example 2

`<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");
cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(1, ?)");
$lob1 = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob1, "cubrid php driver");
cubrid_lob2_bind($req, 1, $lob1);
cubrid_execute($req);
$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob2 = $row[1];
cubrid_lob2_seek($lob2, 0, CUBRID_CURSOR_LAST);
$pos = cubrid_lob2_tell($lob2);
print "pos before write: $pos\n";
cubrid_lob2_write($lob2, "Hello world");
$pos = cubrid_lob2_tell($lob2);
print "pos after write: $pos\n";
cubrid_disconnect($conn);
?>`

### See Also

- cubrid_lob2_read() - Read from BLOB/CLOB data
- cubrid_lob2_seek() - Move the cursor of a lob object
- cubrid_lob2_seek64() - Move the cursor of a lob object
- cubrid_lob2_tell() - Tell the cursor position of the LOB object
- cubrid_lob2_tell64() - Tell the cursor position of the LOB object
- cubrid_lob2_size() - Get a lob object's size
- cubrid_lob2_size64() - Get a lob object's size

# cubrid_lock_read

(PECL CUBRID >= 8.3.0)

cubrid_lock_read — Set a read lock on the given OID

### Description

cubrid_lock_read(resource `$conn_identifier`, string `$oid`): bool

The cubrid_lock_read() function is used to put read lock on the instance pointed by given `oid`.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to put read lock on.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lock_read() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
cubrid_lock_read($conn, $oid);
$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);
$attr = cubrid_get($conn, $oid);
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    string(9) "{1, 2, 3}"
    array(4) {
      ["a"]=>
      string(1) "1"
      ["b"]=>
      array(3) {
        [0]=>
        string(1) "1"
        [1]=>
        string(1) "2"
        [2]=>
        string(1) "3"
      }
      ["c"]=>
      array(4) {
        [0]=>
        string(2) "11"
        [1]=>
        string(2) "22"
        [2]=>
        string(2) "33"
        [3]=>
        string(3) "333"
      }
      ["d"]=>
      string(10) "a         "
    }

### See Also

- cubrid_lock_write() - Set a write lock on the given OID

# cubrid_lock_write

(PECL CUBRID >= 8.3.0)

cubrid_lock_write — Set a write lock on the given OID

### Description

cubrid_lock_write(resource `$conn_identifier`, string `$oid`): bool

The cubrid_lock_write() function is used to put write lock on the instance pointed by the given `oid`.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to put write lock on.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_lock_write() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
cubrid_lock_write($conn, $oid);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_put($conn, $oid, "b", array(2, 4, 8));
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    array(3) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "4"
      [2]=>
      string(1) "8"
    }

### See Also

- cubrid_lock_read() - Set a read lock on the given OID

# cubrid_move_cursor

(PECL CUBRID >= 8.3.0)

cubrid_move_cursor — Move the cursor in the result

### Description

cubrid_move_cursor(resource `$req_identifier`, int `$offset`, int `$origin` = CUBRID_CURSOR_CURRENT): bool

The cubrid_move_cursor() function is used to move the current cursor location of `req_identifier` by the value set in the `offset` argument, to the direction set in the `origin` argument. To set the `origin` argument, you can use `CUBRID_CURSOR_FIRST` for the first part of the result, `CUBRID_CURSOR_CURRENT` for the current location of the result, or `CUBRID_CURSOR_LAST` for the last part of the result. If `origin` argument is not explicitly designated, then the function uses `CUBRID_CURSOR_CURRENT` as its default value.

If the value of cursor movement range goes over the valid limit, then the cursor moves to the next location after the valid range for the cursor. For example, if you move 20 units in the result with the size of 10, then the cursor will move to 11th place and return `CUBRID_NO_MORE_DATA`.

### Parameters

`req_identifier`
  Request identifier.
`offset`
  Number of units you want to move the cursor.
`origin`
  Location where you want to move the cursor from `CUBRID_CURSOR_FIRST`, `CUBRID_CURSOR_CURRENT`, `CUBRID_CURSOR_LAST`.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_move_cursor() example

`<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_move_cursor($req, 1, CUBRID_CURSOR_LAST);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_CURRENT);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(2) {
      [0]=>
      string(1) "G"
      [1]=>
      string(4) "Gold"
    }
    array(2) {
      [0]=>
      string(1) "X"
      [1]=>
      string(5) "Mixed"
    }
    array(2) {
      [0]=>
      string(1) "M"
      [1]=>
      string(3) "Man"
    }

### See Also

- cubrid_execute() - Execute a prepared SQL statement

# cubrid_next_result

(PECL CUBRID >= 8.4.0)

cubrid_next_result — Get result of next query when executing multiple SQL statements

### Description

cubrid_next_result(resource `$result`): bool

The cubrid_next_result() function is used to get results of next query if multiple SQL statements are executed and `CUBRID_EXEC_QUERY_ALL` flag is set upon cubrid_execute().

### Parameters

`result`
  `result` comes from a call to cubrid_execute()

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_next_result() example

`<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
$sql_stmt = "SELECT * FROM code; SELECT * FROM history WHERE host_year=2004 AND event_code=20281";
$res = cubrid_execute($conn, $sql_stmt, CUBRID_EXEC_QUERY_ALL);
get_result_info($res);
cubrid_next_result($res);
get_result_info($res);
function get_result_info($req)
{
printf("\n------------ get_result_info --------------------\n");
$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);
$column_name_list = cubrid_column_names($req);
$column_type_list = cubrid_column_types($req);
$column_last_name = cubrid_field_name($req, $col_num - 1);
$column_last_table = cubrid_field_table($req, $col_num - 1);
$column_last_type = cubrid_field_type($req, $col_num - 1);
$column_last_len = cubrid_field_len($req, $col_num - 1);
$column_1_flags = cubrid_field_flags($req, 1);
printf("%-30s %d\n", "Row count:", $row_num);
printf("%-30s %d\n", "Column count:", $col_num);
printf("\n");
printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Len");
printf("------------------------------------------------------------------------------\n");
$size = count($column_name_list);
for($i = 0; $i < $size; $i++) {
$column_len = cubrid_field_len($req, $i);
printf("%-30s %-30s %-15s\n", $column_name_list[$i], $column_type_list[$i], $column_len);
}
printf("\n\n");
printf("%-30s %s\n", "Last Column Name:", $column_last_name);
printf("%-30s %s\n", "Last Column Table:", $column_last_table);
printf("%-30s %s\n", "Last Column Type:", $column_last_type);
printf("%-30s %d\n", "Last Column Len:", $column_last_len);
printf("%-30s %s\n", "Second Column Flags:", $column_1_flags);
printf("\n\n");
}
?>`

The above example will output:

    ------------ get_result_info --------------------
    Row count:                     6
    Column count:                  2

    Column Names                   Column Types                   Column Len
    ------------------------------------------------------------------------------
    s_name                         char                           1
    f_name                         varchar                        6

    Last Column Name:              f_name
    Last Column Table:             code
    Last Column Type:              varchar
    Last Column Len:               6
    Second Column Flags:

    ------------ get_result_info --------------------
    Row count:                     4
    Column count:                  5

    Column Names                   Column Types                   Column Len
    ------------------------------------------------------------------------------
    event_code                     integer                        11
    athlete                        varchar                        40
    host_year                      integer                        11
    score                          varchar                        10
    unit                           varchar                        5

    Last Column Name:              unit
    Last Column Table:             history
    Last Column Type:              varchar
    Last Column Len:               5
    Second Column Flags:           not_null primary_key unique_key

### See Also

- cubrid_execute() - Execute a prepared SQL statement

# cubrid_num_cols

(PECL CUBRID >= 8.3.0)

cubrid_num_cols — Return the number of columns in the result set

### Description

cubrid_num_cols(resource `$result`): int

The cubrid_num_cols() function is used to get the number of columns from the query result. It can only be used when the query executed is a `SELECT` statement.

### Parameters

`result`
  Result.

### Return Values

Number of columns, when process is successful.

`false`, if SQL statement is not SELECT.

### Examples

Example #1 cubrid_num_cols() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$req = cubrid_execute($conn, "SELECT * FROM code");
$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);
printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);
cubrid_disconnect($conn);
?>`

The above example will output:

    Row Num: 6
    Column Num: 2

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_num_rows() - Get the number of rows in the result set

# cubrid_num_rows

(PECL CUBRID >= 8.3.0)

cubrid_num_rows — Get the number of rows in the result set

### Description

cubrid_num_rows(resource `$result`): int

The cubrid_num_rows() function is used to get the number of rows from the query result. It can be used for `SELECT` statements. For `INSERT`, `UPDATE`, or `DELETE` queries, use the cubrid_affected_rows() function.

Note: The cubrid_num_rows() function can only be used for synchronous query; it returns 0 when it is used for asynchronous query.

### Parameters

`result`
  `result` comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

### Return Values

Number of rows, when process is successful.

0 when the query was done in async mode.

-1, if SQL statement is not SELECT.

`false` when process is unsuccessful.

### Examples

Example #1 cubrid_num_rows() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$req = cubrid_execute($conn, "SELECT * FROM code");
$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);
printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);
cubrid_disconnect($conn);
?>`

The above example will output:

    Row Num: 6
    Column Num: 2

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_num_cols() - Return the number of columns in the result set
- cubrid_affected_rows() - Return the number of rows affected by the last SQL statement

# cubrid_pconnect

(PECL CUBRID >= 8.3.1)

cubrid_pconnect — Open a persistent connection to a CUBRID server

### Description

cubrid_pconnect(
string `$host`,
int `$port`,
string `$dbname`,
string `$userid` = ?,
string `$passwd` = ?
): resource

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect() acts very much like cubrid_connect() with two major differences.

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

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

This type of link is therefore called 'persistent'.

### Parameters

`host`
  Host name or IP address of CUBRID CAS server.
`port`
  Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).
`dbname`
  Name of database.
`userid`
  User name for the database.
`passwd`
  User password.

### Return Values

Connection identifier, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_connect() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_pconnect("localhost", 33000, "demodb", "dba");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

### See Also

- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
- cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
- cubrid_disconnect() - Close a database connection
- cubrid_close() - Close CUBRID connection

# cubrid_pconnect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_pconnect_with_url — Open a persistent connection to CUBRID server

### Description

cubrid_pconnect_with_url(string `$conn_url`, string `$userid` = ?, string `$passwd` = ?): resource

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect_with_url() acts very much like cubrid_connect_with_url() with two major differences.

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

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

This type of link is therefore called 'persistent'.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

- host : A host name or IP address of the master database
- db_name : A name of the database
- db_user : A name of the database user
- db_password : A database user password
- alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
- rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
- login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
- query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
- disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

> Note: `?` and `:` that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "`?:`". $url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100"; Passwords that contain `?` or `:` may be passed as a separate parameter. $url = "CUBRID:localhost:33000:tbd:::?login_timeout=100"; $conn = cubrid_pconnect_with_url ($url, "dba", "12?"); If user or password is empty,you can't delete "`:`",the following is an example. $url = "CUBRID:localhost:33000:demodb:::";

### Parameters

`conn_url`
  A character string that contains server connection information.
`userid`
  User name for the database.
`passwd`
  User password.

### Return Values

Connection identifier, when process is successful, or `false` on failure.

### Examples

Example #1 cubrid_pconnect_with_url() url without properties example

`<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::";
$con = cubrid_pconnect_with_url ($conn_url);
if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_disconnect ($con);
}
?>`

Example #2 cubrid_pconnect_with_url() url with properties example

`<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?althost=10.34.63.132:33088&rctime=100";
$con = cubrid_pconnect_with_url ($conn_url);
if ($con) {
echo "connected successfully";
$req =cubrid_execute($con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_disconnect ($con);
}
?>`

### See Also

- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
- cubrid_pconnect() - Open a persistent connection to a CUBRID server
- cubrid_disconnect() - Close a database connection
- cubrid_close() - Close CUBRID connection

# cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare a SQL statement for execution

### Description

cubrid_prepare(resource `$conn_identifier`, string `$prepare_stmt`, int `$option` = 0): resource

The cubrid_prepare() function is a sort of API which represents SQL statements compiled previously to a given connection handle. This pre-compiled SQL statement will be included in the cubrid_prepare().

Accordingly, you can use this statement effectively to execute several times repeatedly or to process long data. Only a single statement can be used and a parameter may put a question mark (?) to appropriate area in the SQL statement. Add a parameter when you bind a value in the VALUES clause of INSERT statement or in the WHERE clause. Note that it is allowed to bind a value to a MARK(?) by using the cubrid_bind() function only.

### Parameters

`conn_identifier`
  Connection identifier.
`prepare_stmt`
  Prepare query.
`option`
  OID return option `CUBRID_INCLUDE_OID`.

### Return Values

Request identifier, if process is successful, or `false` on failure.

### Examples

Example #1 cubrid_prepare() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$sql = <<<EOD
SELECT g.event_code, e.name
FROM game g
JOIN event e ON g.event_code=e.code
WHERE host_year = ? AND event_code NOT IN (SELECT event_code FROM game WHERE host_year=?) GROUP BY event_code;
EOD;
$req = cubrid_prepare($conn, $sql);
cubrid_bind($req, 1, 2004);
cubrid_bind($req, 2, 2000);
cubrid_execute($req);
$row_num = cubrid_num_rows($req);
printf("There are %d event that exits in 2004 olympic but not in 2000. For example:\n\n", $row_num);
printf("%-15s %s\n", "Event_code", "Event_name");
printf("----------------------------\n");
$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);
$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);
cubrid_disconnect($conn);
?>`

The above example will output:

    There are 27 event that exits in 2004 olympic but not in 2000. For example:

    Event_code      Event_name
    ----------------------------
    20063           +91kg
    20070           64kg

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_bind() - Bind variables to a prepared statement as parameters

# cubrid_put

(PECL CUBRID >= 8.3.0)

cubrid_put — Update a column using OID

### Description

cubrid_put(
resource `$conn_identifier`,
string `$oid`,
string `$attr` = ?,
mixed `$value`
): bool

The cubrid_put() function is used to update an attribute of the instance of the given `oid`.

You can update single attribute by using string data type to set `attr`. In such case, you can use integer, floating point or string type data for the `value` argument. To update multiple number of attributes, you can disregard the `attr` argument, and set `value` argument with associative array data type.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance that you want to update.
`attr`
  Name of the attribute that you want to update.
`value`
  New value that you want to assign to the attribute.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_put() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_put($conn, $oid, "b", array(2, 4, 8));
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    array(3) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "4"
      [2]=>
      string(1) "8"
    }

### See Also

- cubrid_get() - Get a column using OID
- cubrid_set_add() - Insert a single element to set type column using OID
- cubrid_set_drop() - Delete an element from set type column using OID
- cubrid_seq_insert() - Insert an element to a sequence type column using OID
- cubrid_seq_drop() - Delete an element from sequence type column using OID
- cubrid_seq_put() - Update the element value of sequence type column using OID

# cubrid_rollback

(PECL CUBRID >= 8.3.0)

cubrid_rollback — Roll back a transaction

### Description

cubrid_rollback(resource `$conn_identifier`): bool

The cubrid_rollback() function executes rollback on the transaction pointed by `conn_identifier`, currently in progress.

Connection to server is closed after calling cubrid_rollback(). Connection handle, however, is still valid.

### Parameters

`conn_identifier`
  Connection identifier.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_rollback() example

`<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
cubrid_set_autocommit($conn,false);
@cubrid_execute($conn, "DROP TABLE publishers");
$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;
if (!cubrid_execute($conn, $sql)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());
cubrid_disconnect($conn);
exit;
}
$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");
$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");
for ($i = 0, $size = count($id_list); $i < $size; $i++) {
cubrid_bind($req, 1, $id_list[$i]);
cubrid_bind($req, 2, $name_list[$i]);
cubrid_bind($req, 3, $city_list[$i]);
cubrid_bind($req, 4, $state_list[$i]);
cubrid_bind($req, 5, $country_list[$i]);
if (!($ret = cubrid_execute($req))) {
break;
}
}
if (!$ret) {
cubrid_rollback($conn);
} else {
cubrid_commit($conn);
$req = cubrid_execute($conn, "SELECT * FROM publishers");
while ($result = cubrid_fetch_assoc($req)) {
printf("%-3s %-20s %-15s %-3s %-15s\n",
$result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
}
}
cubrid_disconnect($conn);
?>`

The above example will output:

    P01 Abatis Publishers    New York        NY  USA
    P02 Core Dump Books      San Francisco   CA  USA
    P03 Schadenfreude Press  Hamburg             Germany
    P04 Tenterhooks Press    Berkeley        CA  USA

### See Also

- cubrid_commit() - Commit a transaction
- cubrid_disconnect() - Close a database connection

# cubrid_schema

(PECL CUBRID >= 8.3.0)

cubrid_schema — Get the requested schema information

### Description

cubrid_schema(
resource `$conn_identifier`,
int `$schema_type`,
string `$class_name` = ?,
string `$attr_name` = ?
): array

The cubrid_schema() function is used to get the requested schema information from database. To get information about specific class, set the `class_name`, to get information about specific attribute (can be used only with `CUBRID_SCH_ATTR_PRIVILEGE`), set the `attr_name`.

The result of the cubrid_schema() function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
--- | --- | --- | ---
CUBRID_SCH_CLASS | 1 | NAME |
| 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_VCLASS | 1 | NAME |
| 2 | TYPE | 1:vclass
CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
CUBRID_SCH_ATTRIBUTE / CUBRID_SCH_CLASS_ATTRIBUTE | 1 | ATTR_NAME |
| 2 | DOMAIN |
| 3 | SCALE |
| 4 | PRECISION |
| 5 | INDEXED | 1:indexed
| 6 | NOT NULL | 1:not null
| 7 | SHARED | 1:shared
| 8 | UNIQUE | 1:unique
| 9 | DEFAULT |
| 10 | ATTR_ORDER | base:1
| 11 | CLASS_NAME |
| 12 | SOURCE_CLASS |
| 13 | IS_KEY | 1:key
CUBRID_SCH_METHOD / CUBRID_SCH_CLASS_METHOD | 1 | NAME |
| 2 | RET_DOMAIN |
| 3 | ARG_DOMAIN |
CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
CUBRID_SCH_SUPERCLASS / CUBRID_SCH_DIRECT_SUPER_CLASS / CUBRID_SCH_SUBCLASS | 1 | CLASS_NAME |
| 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
| 2 | NAME |
| 3 | ATTR_NAME |
| 4 | NUM_PAGES |
| 5 | NUM_KEYS |
| 6 | PRIMARY_KEY | 1:primary key
| 7 | KEY_ORDER | base:1
CUBRID_SCH_TRIGGER | 1 | NAME |
| 2 | STATUS |
| 3 | EVENT |
| 4 | TARGET_CLASS |
| 5 | TARGET_ATTR |
| 6 | ACTION_TIME |
| 7 | ACTION |
| 8 | PRIORITY |
| 9 | CONDITION_TIME |
| 10 | CONDITION |
CUBRID_SCH_CLASS_PRIVILEGE / CUBRID_SCH_ATTR_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
| 2 | PRIVILEGE |
| 3 | GRANTABLE |
CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
| 2 | ATTR_NAME |
| 3 | KEY_SEQ | base:1
| 4 | KEY_NAME |
CUBRID_SCH_IMPORTED_KEYS / CUBRID_SCH_EXPORTED_KEYS / CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
| 2 | PKCOLUMN_NAME |
| 3 | FKTABLE_NAME | base:1
| 4 | FKCOLUMN_NAME |
| 5 | KEY_SEQ | base:1
| 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
| 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
| 8 | FK_NAME |
| 9 | PK_NAME |

### Parameters

`conn_identifier`
  Connection identifier.
`schema_type`
  Schema data that you want to know.
`class_name`
  Class you want to know the schema of.
`attr_name`
  Attribute you want to know the schema of.

### Return Values

Array containing the schema information, when process is successful, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

### Examples

Example #1 cubrid_schema() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
printf("\n--- Primary Key ---\n");
$pk = cubrid_schema($conn, CUBRID_SCH_PRIMARY_KEY, "game");
var_dump($pk);
printf("\n--- Foreign Keys ---\n");
$fk = cubrid_schema($conn, CUBRID_SCH_IMPORTED_KEYS, "game");
var_dump($fk);
printf("\n--- Column Attribute ---\n");
$attr = cubrid_schema($conn, CUBRID_SCH_ATTRIBUTE, "stadium", "area");
var_dump($attr);
cubrid_disconnect($conn);
?>`

The above example will output:

    --- Primary Key ---
    array(3) {
      [0]=>
      array(4) {
        ["CLASS_NAME"]=>
        string(4) "game"
        ["ATTR_NAME"]=>
        string(12) "athlete_code"
        ["KEY_SEQ"]=>
        string(1) "3"
        ["KEY_NAME"]=>
        string(41) "pk_game_host_year_event_code_athlete_code"
      }
      [1]=>
      array(4) {
        ["CLASS_NAME"]=>
        string(4) "game"
        ["ATTR_NAME"]=>
        string(10) "event_code"
        ["KEY_SEQ"]=>
        string(1) "2"
        ["KEY_NAME"]=>
        string(41) "pk_game_host_year_event_code_athlete_code"
      }
      [2]=>
      array(4) {
        ["CLASS_NAME"]=>
        string(4) "game"
        ["ATTR_NAME"]=>
        string(9) "host_year"
        ["KEY_SEQ"]=>
        string(1) "1"
        ["KEY_NAME"]=>
        string(41) "pk_game_host_year_event_code_athlete_code"
      }
    }

    --- Foreign Keys ---
    array(2) {
      [0]=>
      array(9) {
        ["PKTABLE_NAME"]=>
        string(7) "athlete"
        ["PKCOLUMN_NAME"]=>
        string(4) "code"
        ["FKTABLE_NAME"]=>
        string(4) "game"
        ["FKCOLUMN_NAME"]=>
        string(12) "athlete_code"
        ["KEY_SEQ"]=>
        string(1) "1"
        ["UPDATE_RULE"]=>
        string(1) "1"
        ["DELETE_RULE"]=>
        string(1) "1"
        ["FK_NAME"]=>
        string(20) "fk_game_athlete_code"
        ["PK_NAME"]=>
        string(15) "pk_athlete_code"
      }
      [1]=>
      array(9) {
        ["PKTABLE_NAME"]=>
        string(5) "event"
        ["PKCOLUMN_NAME"]=>
        string(4) "code"
        ["FKTABLE_NAME"]=>
        string(4) "game"
        ["FKCOLUMN_NAME"]=>
        string(10) "event_code"
        ["KEY_SEQ"]=>
        string(1) "1"
        ["UPDATE_RULE"]=>
        string(1) "1"
        ["DELETE_RULE"]=>
        string(1) "1"
        ["FK_NAME"]=>
        string(18) "fk_game_event_code"
        ["PK_NAME"]=>
        string(13) "pk_event_code"
      }
    }

    --- Column Attribute ---
    array(1) {
      [0]=>
      array(13) {
        ["ATTR_NAME"]=>
        string(4) "area"
        ["DOMAIN"]=>
        string(1) "7"
        ["SCALE"]=>
        string(1) "2"
        ["PRECISION"]=>
        string(2) "10"
        ["INDEXED"]=>
        string(1) "0"
        ["NON_NULL"]=>
        string(1) "0"
        ["SHARED"]=>
        string(1) "0"
        ["UNIQUE"]=>
        string(1) "0"
        ["DEFAULT"]=>
        NULL
        ["ATTR_ORDER"]=>
        string(1) "4"
        ["CLASS_NAME"]=>
        string(7) "stadium"
        ["SOURCE_CLASS"]=>
        string(7) "stadium"
        ["IS_KEY"]=>
        string(1) "0"
      }
    }

# cubrid_seq_drop

(PECL CUBRID >= 8.3.0)

cubrid_seq_drop — Delete an element from sequence type column using OID

### Description

cubrid_seq_drop(
resource `$conn_identifier`,
string `$oid`,
string `$attr_name`,
int `$index`
): bool

The cubrid_seq_drop() function is used to delete an element you request from the given sequence type attribute in the database.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance you want to work with.
`attr_name`
  Name of the attribute that you want to delete an element from.
`index`
  Index of the element that you want to delete (1-based).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_seq_drop() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_seq_drop($conn, $oid, "c", 4);
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
      [3]=>
      string(3) "333"
    }
    array(3) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
    }

### See Also

- cubrid_seq_insert() - Insert an element to a sequence type column using OID
- cubrid_seq_put() - Update the element value of sequence type column using OID

# cubrid_seq_insert

(PECL CUBRID >= 8.3.0)

cubrid_seq_insert — Insert an element to a sequence type column using OID

### Description

cubrid_seq_insert(
resource `$conn_identifier`,
string `$oid`,
string `$attr_name`,
int `$index`,
string `$seq_element`
): bool

The cubrid_col_insert() function is used to insert an element to a sequence type attribute in a requested location.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance you want to work with.
`attr_name`
  Name of the attribute you want to insert an instance to.
`index`
  Location of the element, you want to insert the element to (1-based).
`seq_element`
  Content of the element that you want to insert.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_seq_insert() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_seq_insert($conn, $oid, "c", 5, "44");
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
      [3]=>
      string(3) "333"
    }
    array(5) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
      [3]=>
      string(3) "333"
      [4]=>
      string(2) "44"
    }

### See Also

- cubrid_seq_drop() - Delete an element from sequence type column using OID
- cubrid_seq_put() - Update the element value of sequence type column using OID

# cubrid_seq_put

(PECL CUBRID >= 8.3.0)

cubrid_seq_put — Update the element value of sequence type column using OID

### Description

cubrid_seq_put(
resource `$conn_identifier`,
string `$oid`,
string `$attr_name`,
int `$index`,
string `$seq_element`
): bool

The cubrid_seq_put() function is used to update the content of the requested element in a sequent type attribute using OID.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance you want to work with.
`attr_name`
  Name of the attribute that you want to update an element.
`index`
  Index (1-based) of the element that you want to update.
`seq_element`
  New content that you want to use for the update.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_seq_put() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_seq_put($conn, $oid, "c", 1, "111");
$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
      [3]=>
      string(3) "333"
    }
    array(4) {
      [0]=>
      string(3) "111"
      [1]=>
      string(2) "22"
      [2]=>
      string(2) "33"
      [3]=>
      string(3) "333"
    }

### See Also

- cubrid_seq_drop() - Delete an element from sequence type column using OID
- cubrid_seq_insert() - Insert an element to a sequence type column using OID

# cubrid_set_add

(PECL CUBRID >= 8.3.0)

cubrid_set_add — Insert a single element to set type column using OID

### Description

cubrid_set_add(
resource `$conn_identifier`,
string `$oid`,
string `$attr_name`,
string `$set_element`
): bool

The cubrid_set_add() function is used to insert a single element to a set type attribute (set, multiset, sequence) you requested.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance you want to work with.
`attr_name`
  Name of the attribute you want to insert an element.
`set_element`
  Content of the element you want to insert.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_set_add() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_set_add($conn, $oid, "b", "4");
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    array(4) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
      [3]=>
      string(1) "4"
    }

### See Also

- cubrid_seq_drop() - Delete an element from sequence type column using OID

# cubrid_set_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_set_autocommit — Set autocommit mode of the connection

### Description

cubrid_set_autocommit(resource `$conn_identifier`, bool `$mode`): bool

The cubrid_set_autocommit() function is used to set the CUBRID database auto-commit mode of the current database connection.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. When auto-commit mode is truned from off to on, any pending work is automatically committed.

### Parameters

`conn_identifier`
  Connection identifier.
`mode`
  Auto-commit mode. The following constants can be used:
  - `CUBRID_AUTOCOMMIT_FALSE`
  - `CUBRID_AUTOCOMMIT_TRUE`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- cubrid_get_autocommit() - Get auto-commit mode of the connection
- cubrid_commit() - Commit a transaction

# cubrid_set_db_parameter

(PECL CUBRID >= 8.4.0)

cubrid_set_db_parameter — Sets the CUBRID database parameters

### Description

cubrid_set_db_parameter(resource `$conn_identifier`, int `$param_type`, int `$param_value`): bool

The cubrid_set_db_parameter() function is used to set the CUBRID database parameters. It can set the following CUBRID database parameters:

- `PARAM_ISOLATION_LEVEL`
- `PARAM_LOCK_TIMEOUT`

> Note: The auto-commit mode can be set by using cubrid_set_autocommit().

### Parameters

`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.
`param_type`
  Database parameter type.
`param_value`
  Isolation level value (1-6) or lock timeout (in seconds) value.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_get_db_parameter() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$params = cubrid_get_db_parameter($conn);
var_dump($params);
cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE);
cubrid_set_db_parameter($conn, CUBRID_PARAM_ISOLATION_LEVEL, 2);
$params_new = cubrid_get_db_parameter($conn);
var_dump($params_new);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      ["PARAM_ISOLATION_LEVEL"]=>
      int(3)
      ["PARAM_LOCK_TIMEOUT"]=>
      int(-1)
      ["PARAM_MAX_STRING_LENGTH"]=>
      int(1073741823)
      ["PARAM_AUTO_COMMIT"]=>
      int(0)
    }
    array(4) {
      ["PARAM_ISOLATION_LEVEL"]=>
      int(2)
      ["PARAM_LOCK_TIMEOUT"]=>
      int(-1)
      ["PARAM_MAX_STRING_LENGTH"]=>
      int(1073741823)
      ["PARAM_AUTO_COMMIT"]=>
      int(1)
    }

### See Also

- cubrid_get_db_parameter() - Returns the CUBRID database parameters
- cubrid_set_autocommit() - Set autocommit mode of the connection

# cubrid_set_drop

(PECL CUBRID >= 8.3.0)

cubrid_set_drop — Delete an element from set type column using OID

### Description

cubrid_set_drop(
resource `$conn_identifier`,
string `$oid`,
string `$attr_name`,
string `$set_element`
): bool

The cubrid_set_drop() function is used to delete an element that you request from the given set type (set, multiset) attribute of the database.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  OID of the instance you want to work with.
`attr_name`
  Name of the attribute you want to delete an element from.
`set_element`
  Content of the element you want to delete.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_set_drop() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);
cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_set_drop($conn, $oid, "b", "1");
$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    array(2) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "3"
    }

### See Also

- cubrid_set_add() - Insert a single element to set type column using OID

# cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

### Description

cubrid_set_query_timeout(resource `$req_identifier`, int `$timeout`): bool

The cubrid_set_query_timeout() function is used to set the timeout time of query execution.

### Parameters

`req_identifier`
  Request identifier.
`timeout`
  Timeout time in milliseconds.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- cubrid_get_query_timeout() - Get the query timeout value of the request

# cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

### Description

cubrid_version(): string

The cubrid_version() function is used to get the CUBRID PHP module's version.

### Parameters

This function has no parameters.

### Return Values

Version information (eg. "8.3.1.0001").

### Examples

Example #1 cubrid_version() example

`<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());
printf("\n");
$conn = cubrid_connect("localhost", 33088, "demodb", "dba");
if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}
$db_params = cubrid_get_db_parameter($conn);
while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}
printf("\n");
$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();
printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);
printf("\n");
$charset = cubrid_get_charset($conn);
printf("%-30s %s\n", "CUBRID Charset:", $charset);
cubrid_disconnect($conn);
?>`

The above example will output:

    CUBRID PHP Version:            9.1.0.0001

    PARAM_ISOLATION_LEVEL          3
    LOCK_TIMEOUT                   -1
    MAX_STRING_LENGTH              1073741823
    PARAM_AUTO_COMMIT              1

    Server Info:                   9.1.0.0212
    Client Info:                   9.1.0

    CUBRID Charset:                iso8859-1

### See Also

- cubrid_error_code() - Get error code for the most recent function call
- cubrid_error_code_facility() - Get the facility code of error

## Table of Contents

- cubrid_bind — Bind variables to a prepared statement as parameters
- cubrid_close_prepare — Close the request handle
- cubrid_close_request — Close the request handle
- cubrid_col_get — Get contents of collection type column using OID
- cubrid_col_size — Get the number of elements in collection type column using OID
- cubrid_column_names — Get the column names in result
- cubrid_column_types — Get column types in result
- cubrid_commit — Commit a transaction
- cubrid_connect — Open a connection to a CUBRID Server
- cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
- cubrid_current_oid — Get OID of the current cursor location
- cubrid_disconnect — Close a database connection
- cubrid_drop — Delete an instance using OID
- cubrid_error_code — Get error code for the most recent function call
- cubrid_error_code_facility — Get the facility code of error
- cubrid_error_msg — Get last error message for the most recent function call
- cubrid_execute — Execute a prepared SQL statement
- cubrid_fetch — Fetch the next row from a result set
- cubrid_free_result — Free the memory occupied by the result data
- cubrid_get — Get a column using OID
- cubrid_get_autocommit — Get auto-commit mode of the connection
- cubrid_get_charset — Return the current CUBRID connection charset
- cubrid_get_class_name — Get the class name using OID
- cubrid_get_client_info — Return the client library version
- cubrid_get_db_parameter — Returns the CUBRID database parameters
- cubrid_get_query_timeout — Get the query timeout value of the request
- cubrid_get_server_info — Return the CUBRID server version
- cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
- cubrid_is_instance — Check whether the instance pointed by OID exists
- cubrid_lob_close — Close BLOB/CLOB data
- cubrid_lob_export — Export BLOB/CLOB data to file
- cubrid_lob_get — Get BLOB/CLOB data
- cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
- cubrid_lob_size — Get BLOB/CLOB data size
- cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters
- cubrid_lob2_close — Close LOB object
- cubrid_lob2_export — Export the lob object to a file
- cubrid_lob2_import — Import BLOB/CLOB data from a file
- cubrid_lob2_new — Create a lob object
- cubrid_lob2_read — Read from BLOB/CLOB data
- cubrid_lob2_seek — Move the cursor of a lob object
- cubrid_lob2_seek64 — Move the cursor of a lob object
- cubrid_lob2_size — Get a lob object's size
- cubrid_lob2_size64 — Get a lob object's size
- cubrid_lob2_tell — Tell the cursor position of the LOB object
- cubrid_lob2_tell64 — Tell the cursor position of the LOB object
- cubrid_lob2_write — Write to a lob object
- cubrid_lock_read — Set a read lock on the given OID
- cubrid_lock_write — Set a write lock on the given OID
- cubrid_move_cursor — Move the cursor in the result
- cubrid_next_result — Get result of next query when executing multiple SQL statements
- cubrid_num_cols — Return the number of columns in the result set
- cubrid_num_rows — Get the number of rows in the result set
- cubrid_pconnect — Open a persistent connection to a CUBRID server
- cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
- cubrid_prepare — Prepare a SQL statement for execution
- cubrid_put — Update a column using OID
- cubrid_rollback — Roll back a transaction
- cubrid_schema — Get the requested schema information
- cubrid_seq_drop — Delete an element from sequence type column using OID
- cubrid_seq_insert — Insert an element to a sequence type column using OID
- cubrid_seq_put — Update the element value of sequence type column using OID
- cubrid_set_add — Insert a single element to set type column using OID
- cubrid_set_autocommit — Set autocommit mode of the connection
- cubrid_set_db_parameter — Sets the CUBRID database parameters
- cubrid_set_drop — Delete an element from set type column using OID
- cubrid_set_query_timeout — Set the timeout time of query execution
- cubrid_version — Get the CUBRID PHP module's version

# CUBRID MySQL Compatibility Functions

# cubrid_affected_rows

(PECL CUBRID >= 8.3.0)

cubrid_affected_rows — Return the number of rows affected by the last SQL statement

### Description

cubrid_affected_rows(resource `$conn_identifier` = ?): int
cubrid_affected_rows(resource `$req_identifier` = ?): int

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

### Parameters

`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last link opend by cubrid_connect() is assumed.
`req_identifier`
  Request Identifier, could be returned from either cubrid_prepare() or cubrid_execute(). If the request identifier is not specified, the last identifier requested by cubrid_prepare() or cubrid_execute() is assumed.

### Return Values

Number of rows affected by the SQL statement, when process is successful.

-1, when SQL statement is not INSERT, DELETE or UPDATE.

`false`, when the request identifier is not specified, and there is no last request.

### Examples

Example #1 cubrid_affected_rows() example

`<?php
$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
cubrid_execute($conn, "DROP TABLE IF EXISTS cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d varchar)");
$sql_stmt = "INSERT INTO cubrid_test(d) VALUES('php-test')";
$req = cubrid_prepare($conn, $sql_stmt);
for ($i = 0; $i < 10; $i++) {
cubrid_execute($req);
}
cubrid_commit($conn);
$req = cubrid_execute($conn, "DELETE FROM cubrid_test WHERE d='php-test'", CUBRID_ASYNC);
var_dump(cubrid_affected_rows());
var_dump(cubrid_affected_rows($conn));
var_dump(cubrid_affected_rows($req));
cubrid_disconnect($conn);
print "done!";
?>`

The above example will output:

    int(10)
    int(10)
    int(10)
    done!

### See Also

- cubrid_execute() - Execute a prepared SQL statement

# cubrid_client_encoding

(PECL CUBRID >= 8.3.1)

cubrid_client_encoding — Return the current CUBRID connection charset

### Description

cubrid_client_encoding(resource `$conn_identifier` = ?): string

This function returns the current CUBRID connection charset and is similar to the CUBRID function cubrid_get_charset().

### Parameters

`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

### Return Values

A string that represents the CUBRID connection charset; on success.

`false` on failure.

### Examples

Example #1 cubrid_client_encoding() example

`<?php
$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
die('Could not connect.');
}
printf("CUBRID current charset: %s\n", cubrid_client_encoding($con));
?>`

The above example will output:

    CUBRID current charset: iso8859-1

### See Also

- cubrid_get_charset() - Return the current CUBRID connection charset

# cubrid_close

(PECL CUBRID >= 8.3.1)

cubrid_close — Close CUBRID connection

### Description

cubrid_close(resource `$conn_identifier` = ?): bool

The cubrid_close() function ends the transaction currently in process, closes the connection handle and disconnects from server. If there is any request handles not closed yet at this point, they will be closed. It is similar to the CUBRID function cubrid_disconnect().

### Parameters

`conn_identifier`
  The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

`true`, when process is successful.

`false`, when process is unsuccessful.

### Examples

Example #1 cubrid_close() example

`<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_close ($con);
}
?>`

### See Also

- cubrid_disconnect() - Close a database connection
- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

# cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

### Description

cubrid_data_seek(resource `$result`, int `$row_number`): bool

This function performs the moving of the internal row pointer of the CUBRID result (associated with the specified result identifier) to point to a specific row number. There are functions, such as cubrid_fetch_assoc(), which use the currently stored value of row number.

### Parameters

`result`
  The result.
`row_number`
  This is the desired row number of the new result pointer.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 cubrid_data_seek() example

`<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_data_seek($req, 0);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_data_seek($req, 2);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_data_seek($req, 4);
$result = cubrid_fetch_row($req);
var_dump($result);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(2) {
      [0]=>
      string(1) "X"
      [1]=>
      string(5) "Mixed"
    }
    array(2) {
      [0]=>
      string(1) "M"
      [1]=>
      string(3) "Man"
    }
    array(2) {
      [0]=>
      string(1) "S"
      [1]=>
      string(6) "Silver"
    }

# cubrid_db_name

(PECL CUBRID >= 8.3.1)

cubrid_db_name — Get db name from results of cubrid_list_dbs

### Description

cubrid_db_name(array `$result`, int `$index`): string

Retrieve the database name from a call to cubrid_list_dbs().

### Parameters

`result`
  The result pointer from a call to cubrid_list_dbs().
`index`
  The index into the result set.

### Return Values

Returns the database name on success, and `false` on failure. If `false` is returned, use cubrid_error() to determine the nature of the error.

### Examples

Example #1 cubrid_db_name() example

`<?php
error_reporting(E_ALL);
$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$db_list = cubrid_list_dbs($conn);
$i = 0;
$cnt = count($db_list);
while ($i < $cnt) {
echo cubrid_db_name($db_list, $i) . "\n";
$i++;
}
?>`

The above example will output:

    demodb

### See Also

- cubrid_list_dbs() - Return an array with the list of all existing CUBRID databases

# cubrid_errno

(PECL CUBRID >= 8.3.1)

cubrid_errno — Return the numerical value of the error message from previous CUBRID operation

### Description

cubrid_errno(resource `$conn_identifier` = ?): int

Returns the error number from the last CUBRID function.

The cubrid_errno() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

### Parameters

`conn_identifier`
  The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

Returns the error number from the last CUBRID function, or `0` (zero) if no error occurred.

### Examples

Example #1 cubrid_errno() example

`<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
while (list ($id, $name) = cubrid_fetch($req))
echo $id, $name;
} else {
echo "Error Code: ", cubrid_errno($con);
echo "Error Message: ", cubrid_error($con);
}
?>`

The above example will output:

    Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

### See Also

- cubrid_error() - Get the error message
- cubrid_error_code() - Get error code for the most recent function call
- cubrid_error_msg() - Get last error message for the most recent function call

# cubrid_error

(PECL CUBRID >= 8.3.1)

cubrid_error — Get the error message

### Description

cubrid_error(resource `$connection` = ?): string

The cubrid_error() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

### Parameters

`connection`
  The CUBRID connection.

### Return Values

Error message that occurred.

### Examples

Example #1 cubrid_error() example

`<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
while (list ($id, $name) = cubrid_fetch($req))
echo $id, $name;
} else {
echo "Error Code: ", cubrid_errno($con);
echo "Error Message: ", cubrid_error($con);
}
?>`

The above example will output:

    Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

### See Also

- cubrid_errno() - Return the numerical value of the error message from previous CUBRID operation
- cubrid_error_code() - Get error code for the most recent function call
- cubrid_error_msg() - Get last error message for the most recent function call

# cubrid_fetch_array

(PECL CUBRID >=8.3.0)

cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both

### Description

cubrid_fetch_array(resource `$result`, int `$type` = CUBRID_BOTH): array

The cubrid_fetch_array() function is used to get a single row from the query result and returns an array. The cursor automatically moves to the next row after getting the result.

### Parameters

`result`
  `Result` comes from a call to cubrid_execute()
`type`
  Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH. If you need to operate the lob object, you can use CUBRID_LOB.

### Return Values

Returns an array of strings that corresponds to the fetched row, when process is successful.

`false`, when there are no more rows; NULL, when process is unsuccessful.

The type of returned array depends on how type is defined. By using CUBRID_BOTH (default), you'll get an array with both associative and number indices, and you can decide which data type to use by setting the `type` argument. The `type` variable can be set to one of the following values:

- CUBRID_NUM : Numerical array (0-based)
- CUBRID_ASSOC : Associative array
- CUBRID_BOTH : Numerical & Associative array (default)

### Examples

Example #1 cubrid_fetch_array() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_array($req, CUBRID_NUM)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}
// if you want to operate LOB object, you can use cubrid_fetch_array($req, CUBRID_NUM | CUBRID_LOB)
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    name                                     area       seats  address
    Panathinaiko Stadium                     86300.00   50000  Athens, Greece
    Olympic Stadium                          54700.00   13000  Athens, Greece
    Olympic Indoor Hall                      34100.00   18800  Athens, Greece
    Olympic Hall                             52400.00   21000  Athens, Greece
    Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
    Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
    Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
    Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
    Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_fetch() - Fetch the next row from a result set
- cubrid_fetch_row() - Return a numerical array with the values of the current row
- cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
- cubrid_fetch_object() - Fetch the next row and return it as an object

# cubrid_fetch_assoc

(PECL CUBRID >= 8.3.0)

cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row

### Description

cubrid_fetch_assoc(resource `$result`, int `$type` = ?): array

This function returns the associative array, that corresponds to the fetched row, and then moves the internal data pointer ahead, or returns FALSE when the end is reached.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`type`
  Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

### Return Values

Associative array, when process is successful.

`false`, when there are no more rows; NULL, when process is unsuccessful.

### Examples

Example #1 cubrid_fetch_assoc() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_assoc($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}
// if you want to operate LOB object, you can use cubrid_fetch_assoc($req, CUBRID_LOB)
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    name                                     area       seats  address
    Panathinaiko Stadium                     86300.00   50000  Athens, Greece
    Olympic Stadium                          54700.00   13000  Athens, Greece
    Olympic Indoor Hall                      34100.00   18800  Athens, Greece
    Olympic Hall                             52400.00   21000  Athens, Greece
    Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
    Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
    Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
    Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
    Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_fetch() - Fetch the next row from a result set
- cubrid_fetch_row() - Return a numerical array with the values of the current row
- cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- cubrid_fetch_object() - Fetch the next row and return it as an object

# cubrid_fetch_field

(PECL CUBRID >= 8.3.1)

cubrid_fetch_field — Get column information from a result and return as an object

### Description

cubrid_fetch_field(resource `$result`, int `$field_offset` = 0): object

This function returns an object with certain properties of the specific column. The properties of the object are:

`name`
  column name
`table`
  name of the table that the column belongs to
`def`
  default value of the column
`max_length`
  maximum length of the column
`not_null`
  1 if the column cannot be NULL
`primary_key`
  1 if the column is a primary key
`unique_key`
  1 if the column is a unique key
`multiple_key`
  1 if the column is a non-unique key
`numeric`
  1 if the column is numeric
`blob`
  1 if the column is a BLOB
`type`
  the type of the column
`unsigned`
  1 if the column is unsigned
`zerofill`
  1 if the column is zero-filled

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. If the field offset is not specified, the next field (that was not yet retrieved by this function) is retrieved. The `field_offset` starts at 0.

### Return Values

Object with certain properties of the specific column, when process is successful.

`false` on failure.

### Examples

Example #1 cubrid_fetch_field() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");
var_dump(cubrid_fetch_row($req));
cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);
printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "primary key:", $field->primary_key);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %d\n", "blob:", $field->blob);
printf("%-30s %s\n", "type:", $field->type);
printf("%-30s %d\n", "unsigned:", $field->unsigned);
printf("%-30s %d\n", "zerofill:", $field->zerofill);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      [0]=>
      string(5) "20001"
      [1]=>
      string(5) "16681"
      [2]=>
      string(3) "KOR"
      [3]=>
      string(9) "1988-9-30"
    }

    --- Field Properties ---
    name:                          athlete_code
    table:                         game
    default value:                 ""
    max length:                    0
    not null:                      1
    primary key:                   1
    unique key:                    1
    multiple key:                  0
    numeric:                       1
    blob:                          0
    type:                          integer
    unsigned:                      0
    zerofill:                      0

# cubrid_fetch_lengths

(PECL CUBRID >= 8.3.0)

cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row

### Description

cubrid_fetch_lengths(resource `$result`): array

This function returns a numeric array with the lengths of the values of each field from the current row of the result set or it returns FALSE on failure.

> Note: If field data type is BLOB/CLOB, you should get its length by using cubrid_lob_size().

### Parameters

`result`
  `result` comes from a call to cubrid_execute()

### Return Values

A numeric array, when process is successful.

`false` on failure.

### Examples

Example #1 cubrid_fetch_lengths() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$row = cubrid_fetch_row($result);
print_r($row);
$lens = cubrid_fetch_lengths($result);
print_r($lens);
cubrid_disconnect($conn);
?>`

The above example will output:

    Array
    (
        [0] => 2004
        [1] => 20085
        [2] => 15118
        [3] => 30134
        [4] => AUS
        [5] => G
        [6] => 2004-8-20
    )
    Array
    (
        [0] => 4
        [1] => 5
        [2] => 5
        [3] => 5
        [4] => 3
        [5] => 1
        [6] => 10
    )

# cubrid_fetch_object

(PECL CUBRID >= 8.3.0)

cubrid_fetch_object — Fetch the next row and return it as an object

### Description

cubrid_fetch_object(
resource `$result`,
string `$class_name` = ?,
array `$params` = ?,
int `$type` = ?
): object

This function returns an object with the column names of the result set as properties. The values of these properties are extracted from the current row of the result.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`class_name`
  The name of the class to instantiate. If not specified, a stdClass (stdClass is PHP's generic empty class that's used when casting other types to objects) object is returned.
`params`
  An optional array of parameters to pass to the constructor for `class_name` objects.
`type`
  Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

### Return Values

An object, when process is successful.

`false`, when there are no more rows; NULL, when process is unsuccessful.

### Examples

Example #1 cubrid_fetch_object() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$res = cubrid_execute($conn, "SELECT * FROM code");
var_dump(cubrid_fetch_object($res));
// if you want to operate LOB object, you can use cubrid_fetch_object($res, CUBRID_LOB)
class demodb_code {
public $s_name = null;
public $f_name = null;
public function toString() {
var_dump($this);
}
}
var_dump(cubrid_fetch_object($res, "demodb_code"));
// if you want to operate LOB object, you can use cubrid_fetch_object($res, "demodb_code", CUBRID_LOB)
class demodb_code_construct extends demodb_code {
public function __construct($s, $f) {
$this->s_name = $s;
$this->f_name = $f;
}
}
var_dump(cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name')));
// if you want to operate LOB object, you can use cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name'), CUBRID_LOB)
var_dump(cubrid_fetch_object($res));
cubrid_close_request($res);
cubrid_disconnect($conn);
?>`

The above example will output:

    object(stdClass)#1 (2) {
      ["s_name"]=>
      string(1) "X"
      ["f_name"]=>
      string(5) "Mixed"
    }
    object(demodb_code)#1 (2) {
      ["s_name"]=>
      string(1) "W"
      ["f_name"]=>
      string(5) "Woman"
    }
    object(demodb_code_construct)#1 (2) {
      ["s_name"]=>
      string(6) "s_name"
      ["f_name"]=>
      string(6) "f_name"
    }
    object(stdClass)#1 (2) {
      ["s_name"]=>
      string(1) "B"
      ["f_name"]=>
      string(6) "Bronze"
    }

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_fetch() - Fetch the next row from a result set
- cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
- cubrid_fetch_row() - Return a numerical array with the values of the current row

# cubrid_fetch_row

(PECL CUBRID >= 8.3.0)

cubrid_fetch_row — Return a numerical array with the values of the current row

### Description

cubrid_fetch_row(resource `$result`, int `$type` = ?): array

This function returns a numerical array with the values of the current row from the result set, starting from 0, and moves the internal data pointer ahead.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`type`
  Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

### Return Values

A numerical array, when process is successful.

`false`, when there are no more rows; NULL, when process is unsuccessful.

### Examples

Example #1 cubrid_fetch_row() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_row($req)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}
// if you want to operate LOB object, you can use cubrid_fetch_row($req, CUBRID_LOB)
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    name                                     area       seats  address
    Panathinaiko Stadium                     86300.00   50000  Athens, Greece
    Olympic Stadium                          54700.00   13000  Athens, Greece
    Olympic Indoor Hall                      34100.00   18800  Athens, Greece
    Olympic Hall                             52400.00   21000  Athens, Greece
    Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
    Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
    Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
    Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
    Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

### See Also

- cubrid_execute() - Execute a prepared SQL statement
- cubrid_fetch() - Fetch the next row from a result set
- cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
- cubrid_fetch_object() - Fetch the next row and return it as an object

# cubrid_field_flags

(PECL CUBRID >= 8.3.0)

cubrid_field_flags — Return a string with the flags of the given field offset

### Description

cubrid_field_flags(resource `$result`, int `$field_offset`): string

This function returns a string with the flags of the given field offset separated by space. You can split the returned value using explode. The possible flags could be: `not_null`, `primary_key`, `unique_key`, `foreign_key`, `auto_increment`, `shared`, `reverse_index`, `reverse_unique` and `timestamp`.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

A string with flags, when process is successful.

`false` when invalid field_offset value.

-1 if SQL sentence is not SELECT.

### Examples

Example #1 cubrid_field_flags() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$col_num = cubrid_num_cols($result);
printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Field Name                     Field Flags
    host_year                      not_null primary_key unique_key
    event_code                     not_null primary_key unique_key foreign_key
    athlete_code                   not_null primary_key unique_key foreign_key
    stadium_code                   not_null
    nation_code
    medal
    game_date

# cubrid_field_len

(PECL CUBRID >= 8.3.0)

cubrid_field_len — Get the maximum length of the specified field

### Description

cubrid_field_len(resource `$result`, int `$field_offset`): int

This function returns the maximum length of the specified field on success, or it returns FALSE on failure.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Maximum length, when process is successful.

`false` on failure.

### Examples

Example #1 cubrid_field_len() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);
printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Column Names                   Column Types                   Column Maxlen
    host_year                      integer                        11
    event_code                     integer                        11
    athlete_code                   integer                        11
    stadium_code                   integer                        11
    nation_code                    char                           3
    medal                          char                           1
    game_date                      date                           10

# cubrid_field_name

(PECL CUBRID >= 8.3.0)

cubrid_field_name — Return the name of the specified field index

### Description

cubrid_field_name(resource `$result`, int `$field_offset`): string

This function returns the name of the specified field index on success or it returns FALSE on failure.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Name of specified field index, on success.

`false` on failure.

### Examples

Example #1 cubrid_field_name() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");
$col_num = cubrid_num_cols($result);
printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Field Name                     Field Flags
    host_year                      not_null primary_key unique_key
    event_code                     not_null primary_key unique_key foreign_key
    athlete_code                   not_null primary_key unique_key foreign_key
    stadium_code                   not_null
    nation_code
    medal
    game_date

# cubrid_field_seek

(PECL CUBRID >= 8.3.0)

cubrid_field_seek — Move the result set cursor to the specified field offset

### Description

cubrid_field_seek(resource `$result`, int `$field_offset` = 0): bool

This function moves the result set cursor to the specified field offset. This offset is used by cubrid_fetch_field() if it doesn't include a field offset. It returns TRUE on success or FALSE on failure.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

`true` on success.

`false` on failure.

### Examples

Example #1 cubrid_field_seek() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");
var_dump(cubrid_fetch_row($req));
cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);
printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(4) {
      [0]=>
      string(5) "20001"
      [1]=>
      string(5) "16132"
      [2]=>
      string(3) "KOR"
      [3]=>
      string(9) "1988-09-30"
    }

    --- Field Properties ---
    name:                          athlete_code
    table:                         game
    default value:                 ""
    max length:                    0
    not null:                      1
    unique key:                    1
    multiple key:                  0
    numeric:                       1
    type:                          integer

# cubrid_field_table

(PECL CUBRID >= 8.3.0)

cubrid_field_table — Return the name of the table of the specified field

### Description

cubrid_field_table(resource `$result`, int `$field_offset`): string

This function returns the name of the table of the specified field. This is useful when using large select queries with JOINS.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Name of the table of the specified field, on success.

`false` when invalid field_offset value.

-1 if SQL sentence is not SELECT.

### Examples

Example #1 cubrid_field_table() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");
$col_num = cubrid_num_cols($result);
printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
printf("%-15s %-15s %s\n",
cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Field Table     Field Name      Field Type
    code            s_name          char
    code            f_name          varchar

# cubrid_field_type

(PECL CUBRID >= 8.3.0)

cubrid_field_type — Return the type of the column corresponding to the given field offset

### Description

cubrid_field_type(resource `$result`, int `$field_offset`): string

This function returns the type of the column corresponding to the given field offset. The returned field type could be one of the following: "int", "real", "string", etc.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`field_offset`
  The numerical field offset. The `field_offset` starts at 0. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Type of the column, on success.

`false` when invalid field_offset value.

-1 if SQL sentence is not SELECT.

### Examples

Example #1 cubrid_field_type() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");
$col_num = cubrid_num_cols($result);
printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
printf("%-15s %-15s %s\n",
cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}
cubrid_disconnect($conn);
?>`

The above example will output:

    Field Table     Field Name      Field Type
    code            s_name          char
    code            f_name          varchar

# cubrid_list_dbs

(PECL CUBRID >= 8.3.0)

cubrid_list_dbs — Return an array with the list of all existing CUBRID databases

### Description

cubrid_list_dbs(resource `$conn_identifier` = ?): array

This function returns an array with the list of all existing Cubrid databases.

### Parameters

`conn_identifier`
  The CUBRID connection.

### Return Values

An numeric array with all existing Cubrid databases; on success.

`false` on failure.

### Examples

Example #1 cubrid_list_dbs() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$db_list = cubrid_list_dbs($conn);
var_dump($db_list);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(1) {
      [0]=>
      string(6) "demodb"
    }

# cubrid_num_fields

(PECL CUBRID >= 8.3.0)

cubrid_num_fields — Return the number of columns in the result set

### Description

cubrid_num_fields(resource `$result`): int

This function returns the number of columns in the result set, on success, or it returns FALSE on failure.

### Parameters

`result`
  `result` comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

### Return Values

Number of columns, on success.

-1 if SQL sentence is not SELECT.

`false` when process is unsuccessful.

### Examples

Example #1 cubrid_num_fields() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM code");
$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_fields($req);
printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);
cubrid_disconnect($conn);
?>`

The above example will output:

    Row Num: 6
    Column Num: 2

# cubrid_ping

(PECL CUBRID >= 8.3.1)

cubrid_ping — Ping a server connection or reconnect if there is no connection

### Description

cubrid_ping(resource `$conn_identifier` = ?): bool

Checks whether or not the connection to the server is working.

### Parameters

`conn_identifier`
  The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

Returns `true` if the connection to the server CUBRID server is working, otherwise `false`.

### Examples

Example #1 cubrid_ping() example

`<?php
set_time_limit(0);
$conn = cubrid_connect('localhost', 33000, 'demodb');
/* Assuming this query will take a long time */
$sql = "select * from athlete";
$result = cubrid_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!cubrid_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
cubrid_free_result($result);
/* So the connection is still alive, let's run another query */
$sql2 = "select * from code";
$result2 = cubrid_query($sql2);
?>`

# cubrid_query

(PECL CUBRID >= 8.3.1)

cubrid_query — Send a CUBRID query

### Description

cubrid_query(string `$query`, resource `$conn_identifier` = ?): resource

cubrid_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified `conn_identifier`.

### Parameters

`query`
  An SQL query Data inside the query should be properly escaped.
`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, cubrid_query() returns a resource on success, or `false` on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, cubrid_query() returns `true` on success or `false` on error.

The returned result resource should be passed to cubrid_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use cubrid_num_rows() to find out how many rows were returned for a SELECT statement or cubrid_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

cubrid_query() will also fail and return `false` if the user does not have permission to access the table(s) referenced by the query.

### Examples

Example #1 Invalid Query

The following query is syntactically invalid, so cubrid_query() fails and returns `false`.

`<?php
$conn = cubrid_connect('localhost', 33000, 'demodb');
$result = cubrid_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . cubrid_error());
}
?>`

Example #2 Valid Query

The following query is valid, so cubrid_query() returns a resource.

`<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
$conn = cubrid_connect('localhost', 33000, 'demodb');
cubrid_execute($conn,"DROP TABLE if exists friends");
cubrid_execute($conn,"create table friends(firstname varchar,lastname varchar,address char(24),age int)");
cubrid_execute($conn,"insert into friends values('fred','fox','home-1','20')");
cubrid_execute($conn,"insert into friends values('blue','cat','home-2','21')");
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see cubrid_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
cubrid_real_escape_string($firstname),
cubrid_real_escape_string($lastname));
// Perform Query
$result = cubrid_query($query);
// Check result
// This shows the actual query sent to CUBRID, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . cubrid_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the cubrid result functions must be used
// See also cubrid_result(), cubrid_fetch_array(), cubrid_fetch_row(), etc.
while ($row = cubrid_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
cubrid_free_result($result);
?>`

### See Also

- cubrid_connect() - Open a connection to a CUBRID Server
- cubrid_error() - Get the error message
- cubrid_real_escape_string() - Escape special characters in a string for use in an SQL statement
- cubrid_result() - Return the value of a specific field in a specific row
- cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
- cubrid_unbuffered_query() - Perform a query without fetching the results into memory

# cubrid_real_escape_string

(PECL CUBRID >= 8.3.0)

cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement

### Description

cubrid_real_escape_string(string `$unescaped_string`, resource `$conn_identifier` = ?): string

This function returns the escaped string version of the given string. It will escape the following characters: `'`. In general, single quotations are used to enclose character string. Double quotations may be used as well depending on the value of ansi_quotes, which is a parameter related to SQL statement. If the ansi_quotes value is set to no, character string enclosed by double quotations is handled as character string, not as an identifier. The default value is yes. If you want to include a single quote as part of a character string, enter two single quotes in a row.

### Parameters

`unescaped_string`
  The string that is to be escaped.
`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

Escaped string version of the given string, on success.

`false` on failure.

### Examples

Example #1 cubrid_real_escape_string() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$unescaped_str = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$escaped_str = cubrid_real_escape_string($unescaped_str);
$len = strlen($unescaped_str);
@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t char($len))");
cubrid_execute($conn, "INSERT INTO cubrid_test (t) VALUES('$escaped_str')");
$req = cubrid_execute($conn, "SELECT * FROM cubrid_test");
$row = cubrid_fetch_assoc($req);
var_dump($row);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    array(1) {
      ["t"]=>
      string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
    }

# cubrid_result

(PECL CUBRID >= 8.3.0)

cubrid_result — Return the value of a specific field in a specific row

### Description

cubrid_result(resource `$result`, int `$row`, mixed `$field` = 0): string

This function returns the value of a specific field in a specific row from a result set.

### Parameters

`result`
  `result` comes from a call to cubrid_execute()
`row`
  The row number from the result that is being retrieved. Row numbers start at 0.
`field`
  The name or offset of the `field` being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

### Return Values

Value of a specific field, on success (NULL if value if null).

`false` on failure.

### Examples

Example #1 cubrid_result() example

`<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM code");
$result = cubrid_result($req, 0);
var_dump($result);
$result = cubrid_result($req, 0, 1);
var_dump($result);
$result = cubrid_result($req, 5, "f_name");
var_dump($result);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>`

The above example will output:

    string(1) "X"
    string(5) "Mixed"
    string(4) "Gold"

# cubrid_unbuffered_query

(PECL CUBRID >= 8.3.0)

cubrid_unbuffered_query — Perform a query without fetching the results into memory

### Description

cubrid_unbuffered_query(string `$query`, resource `$conn_identifier` = ?): resource

This function performs a query without waiting for that all query results have been complete. It will return when the results are being generated.

### Parameters

`query`
  A SQL query.
`conn_identifier`
  The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

### Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a request identifier resource on success.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns `true` on success.

`false` on failure.

### Examples

Example #1 cubrid_unbuffered_query() example

`<?php
$link = cubrid_connect("localhost", 30000, "demodb", "dba", "");
if (!$link)
{
die('Could not connect.');
}
$query = "select * from code";
$result = cubrid_unbuffered_query($query, $link);
while ($row = cubrid_fetch($result))
{
var_dump($row);
}
cubrid_close_request($result);
cubrid_disconnect($link);
?>`

### Notes

> Note: The benefits of cubrid_unbuffered_query() come at a cost: you cannot use cubrid_num_rows() and cubrid_data_seek() on a result set returned from cubrid_unbuffered_query().

## Table of Contents

- cubrid_affected_rows — Return the number of rows affected by the last SQL statement
- cubrid_client_encoding — Return the current CUBRID connection charset
- cubrid_close — Close CUBRID connection
- cubrid_data_seek — Move the internal row pointer of the CUBRID result
- cubrid_db_name — Get db name from results of cubrid_list_dbs
- cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
- cubrid_error — Get the error message
- cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
- cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
- cubrid_fetch_field — Get column information from a result and return as an object
- cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
- cubrid_fetch_object — Fetch the next row and return it as an object
- cubrid_fetch_row — Return a numerical array with the values of the current row
- cubrid_field_flags — Return a string with the flags of the given field offset
- cubrid_field_len — Get the maximum length of the specified field
- cubrid_field_name — Return the name of the specified field index
- cubrid_field_seek — Move the result set cursor to the specified field offset
- cubrid_field_table — Return the name of the table of the specified field
- cubrid_field_type — Return the type of the column corresponding to the given field offset
- cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
- cubrid_num_fields — Return the number of columns in the result set
- cubrid_ping — Ping a server connection or reconnect if there is no connection
- cubrid_query — Send a CUBRID query
- cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
- cubrid_result — Return the value of a specific field in a specific row
- cubrid_unbuffered_query — Perform a query without fetching the results into memory

# CUBRID Obsolete Aliases and Functions

# cubrid_load_from_glo

(PECL CUBRID >= 8.3.0)

cubrid_load_from_glo — Read data from a GLO instance and save it in a file

### Description

cubrid_load_from_glo(resource `$conn_identifier`, string `$oid`, string `$file_name`): int

The cubrid_load_from_glo() function is used to read a data from a glo instance, and saves it in a designated file.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  Oid of the glo instance that you want to read the data from.
`file_name`
  Name of the file where you want to save the data in.

### Return Values

`true`, when process is successful.

`false`, when process is unsuccessful.

### Examples

Example #1 cubrid_load_from_glo() example

`<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
$res = cubrid_load_from_glo ($con, $oid, "output.jpg");
if ($res) {
echo "image changed successfully";
}
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: cubrid_load_from_glo()

> Note: This function is removed from CUBRID 3.1.

### See Also

- cubrid_new_glo() - Create a glo instance
- cubrid_save_to_glo() - Save requested file in a GLO instance
- cubrid_send_glo() - Read data from glo and send it to std output

# cubrid_new_glo

(PECL CUBRID >= 8.3.0)

cubrid_new_glo — Create a glo instance

### Description

cubrid_new_glo(resource `$conn_identifier`, string `$class_name`, string `$file_name`): string

The cubrid_new_glo() function is used to create a glo instance in the requested class (glo class). The glo created is a LO type, and is stored in the `file_name` file.

### Parameters

`conn_identifier`
  Connection identifier.
`class_name`
  Name of the class that you want to create a glo in.
`file_name`
  The file name that you want to save in the newly created glo.

### Return Values

Oid of the instance created, when process is successful.

`false`, when process is unsuccessful.

### Examples

Example #1 cubrid_new_glo() example

`<?php
$oid = cubrid_new_glo ($con, "glo", "input.jpg");
if ($oid){
// the type of column "image" is "object"
$req = cubrid_execute ($con, "insert into person(image) values($oid)");
if ($req) {
echo "image inserted successfully";
cubrid_close_request ($req);
cubrid_commit($con);
}
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: cubrid_new_glo()

> Note: This function is removed from CUBRID 3.1.

### See Also

- cubrid_save_to_glo() - Save requested file in a GLO instance
- cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
- cubrid_send_glo() - Read data from glo and send it to std output

# cubrid_save_to_glo

(PECL CUBRID >= 8.3.0)

cubrid_save_to_glo — Save requested file in a GLO instance

### Description

cubrid_save_to_glo(resource `$conn_identifier`, string `$oid`, string `$file_name`): int

The cubrid_save_to_glo() function is used to save requested file in a glo instance.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  Oid of the glo instance that you want to save a file in.
`file_name`
  The name of the file that you want to save.

### Return Values

`true`, when process is successful.

`false`, when process is unsuccessful.

### Examples

Example #1 cubrid_save_to_glo() example

`<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
$res = cubrid_save_to_glo ($con, $oid, "input.jpg");
if ($res) {
echo "image changed successfully";
}
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: cubrid_save_to_glo()

> Note: This function is removed from CUBRID 3.1.

### See Also

- cubrid_new_glo() - Create a glo instance
- cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
- cubrid_send_glo() - Read data from glo and send it to std output

# cubrid_send_glo

(PECL CUBRID >= 8.3.0)

cubrid_send_glo — Read data from glo and send it to std output

### Description

cubrid_send_glo(resource `$conn_identifier`, string `$oid`): int

The cubrid_send_glo() function is used to read data from glo instance and sends it to the PHP standard output.

### Parameters

`conn_identifier`
  Connection identifier.
`oid`
  Oid of the glo instance that you want to read data from.

### Return Values

`true`, when process is successful.

`false`, when process is unsuccessful.

### Examples

Example #1 cubrid_send_glo() example

`<?php
$req = cubrid_execute ($con, "select image from person where id =1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
Header ("Content-type: image/jpeg");
cubrid_send_glo ($con, $oid);
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: cubrid_send_glo()

> Note: This function is removed from CUBRID 3.1.

### See Also

- cubrid_new_glo() - Create a glo instance
- cubrid_save_to_glo() - Save requested file in a GLO instance
- cubrid_load_from_glo() - Read data from a GLO instance and save it in a file

## Table of Contents

- cubrid_load_from_glo — Read data from a GLO instance and save it in a file
- cubrid_new_glo — Create a glo instance
- cubrid_save_to_glo — Save requested file in a GLO instance
- cubrid_send_glo — Read data from glo and send it to std output

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
- CUBRID Functions
  - cubrid_bind — Bind variables to a prepared statement as parameters
  - cubrid_close_prepare — Close the request handle
  - cubrid_close_request — Close the request handle
  - cubrid_col_get — Get contents of collection type column using OID
  - cubrid_col_size — Get the number of elements in collection type column using OID
  - cubrid_column_names — Get the column names in result
  - cubrid_column_types — Get column types in result
  - cubrid_commit — Commit a transaction
  - cubrid_connect — Open a connection to a CUBRID Server
  - cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
  - cubrid_current_oid — Get OID of the current cursor location
  - cubrid_disconnect — Close a database connection
  - cubrid_drop — Delete an instance using OID
  - cubrid_error_code — Get error code for the most recent function call
  - cubrid_error_code_facility — Get the facility code of error
  - cubrid_error_msg — Get last error message for the most recent function call
  - cubrid_execute — Execute a prepared SQL statement
  - cubrid_fetch — Fetch the next row from a result set
  - cubrid_free_result — Free the memory occupied by the result data
  - cubrid_get — Get a column using OID
  - cubrid_get_autocommit — Get auto-commit mode of the connection
  - cubrid_get_charset — Return the current CUBRID connection charset
  - cubrid_get_class_name — Get the class name using OID
  - cubrid_get_client_info — Return the client library version
  - cubrid_get_db_parameter — Returns the CUBRID database parameters
  - cubrid_get_query_timeout — Get the query timeout value of the request
  - cubrid_get_server_info — Return the CUBRID server version
  - cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
  - cubrid_is_instance — Check whether the instance pointed by OID exists
  - cubrid_lob_close — Close BLOB/CLOB data
  - cubrid_lob_export — Export BLOB/CLOB data to file
  - cubrid_lob_get — Get BLOB/CLOB data
  - cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
  - cubrid_lob_size — Get BLOB/CLOB data size
  - cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters
  - cubrid_lob2_close — Close LOB object
  - cubrid_lob2_export — Export the lob object to a file
  - cubrid_lob2_import — Import BLOB/CLOB data from a file
  - cubrid_lob2_new — Create a lob object
  - cubrid_lob2_read — Read from BLOB/CLOB data
  - cubrid_lob2_seek — Move the cursor of a lob object
  - cubrid_lob2_seek64 — Move the cursor of a lob object
  - cubrid_lob2_size — Get a lob object's size
  - cubrid_lob2_size64 — Get a lob object's size
  - cubrid_lob2_tell — Tell the cursor position of the LOB object
  - cubrid_lob2_tell64 — Tell the cursor position of the LOB object
  - cubrid_lob2_write — Write to a lob object
  - cubrid_lock_read — Set a read lock on the given OID
  - cubrid_lock_write — Set a write lock on the given OID
  - cubrid_move_cursor — Move the cursor in the result
  - cubrid_next_result — Get result of next query when executing multiple SQL statements
  - cubrid_num_cols — Return the number of columns in the result set
  - cubrid_num_rows — Get the number of rows in the result set
  - cubrid_pconnect — Open a persistent connection to a CUBRID server
  - cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
  - cubrid_prepare — Prepare a SQL statement for execution
  - cubrid_put — Update a column using OID
  - cubrid_rollback — Roll back a transaction
  - cubrid_schema — Get the requested schema information
  - cubrid_seq_drop — Delete an element from sequence type column using OID
  - cubrid_seq_insert — Insert an element to a sequence type column using OID
  - cubrid_seq_put — Update the element value of sequence type column using OID
  - cubrid_set_add — Insert a single element to set type column using OID
  - cubrid_set_autocommit — Set autocommit mode of the connection
  - cubrid_set_db_parameter — Sets the CUBRID database parameters
  - cubrid_set_drop — Delete an element from set type column using OID
  - cubrid_set_query_timeout — Set the timeout time of query execution
  - cubrid_version — Get the CUBRID PHP module's version
- CUBRID MySQL Compatibility Functions
  - cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  - cubrid_client_encoding — Return the current CUBRID connection charset
  - cubrid_close — Close CUBRID connection
  - cubrid_data_seek — Move the internal row pointer of the CUBRID result
  - cubrid_db_name — Get db name from results of cubrid_list_dbs
  - cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
  - cubrid_error — Get the error message
  - cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  - cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
  - cubrid_fetch_field — Get column information from a result and return as an object
  - cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
  - cubrid_fetch_object — Fetch the next row and return it as an object
  - cubrid_fetch_row — Return a numerical array with the values of the current row
  - cubrid_field_flags — Return a string with the flags of the given field offset
  - cubrid_field_len — Get the maximum length of the specified field
  - cubrid_field_name — Return the name of the specified field index
  - cubrid_field_seek — Move the result set cursor to the specified field offset
  - cubrid_field_table — Return the name of the table of the specified field
  - cubrid_field_type — Return the type of the column corresponding to the given field offset
  - cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
  - cubrid_num_fields — Return the number of columns in the result set
  - cubrid_ping — Ping a server connection or reconnect if there is no connection
  - cubrid_query — Send a CUBRID query
  - cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
  - cubrid_result — Return the value of a specific field in a specific row
  - cubrid_unbuffered_query — Perform a query without fetching the results into memory
- CUBRID Obsolete Aliases and Functions
  - cubrid_load_from_glo — Read data from a GLO instance and save it in a file
  - cubrid_new_glo — Create a glo instance
  - cubrid_save_to_glo — Save requested file in a GLO instance
  - cubrid_send_glo — Read data from glo and send it to std output

# dBase

# Introduction

> Note:

> This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

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

Warning

We recommend against using dBase files as your production database. Use » SQLite or choose any real SQL server instead; » MySQL or » Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

Caution

As of dbase 7.0.0 the databases are automatically locked via flock(). There has been no support for locking earlier, so two concurrent web server processes modifying the same dBase file would have very likely ruined your database. This can happen even with dbase 7.0.0+ on systems which implement the locks at the process level with multithreaded SAPIs.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and deleted records are kept until you call dbase_pack().

Only dbf file levels 3 (dBASE III+) - 5 (dBASE V) are supported. The types of dBase fields available are:

Available types of fields
Field | dBase Type | Format | Additional information
--- | --- | --- | ---
`M` | Memo | n/a | This type is not supported by PHP, such field will be ignored
`D` | Date | `YYYYMMDD` | The field length is limited to 8
`T` | DateTime | `YYYYMMDDhhmmss.uuu` | (FoxPro) No validity checks are done. Available as of dbase 7.0.0.
`N` | Number | A number | You must declare a length and a precision (the number of digits after the decimal point).
`F` | Float | A float number | Same as `N`.
`C` | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length. Overlong strings will be silently truncated when storing data.
`L` | Boolean | `T` or `Y` for `true`, `F` or `N` for `false`, `?` for uninitialized. | As of dbase 7.0.0, returned as a bool (`true` or `false`), or `null` for uninitialized fields. Formerly, returned as an int (`1` or `0`).

> Note:

> As of dbase 7.0.0 nullable fields are supported for `DBASE_TYPE_FOXPRO` databases. If a field is nullable, passing `null` will set the respective flag, and on later retrieval the field value will be `null`.

> Note:

> There is no support for indexes or memo fields.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

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: » https://pecl.php.net/package/dbase.

## Resource Types

As of dbase 7.0.0, the resource type `dbase` is defined, which is returned by dbase_open() and dbase_create().

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

`DBASE_VERSION` (string)
  The extension version. (Available as of dbase 7.0.0)
`DBASE_RDONLY` (int)
  Open database for reading only. Used with dbase_open(). (Available as of dbase 7.0.0)
`DBASE_RDWR` (int)
  Open database for reading and writing. Used with dbase_open(). (Available as of dbase 7.0.0)
`DBASE_TYPE_DBASE` (int)
  Create dBASE style database. Used with dbase_create(). (Available as of dbase 7.0.0)
`DBASE_TYPE_FOXPRO` (int)
  Create FoxPro style database. Used with dbase_create(). (Available as of dbase 7.0.0)

# dBase Functions

## Examples

Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().

# dbase_add_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_add_record — Adds a record to a database

### Description

dbase_add_record(resource `$database`, array `$data`): bool

Adds the given data to the database.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

`data`

  An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

  > Note:

  > If you're using dbase_get_record() return value for this parameter, remember to reset the key named `deleted`.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Inserting a record in a dBase database

`<?php
// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);
if ($db) {
dbase_add_record($db, array(
date('Ymd'),
'Maxim Topolov',
'23',
'max@example.com',
'T'));
dbase_close($db);
}
?>`

### See Also

- dbase_delete_record() - Deletes a record from a database
- dbase_replace_record() - Replaces a record in a database

# dbase_close

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_close — Closes a database

### Description

dbase_close(resource `$database`): bool

Closes the given database resource.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Closing a dBase database file

`<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);
if ($db) {
// read some data ..
dbase_close($db);
}
?>`

### See Also

- dbase_open() - Opens a database
- dbase_create() - Creates a database

# dbase_create

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_create — Creates a database

### Description

dbase_create(string `$path`, array `$fields`, int `$type` = DBASE_TYPE_DBASE): resource

dbase_create() creates a dBase database with the given definition. If the file already exists, it is not truncated. dbase_pack() can be called to force truncation.

> Note:

> This function is affected by open_basedir.

### Parameters

`path`

  The path of the database. It can be a relative or absolute path to the file where dBase will store your data.

`fields`

  An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, a precision and a nullable flag. The supported field types are listed in the introduction section.

  > Note:

  > The fieldnames are limited in length and must not exceed 10 chars.

`type`

  The type of database to be created. Either `DBASE_TYPE_DBASE` or `DBASE_TYPE_FOXPRO`.

### Return Values

Returns a database resource if the database is successfully created, or `false` if an error occurred.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | The `type` parameter has been added.
PECL dbase 7.0.0 | The return value is now a resource instead of an int.

### Examples

Example #1 Creating a dBase database file

`<?php
// database "definition"
$def = array(
array("date", "D"),
array("name", "C", 50),
array("age", "N", 3, 0),
array("email", "C", 128),
array("ismember", "L")
);
// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
echo "Error, can't create the database\n";
}
?>`

### See Also

- dbase_open() - Opens a database
- dbase_close() - Closes a database

# dbase_delete_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_delete_record — Deletes a record from a database

### Description

dbase_delete_record(resource `$database`, int `$number`): bool

Marks the given record to be deleted from the database.

> Note:

> To actually remove the record from the database, you must also call dbase_pack().

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

`number`

  An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### See Also

- dbase_add_record() - Adds a record to a database
- dbase_replace_record() - Replaces a record in a database

# dbase_get_header_info

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_header_info — Gets the header info of a database

### Description

dbase_get_header_info(resource `$database`): array

Returns information on the column structure of the given database resource.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

### Return Values

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name
  The name of the column
type
  The human-readable name for the dbase type of the column (i.e. date, boolean, etc.) The supported field types are listed in the introduction section.
length
  The number of bytes this column can hold
precision
  The number of digits of decimal precision for the column
format
  A suggested printf() format specifier for the column
offset
  The byte offset of the column from the start of the row

If the database header information cannot be read, `false` is returned.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Showing header information for a dBase database file

`<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
// Display information
print_r($column_info);
?>`

# dbase_get_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record — Gets a record from a database as an indexed array

### Description

dbase_get_record(resource `$database`, int `$number`): array

Gets a record from a database as an indexed array.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

`number`

  The index of the record between `1` and `dbase_numrecords($dbase_identifier)`.

### Return Values

An indexed array with the record. This array will also include an associative key named `deleted` which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

- Dates are left as strings.
- DateTime values are converted to strings.
- Integers outside the range `PHP_INT_MIN`..`PHP_INT_MAX` are returned as strings.
- Before dbase 7.0.0, booleans (`L`) were converted to `1` or `0`.

On error, dbase_get_record() will return `false`.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### See Also

- dbase_get_record_with_names() - Gets a record from a database as an associative array

# dbase_get_record_with_names

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record_with_names — Gets a record from a database as an associative array

### Description

dbase_get_record_with_names(resource `$database`, int `$number`): array

Gets a record from a dBase database as an associative array.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

`number`

  The index of the record between `1` and `dbase_numrecords($dbase_identifier)`.

### Return Values

An associative array with the record. This will also include a key named `deleted` which is set to 1 if the record has been marked for deletion (see dbase_delete_record()). Therefore it is not possible to retrieve the value of a field named `deleted` with this function.

Each field is converted to the appropriate PHP type, except:

- Dates are left as strings.
- DateTime values are converted to strings.
- Integers outside the range `PHP_INT_MIN`..`PHP_INT_MAX` are returned as strings.
- Before dbase 7.0.0, booleans (`L`) were converted to `1` or `0`.

On error, dbase_get_record_with_names() will return `false`.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Listing all the registered members in the database

`<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);
if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
$row = dbase_get_record_with_names($db, $i);
if ($row['ismember'] == 1) {
echo "Member #$i: " . trim($row['name']) . "\n";
}
}
}
?>`

### See Also

- dbase_get_record() - Gets a record from a database as an indexed array

# dbase_numfields

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numfields — Gets the number of fields of a database

### Description

dbase_numfields(resource `$database`): int

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

> Note:

> Field numbers are between 0 and `dbase_numfields($db)-1`, while record numbers are between 1 and `dbase_numrecords($db)`.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

### Return Values

The number of fields in the database, or `false` if an error occurs.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 dbase_numfields() Example

`<?php
$rec = dbase_get_record($db, $recno);
$nf = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
echo $rec[$i], "\n";
}
?>`

### See Also

- dbase_numrecords() - Gets the number of records in a database

# dbase_numrecords

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numrecords — Gets the number of records in a database

### Description

dbase_numrecords(resource `$database`): int

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

> Note:

> Records which are marked as deleted are counted as well.

> Note:

> Record numbers are between 1 and `dbase_numrecords($db)`, while field numbers are between 0 and `dbase_numfields($db)-1`.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

### Return Values

The number of records in the database, or `false` if an error occurs.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Looping over all the records of the database

`<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);
if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
$record = dbase_get_record($db, $i);
if (!$record['deleted']) {
// do something with the $record
} else {
// do something with the deleted $record or ignore it
}
}
}
?>`

### See Also

- dbase_numfields() - Gets the number of fields of a database

# dbase_open

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_open — Opens a database

### Description

dbase_open(string `$path`, int `$mode`): resource|false

dbase_open() opens a dBase database with the given access mode.

> Note:

> This function is affected by open_basedir.

### Parameters

`path`

  The path of the database. It can be a relative or absolute path to the file where dBase will store your data.

`mode`

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

  > Note:

  > You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as `mode`.

  As of dbase 7.0.0 you can use `DBASE_RDONLY` and `DBASE_RDWR`, respectively, to specify the `mode`.

### Return Values

Returns a database resource on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | The return value is now a resource instead of an int.

### Examples

Example #1 Opening a dBase database file

`<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);
if ($db) {
// read some data ..
dbase_close($db);
}
?>`

### See Also

- dbase_create() - Creates a database
- dbase_close() - Closes a database

# dbase_pack

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_pack — Packs a database

### Description

dbase_pack(resource `$database`): bool

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record(). Note that the file will be truncated after successful packing (contrary to dBASE III's PACK command).

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Emptying a dBase database

`<?php
// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);
if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
dbase_delete_record($db, $i);
}
// expunge the database
dbase_pack($db);
}
?>`

### See Also

- dbase_delete_record() - Deletes a record from a database

# dbase_replace_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_replace_record — Replaces a record in a database

### Description

dbase_replace_record(resource `$database`, array `$data`, int `$number`): bool

Replaces the given record in the database with the given data.

### Parameters

`database`

  The database resource, returned by dbase_open() or dbase_create().

`data`

  An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_replace_record() will fail.

  > Note:

  > If you're using dbase_get_record() return value for this parameter, remember to reset the key named `deleted`.

`number`

  An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL dbase 7.0.0 | `database` is now a resource instead of an int.

### Examples

Example #1 Updating a record in the database

`<?php
// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);
if ($db) {
// gets the old row
$row = dbase_get_record_with_names($db, 1);
// remove the 'deleted' entry
unset($row['deleted']);
// Update the date field with the current timestamp
$row['date'] = date('Ymd');
// convert the row to an indexed array
$row = array_values($row);
// Replace the record
dbase_replace_record($db, $row, 1);
dbase_close($db);
}
?>`

### Notes

> Note:

> Boolean fields result in an int element value (`0` or `1`) when retrieved via dbase_get_record() or dbase_get_record_with_names(). If they are written back, this results in the value becoming `0`, so care has to be taken to properly adjust the values.

### See Also

- dbase_add_record() - Adds a record to a database
- dbase_delete_record() - Deletes a record from a database

## Table of Contents

- dbase_add_record — Adds a record to a database
- dbase_close — Closes a database
- dbase_create — Creates a database
- dbase_delete_record — Deletes a record from a database
- dbase_get_header_info — Gets the header info of a database
- dbase_get_record — Gets a record from a database as an indexed array
- dbase_get_record_with_names — Gets a record from a database as an associative array
- dbase_numfields — Gets the number of fields of a database
- dbase_numrecords — Gets the number of records in a database
- dbase_open — Opens a database
- dbase_pack — Packs a database
- dbase_replace_record — Replaces a record in a database

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- dBase Functions
  - dbase_add_record — Adds a record to a database
  - dbase_close — Closes a database
  - dbase_create — Creates a database
  - dbase_delete_record — Deletes a record from a database
  - dbase_get_header_info — Gets the header info of a database
  - dbase_get_record — Gets a record from a database as an indexed array
  - dbase_get_record_with_names — Gets a record from a database as an associative array
  - dbase_numfields — Gets the number of fields of a database
  - dbase_numrecords — Gets the number of records in a database
  - dbase_open — Opens a database
  - dbase_pack — Packs a database
  - dbase_replace_record — Replaces a record in a database

# Firebird/InterBase

# Introduction

Warning

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL GIT here: » https://github.com/php/pecl-database-interbase.

Firebird is a relational database offering many ISO SQL-2003 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Embarcadero/Inprise. More information about InterBase is available at » http://www.embarcadero.com/products/interbase.

Firebird is a commercially independent project (fundation) of C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Embarcadero) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

> Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.4.0 This extension supports InterBase versions 6 and up and Firebird version 2.0 and up.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.4.0

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: » https://github.com/FirebirdSQL/php-firebird.

To enable Firebird/InterBase support configure PHP --with-interbase[=DIR], where DIR is the Firebird/InterBase base install directory, which defaults to /usr.

> Note: Note to Win32/Win64 Users
> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: fbclient.dll,gds32.dll

> If you installed the Firebird/InterBase database server on the same machine PHP is running on, you will have this DLL already and fbclient.dll,gds32.dll (gds32.dll is generated from the installer for legacy applications) will already be in the PATH.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

InterBase configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
ibase.allow_persistent | "1" | `INI_SYSTEM` |
ibase.max_persistent | "-1" | `INI_SYSTEM` |
ibase.max_links | "-1" | `INI_SYSTEM` |
ibase.default_db | NULL | `INI_SYSTEM` |
ibase.default_user | NULL | `INI_ALL` |
ibase.default_password | NULL | `INI_ALL` |
ibase.default_charset | NULL | `INI_ALL` |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | `INI_ALL` |
ibase.dateformat | "%Y-%m-%d" | `INI_ALL` |
ibase.timeformat | "%H:%M:%S" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`ibase.allow_persistent` bool
  Whether to allow persistent connections to Firebird/InterBase.
`ibase.max_persistent` int
  The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.
`ibase.max_links` int
  The maximum number of Firebird/InterBase connections per process, including persistent connections.
`ibase.default_db` string
  The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.
`ibase.default_user` string
  The user name to use when connecting to a database if no user name is specified.
`ibase.default_password` string
  The password to use when connecting to a database if no password is specified.
`ibase.default_charset` string
  The character set to use when connecting to a database if no character set is specified.
`ibase.timestampformat` string
`ibase.dateformat` string
`ibase.timeformat` string
  These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.

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

The following constants can be passed to ibase_trans() to specify transaction behaviour.

Firebird/InterBase transaction flags
Constant | Description
--- | ---
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either `IBASE_REC_VERSION` or `IBASE_REC_NO_VERSION`. This isolation level allows access to changes that were committed after the transaction was started. If `IBASE_REC_NO_VERSION` was specified, only the latest version of a row can be read. If `IBASE_REC_VERSION` was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Firebird/InterBase fetch flags
Constant | Description
--- | ---
IBASE_FETCH_BLOBS | Also available as `IBASE_TEXT`for backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service API functions (ibase_server_info(), ibase_db_info(), ibase_backup(), ibase_restore() and ibase_maintain_db()). Please refer to the Firebird/InterBase manuals for the meaning of these options.

`IBASE_BKP_IGNORE_CHECKSUMS`
  Options to ibase_backup()
`IBASE_BKP_IGNORE_LIMBO`
  Options to ibase_backup()
`IBASE_BKP_METADATA_ONLY`
  Options to ibase_backup()
`IBASE_BKP_NO_GARBAGE_COLLECT`
  Options to ibase_backup()
`IBASE_BKP_OLD_DESCRIPTIONS`
  Options to ibase_backup()
`IBASE_BKP_NON_TRANSPORTABLE`
  Options to ibase_backup()
`IBASE_BKP_CONVERT`
  Options to ibase_backup()
`IBASE_RES_DEACTIVATE_IDX`
  Options to ibase_restore()
`IBASE_RES_NO_SHADOW`
  Options to ibase_restore()
`IBASE_RES_NO_VALIDITY`
  Options to ibase_restore()
`IBASE_RES_ONE_AT_A_TIME`
  Options to ibase_restore()
`IBASE_RES_REPLACE`
`IBASE_RES_CREATE`
  Options to ibase_restore()
`IBASE_RES_USE_ALL_SPACE`
  Options to ibase_restore()
`IBASE_PRP_PAGE_BUFFERS`
`IBASE_PRP_SWEEP_INTERVAL`
`IBASE_PRP_SHUTDOWN_DB`
`IBASE_PRP_DENY_NEW_TRANSACTIONS`
`IBASE_PRP_DENY_NEW_ATTACHMENTS`
`IBASE_PRP_RESERVE_SPACE`
`IBASE_PRP_RES_USE_FULL`
`IBASE_PRP_RES`
`IBASE_PRP_WRITE_MODE`
`IBASE_PRP_WM_ASYNC`
`IBASE_PRP_WM_SYNC`
`IBASE_PRP_ACCESS_MODE`
`IBASE_PRP_AM_READONLY`
`IBASE_PRP_AM_READWRITE`
`IBASE_PRP_SET_SQL_DIALECT`
`IBASE_PRP_ACTIVATE`
`IBASE_PRP_DB_ONLINE`
`IBASE_RPR_CHECK_DB`
`IBASE_RPR_IGNORE_CHECKSUM`
`IBASE_RPR_KILL_SHADOWS`
`IBASE_RPR_MEND_DB`
`IBASE_RPR_VALIDATE_DB`
`IBASE_RPR_FULL`
`IBASE_RPR_SWEEP_DB`
  Options to ibase_maintain_db()
`IBASE_STS_DATA_PAGES`
`IBASE_STS_DB_LOG`
`IBASE_STS_HDR_PAGES`
`IBASE_STS_IDX_PAGES`
`IBASE_STS_SYS_RELATIONS`
  Options to ibase_db_info()
`IBASE_SVC_SERVER_VERSION`
  Options to ibase_server_info()
`IBASE_SVC_IMPLEMENTATION`
  Options to ibase_server_info()
`IBASE_SVC_GET_ENV`
  Options to ibase_server_info()
`IBASE_SVC_GET_ENV_LOCK`
`IBASE_SVC_GET_ENV_MSG`
`IBASE_SVC_USER_DBPATH`
`IBASE_SVC_SVR_DB_INFO`
`IBASE_SVC_GET_USERS`
  Options to ibase_server_info()

# Firebird/InterBase Functions

# fbird_add_user

(PHP 5, PHP 7 < 7.4.0)

fbird_add_user — Alias of ibase_add_user()

### Description

This function is an alias of: ibase_add_user().

### See Also

- fbird_modify_user() - Alias of ibase_modify_user
- fbird_delete_user() - Alias of ibase_delete_user

# fbird_affected_rows

(PHP 5, PHP 7 < 7.4.0)

fbird_affected_rows — Alias of ibase_affected_rows()

### Description

This function is an alias of: ibase_affected_rows().

### See Also

- fbird_query() - Alias of ibase_query
- fbird_execute() - Alias of ibase_execute

# fbird_backup

(PHP 5, PHP 7 < 7.4.0)

fbird_backup — Alias of ibase_backup()

### Description

This function is an alias of: ibase_backup().

# fbird_blob_add

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_add — Alias of ibase_blob_add()

### Description

This function is an alias of: ibase_blob_add().

### See Also

- fbird_blob_cancel() - Cancel creating blob
- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_create() - Alias of ibase_blob_create
- fbird_blob_import() - Alias of ibase_blob_import

# fbird_blob_cancel

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_cancel — Cancel creating blob

### Description

fbird_blob_cancel(resource `$blob_handle`): bool

This function will discard a BLOB if it has not yet been closed by fbird_blob_close().

### Parameters

`blob_handle`
  A BLOB handle opened with fbird_blob_create().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_create() - Alias of ibase_blob_create
- fbird_blob_import() - Alias of ibase_blob_import

# fbird_blob_close

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_close — Alias of ibase_blob_close()

### Description

This function is an alias of: ibase_blob_close().

### See Also

- fbird_blob_create() - Alias of ibase_blob_create
- fbird_blob_cancel() - Cancel creating blob
- fbird_blob_open() - Alias of ibase_blob_open
- fbird_blob_import() - Alias of ibase_blob_import

# fbird_blob_create

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_create — Alias of ibase_blob_create()

### Description

This function is an alias of: ibase_blob_create().

### See Also

- fbird_blob_add() - Alias of ibase_blob_add
- fbird_blob_cancel() - Cancel creating blob
- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_import() - Alias of ibase_blob_import

# fbird_blob_echo

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_echo — Alias of ibase_blob_echo()

### Description

This function is an alias of: ibase_blob_echo().

### See Also

- fbird_blob_open() - Alias of ibase_blob_open
- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_get() - Alias of ibase_blob_get

# fbird_blob_get

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_get — Alias of ibase_blob_get()

### Description

This function is an alias of: ibase_blob_get().

### See Also

- fbird_blob_open() - Alias of ibase_blob_open
- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_echo() - Alias of ibase_blob_echo

# fbird_blob_import

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_import — Alias of ibase_blob_import()

### Description

This function is an alias of: ibase_blob_import().

### See Also

- fbird_blob_add() - Alias of ibase_blob_add
- fbird_blob_cancel() - Cancel creating blob
- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_create() - Alias of ibase_blob_create

# fbird_blob_info

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_info — Alias of ibase_blob_info()

### Description

This function is an alias of: ibase_blob_info().

# fbird_blob_open

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_open — Alias of ibase_blob_open()

### Description

This function is an alias of: ibase_blob_open().

### See Also

- fbird_blob_close() - Alias of ibase_blob_close
- fbird_blob_echo() - Alias of ibase_blob_echo
- fbird_blob_get() - Alias of ibase_blob_get

# fbird_close

(PHP 5, PHP 7 < 7.4.0)

fbird_close — Alias of ibase_close()

### Description

This function is an alias of: ibase_close().

### See Also

- fbird_connect() - Alias of ibase_connect
- fbird_pconnect() - Alias of ibase_pconnect

# fbird_commit

(PHP 5, PHP 7 < 7.4.0)

fbird_commit — Alias of ibase_commit()

### Description

This function is an alias of: ibase_commit().

# fbird_commit_ret

(PHP 5, PHP 7 < 7.4.0)

fbird_commit_ret — Alias of ibase_commit_ret()

### Description

This function is an alias of: ibase_commit_ret().

# fbird_connect

(PHP 5, PHP 7 < 7.4.0)

fbird_connect — Alias of ibase_connect()

### Description

This function is an alias of: ibase_connect().

### See Also

- fbird_pconnect() - Alias of ibase_pconnect
- fbird_close() - Alias of ibase_close

# fbird_db_info

(PHP 5, PHP 7 < 7.4.0)

fbird_db_info — Alias of ibase_db_info()

### Description

This function is an alias of: ibase_db_info().

# fbird_delete_user

(PHP 5, PHP 7 < 7.4.0)

fbird_delete_user — Alias of ibase_delete_user()

### Description

This function is an alias of: ibase_delete_user().

### See Also

- fbird_add_user() - Alias of ibase_add_user
- fbird_modify_user() - Alias of ibase_modify_user

# fbird_drop_db

(PHP 5, PHP 7 < 7.4.0)

fbird_drop_db — Alias of ibase_drop_db()

### Description

This function is an alias of: ibase_drop_db().

### See Also

- fbird_connect() - Alias of ibase_connect
- fbird_pconnect() - Alias of ibase_pconnect

# fbird_errcode

(PHP 5, PHP 7 < 7.4.0)

fbird_errcode — Alias of ibase_errcode()

### Description

This function is an alias of: ibase_errcode().

### See Also

- fbird_errmsg() - Alias of ibase_errmsg

# fbird_errmsg

(PHP 5, PHP 7 < 7.4.0)

fbird_errmsg — Alias of ibase_errmsg()

### Description

This function is an alias of: ibase_errmsg().

### See Also

- fbird_errcode() - Alias of ibase_errcode

# fbird_execute

(PHP 5, PHP 7 < 7.4.0)

fbird_execute — Alias of ibase_execute()

### Description

This function is an alias of: ibase_execute().

### See Also

- fbird_query() - Alias of ibase_query

# fbird_fetch_assoc

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_assoc — Alias of ibase_fetch_assoc()

### Description

This function is an alias of: ibase_fetch_assoc().

### See Also

- fbird_fetch_row() - Alias of ibase_fetch_row
- fbird_fetch_object() - Alias of ibase_fetch_object

# fbird_fetch_object

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_object — Alias of ibase_fetch_object()

### Description

This function is an alias of: ibase_fetch_object().

### See Also

- fbird_fetch_row() - Alias of ibase_fetch_row
- fbird_fetch_assoc() - Alias of ibase_fetch_assoc

# fbird_fetch_row

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_row — Alias of ibase_fetch_row()

### Description

This function is an alias of: ibase_fetch_row().

### See Also

- fbird_fetch_assoc() - Alias of ibase_fetch_assoc
- fbird_fetch_object() - Alias of ibase_fetch_object

# fbird_field_info

(PHP 5, PHP 7 < 7.4.0)

fbird_field_info — Alias of ibase_field_info()

### Description

This function is an alias of: ibase_field_info().

### See Also

- fbird_num_fields() - Alias of ibase_num_fields

# fbird_free_event_handler

(PHP 5, PHP 7 < 7.4.0)

fbird_free_event_handler — Alias of ibase_free_event_handler()

### Description

This function is an alias of: ibase_free_event_handler().

### See Also

- fbird_set_event_handler() - Alias of ibase_set_event_handler

# fbird_free_query

(PHP 5, PHP 7 < 7.4.0)

fbird_free_query — Alias of ibase_free_query()

### Description

This function is an alias of: ibase_free_query().

# fbird_free_result

(PHP 5, PHP 7 < 7.4.0)

fbird_free_result — Alias of ibase_free_result()

### Description

This function is an alias of: ibase_free_result().

# fbird_gen_id

(PHP 5, PHP 7 < 7.4.0)

fbird_gen_id — Alias of ibase_gen_id()

### Description

This function is an alias of: ibase_gen_id().

# fbird_maintain_db

(PHP 5, PHP 7 < 7.4.0)

fbird_maintain_db — Alias of ibase_maintain_db()

### Description

This function is an alias of: ibase_maintain_db().

# fbird_modify_user

(PHP 5, PHP 7 < 7.4.0)

fbird_modify_user — Alias of ibase_modify_user()

### Description

This function is an alias of: ibase_modify_user().

### See Also

- fbird_add_user() - Alias of ibase_add_user
- fbird_delete_user() - Alias of ibase_delete_user

# fbird_name_result

(PHP 5, PHP 7 < 7.4.0)

fbird_name_result — Alias of ibase_name_result()

### Description

This function is an alias of: ibase_name_result().

### See Also

- fbird_prepare() - Alias of ibase_prepare
- fbird_execute() - Alias of ibase_execute

# fbird_num_fields

(PHP 5, PHP 7 < 7.4.0)

fbird_num_fields — Alias of ibase_num_fields()

### Description

This function is an alias of: ibase_num_fields().

### See Also

- fbird_field_info() - Alias of ibase_field_info

# fbird_num_params

(PHP 5, PHP 7 < 7.4.0)

fbird_num_params — Alias of ibase_num_params()

### Description

This function is an alias of: ibase_num_params().

### See Also

- fbird_prepare() - Alias of ibase_prepare
- fbird_param_info() - Alias of ibase_param_info

# fbird_param_info

(PHP 5, PHP 7 < 7.4.0)

fbird_param_info — Alias of ibase_param_info()

### Description

This function is an alias of: ibase_param_info().

### See Also

- fbird_field_info() - Alias of ibase_field_info
- fbird_num_params() - Alias of ibase_num_params

# fbird_pconnect

(PHP 5, PHP 7 < 7.4.0)

fbird_pconnect — Alias of ibase_pconnect()

### Description

This function is an alias of: ibase_pconnect().

### See Also

- fbird_close() - Alias of ibase_close
- fbird_connect() - Alias of ibase_connect

# fbird_prepare

(PHP 5, PHP 7 < 7.4.0)

fbird_prepare — Alias of ibase_prepare()

### Description

This function is an alias of: ibase_prepare().

# fbird_query

(PHP 5, PHP 7 < 7.4.0)

fbird_query — Alias of ibase_query()

### Description

This function is an alias of: ibase_query().

### See Also

- fbird_errmsg() - Alias of ibase_errmsg
- fbird_fetch_row() - Alias of ibase_fetch_row
- fbird_fetch_object() - Alias of ibase_fetch_object
- fbird_free_result() - Alias of ibase_free_result

# fbird_restore

(PHP 5, PHP 7 < 7.4.0)

fbird_restore — Alias of ibase_restore()

### Description

This function is an alias of: ibase_restore().

# fbird_rollback

(PHP 5, PHP 7 < 7.4.0)

fbird_rollback — Alias of ibase_rollback()

### Description

This function is an alias of: ibase_rollback().

# fbird_rollback_ret

(PHP 5, PHP 7 < 7.4.0)

fbird_rollback_ret — Alias of ibase_rollback_ret()

### Description

This function is an alias of: ibase_rollback_ret().

# fbird_server_info

(PHP 5, PHP 7 < 7.4.0)

fbird_server_info — Alias of ibase_server_info()

### Description

This function is an alias of: ibase_server_info().

# fbird_service_attach

(PHP 5, PHP 7 < 7.4.0)

fbird_service_attach — Alias of ibase_service_attach()

### Description

This function is an alias of: ibase_service_attach().

# fbird_service_detach

(PHP 5, PHP 7 < 7.4.0)

fbird_service_detach — Alias of ibase_service_detach()

### Description

This function is an alias of: ibase_service_detach().

# fbird_set_event_handler

(PHP 5, PHP 7 < 7.4.0)

fbird_set_event_handler — Alias of ibase_set_event_handler()

### Description

This function is an alias of: ibase_set_event_handler().

### See Also

- fbird_free_event_handler() - Alias of ibase_free_event_handler
- fbird_wait_event() - Alias of ibase_wait_event

# fbird_trans

(PHP 5, PHP 7 < 7.4.0)

fbird_trans — Alias of ibase_trans()

### Description

This function is an alias of: ibase_trans().

# fbird_wait_event

(PHP 5, PHP 7 < 7.4.0)

fbird_wait_event — Alias of ibase_wait_event()

### Description

This function is an alias of: ibase_wait_event().

### See Also

- fbird_set_event_handler() - Alias of ibase_set_event_handler
- fbird_free_event_handler() - Alias of ibase_free_event_handler

# ibase_add_user

(PHP 5, PHP 7 < 7.4.0)

ibase_add_user — Add a user to a security database

### Description

ibase_add_user(
resource `$service_handle`,
string `$user_name`,
string `$password`,
string `$first_name` = ?,
string `$middle_name` = ?,
string `$last_name` = ?
): bool

### Parameters

`service_handle`
  The handle on the database server service.
`user_name`
  The login name of the new database user.
`password`
  The password of the new user.
`first_name`
  The first name of the new database user.
`middle_name`
  The middle name of the new database user.
`last_name`
  The last name of the new database user.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_modify_user() - Modify a user to a security database
- ibase_delete_user() - Delete a user from a security database

# ibase_affected_rows

(PHP 5, PHP 7 < 7.4.0)

ibase_affected_rows — Return the number of rows that were affected by the previous query

### Description

ibase_affected_rows(resource `$link_identifier` = ?): int

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

### Parameters

`link_identifier`
  A transaction context. If `link_identifier` is a connection resource, its default transaction is used.

### Return Values

Returns the number of rows as an integer.

### See Also

- ibase_query() - Execute a query on an InterBase database
- ibase_execute() - Execute a previously prepared query

# ibase_backup

(PHP 5, PHP 7 < 7.4.0)

ibase_backup — Initiates a backup task in the service manager and returns immediately

### Description

ibase_backup(
resource `$service_handle`,
string `$source_db`,
string `$dest_file`,
int `$options` = 0,
bool `$verbose` = `false`
): mixed

This function passes the arguments to the (remote) database server. There it starts a new backup process. Therefore you won't get any responses.

### Parameters

`service_handle`
  A previously opened connection to the database server.
`source_db`
  The absolute file path to the database on the database server. You can also use a database alias.
`dest_file`
  The path to the backup file on the database server.
`options`

  Additional options to pass to the database server for backup. The `options` parameter can be a combination of the following constants: `IBASE_BKP_IGNORE_CHECKSUMS`, `IBASE_BKP_IGNORE_LIMBO`, `IBASE_BKP_METADATA_ONLY`, `IBASE_BKP_NO_GARBAGE_COLLECT`, `IBASE_BKP_OLD_DESCRIPTIONS`, `IBASE_BKP_NON_TRANSPORTABLE` or `IBASE_BKP_CONVERT`. Read the section about Predefined Constants for further information.

`verbose`
  Since the backup process is done on the database server, you don't have any chance to get its output. This argument is useless.

### Return Values

Returns `true` on success or `false` on failure.

Since the backup process is done on the (remote) server, this function just passes the arguments to it. While the arguments are legal, you won't get `false`.

### Examples

Example #1 ibase_backup() example

`<?php
// Attach to database server by ip address and port
$service = ibase_service_attach ('10.1.11.200/3050', 'sysdba', 'masterkey');
// Start the backup process on database server
// Backup employee database using full path to /srv/backup/employees.fbk
// Don't use any special arguments
ibase_backup($service, '/srv/firebird/employees.fdb', '/srv/backup/employees.fbk');
// Free the attached connection
ibase_service_detach ($service);
?>`

Example #2 ibase_backup() example with arguments

`<?php
// Attach to database server by name and default port
$service = ibase_service_attach ('fb-server.contoso.local', 'sysdba', 'masterkey');
// Start the backup process on database server
// Backup employee database using alias to /srv/backup/employees.fbk.
// Backup only the metadata. Don't create a transportable backup.
ibase_backup($service, 'employees.fdb', '/srv/backup/employees.fbk', IBASE_BKP_METADATA_ONLY | IBASE_BKP_NON_TRANSPORTABLE);
// Free the attached connection
ibase_service_detach ($service);
?>`

### See Also

- ibase_restore() - Initiates a restore task in the service manager and returns immediately

# ibase_blob_add

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_add — Add data into a newly created blob

### Description

ibase_blob_add(resource `$blob_handle`, string `$data`): void

ibase_blob_add() adds data into a blob created with ibase_blob_create().

### Parameters

`blob_handle`
  A blob handle opened with ibase_blob_create().
`data`
  The data to be added.

### Return Values

No value is returned.

### See Also

- ibase_blob_cancel() - Cancel creating blob
- ibase_blob_close() - Close blob
- ibase_blob_create() - Create a new blob for adding data
- ibase_blob_import() - Create blob, copy file in it, and close it

# ibase_blob_cancel

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_cancel — Cancel creating blob

### Description

ibase_blob_cancel(resource `$blob_handle`): bool

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

### Parameters

`blob_handle`
  A BLOB handle opened with ibase_blob_create().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_blob_close() - Close blob
- ibase_blob_create() - Create a new blob for adding data
- ibase_blob_import() - Create blob, copy file in it, and close it

# ibase_blob_close

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_close — Close blob

### Description

ibase_blob_close(resource `$blob_handle`): mixed

This function closes a BLOB that has either been opened for reading by ibase_blob_open() or has been opened for writing by ibase_blob_create().

### Parameters

`blob_handle`
  A BLOB handle opened with ibase_blob_create() or ibase_blob_open().

### Return Values

If the BLOB was being read, this function returns `true` on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns `false`.

### See Also

- ibase_blob_cancel() - Cancel creating blob
- ibase_blob_open() - Open blob for retrieving data parts

# ibase_blob_create

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_create — Create a new blob for adding data

### Description

ibase_blob_create(resource `$link_identifier` = `null`): resource|false

ibase_blob_create() creates a new BLOB for filling with data.

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.

### Return Values

Returns a BLOB handle for later use with ibase_blob_add() or `false` on failure.

### See Also

- ibase_blob_add() - Add data into a newly created blob
- ibase_blob_cancel() - Cancel creating blob
- ibase_blob_close() - Close blob
- ibase_blob_import() - Create blob, copy file in it, and close it

# ibase_blob_echo

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_echo — Output blob contents to browser

### Description

ibase_blob_echo(string `$blob_id`): bool
ibase_blob_echo(resource `$link_identifier`, string `$blob_id`): bool

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.
`blob_id`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_blob_open() - Open blob for retrieving data parts
- ibase_blob_close() - Close blob
- ibase_blob_get() - Get len bytes data from open blob

# ibase_blob_get

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_get — Get len bytes data from open blob

### Description

ibase_blob_get(resource `$blob_handle`, int `$len`): string

This function returns at most `len` bytes from a BLOB that has been opened for reading by ibase_blob_open().

> Note: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

### Parameters

`blob_handle`
  A BLOB handle opened with ibase_blob_open().
`len`
  Size of returned data.

### Return Values

Returns at most `len` bytes from the BLOB, or `false` on failure.

### Examples

Example #1 ibase_blob_get() example

`<?php
$result = ibase_query("SELECT blob_value FROM table");
$data = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo ibase_blob_get($blob_hndl, $blob_data[0]);
?>`
Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

### See Also

- ibase_blob_open() - Open blob for retrieving data parts
- ibase_blob_close() - Close blob
- ibase_blob_echo() - Output blob contents to browser

# ibase_blob_import

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_import — Create blob, copy file in it, and close it

### Description

ibase_blob_import(resource `$link_identifier`, resource `$file_handle`): string
ibase_blob_import(resource `$file_handle`): string

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.
`file_handle`
  The file handle is a handle returned by fopen().

### Return Values

Returns the BLOB id on success, or `false` on error.

### Examples

Example #1 ibase_blob_import() example

`<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';
$fd = fopen($filename, 'r');
if ($fd) {
$blob = ibase_blob_import($dbh, $fd);
fclose($fd);
if (!is_string($blob)) {
// import failed
} else {
$query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
$prepared = ibase_prepare($dbh, $query);
if (!ibase_execute($prepared, $blob)) {
// record insertion failed
}
}
} else {
// unable to open the data file
}
?>`

### See Also

- ibase_blob_add() - Add data into a newly created blob
- ibase_blob_cancel() - Cancel creating blob
- ibase_blob_close() - Close blob
- ibase_blob_create() - Create a new blob for adding data

# ibase_blob_info

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_info — Return blob length and other useful info

### Description

ibase_blob_info(resource `$link_identifier`, string `$blob_id`): array
ibase_blob_info(string `$blob_id`): array

Returns the BLOB length and other useful information.

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.
`blob_id`
  A BLOB id.

### Return Values

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

# ibase_blob_open

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_open — Open blob for retrieving data parts

### Description

ibase_blob_open(resource `$link_identifier`, string `$blob_id`): resource|false
ibase_blob_open(string `$blob_id`): resource|false

Opens an existing BLOB for reading.

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.
`blob_id`
  A BLOB id.

### Return Values

Returns a BLOB handle for later use with ibase_blob_get() or `false` on failure.

### See Also

- ibase_blob_close() - Close blob
- ibase_blob_echo() - Output blob contents to browser
- ibase_blob_get() - Get len bytes data from open blob

# ibase_close

(PHP 5, PHP 7 < 7.4.0)

ibase_close — Close a connection to an InterBase database

### Description

ibase_close(resource `$connection_id` = `null`): bool

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

### Parameters

`connection_id`
  An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_connect() - Open a connection to a database
- ibase_pconnect() - Open a persistent connection to an InterBase database

# ibase_commit

(PHP 5, PHP 7 < 7.4.0)

ibase_commit — Commit a transaction

### Description

ibase_commit(resource `$link_or_trans_identifier` = `null`): bool

Commits a transaction.

### Parameters

`link_or_trans_identifier`
  If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed.

### Return Values

Returns `true` on success or `false` on failure.

# ibase_commit_ret

(PHP 5, PHP 7 < 7.4.0)

ibase_commit_ret — Commit a transaction without closing it

### Description

ibase_commit_ret(resource `$link_or_trans_identifier` = `null`): bool

Commits a transaction without closing it.

### Parameters

`link_or_trans_identifier`
  If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

### Return Values

Returns `true` on success or `false` on failure.

# ibase_connect

(PHP 5, PHP 7 < 7.4.0)

ibase_connect — Open a connection to a database

### Description

ibase_connect(
string `$database` = ?,
string `$username` = ?,
string `$password` = ?,
string `$charset` = ?,
int `$buffers` = ?,
int `$dialect` = ?,
string `$role` = ?,
int `$sync` = ?
): resource

Establishes a connection to an Firebird/InterBase server.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

### Parameters

`database`
  The `database` argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), 'hostname/port:' (TCP/IP with interbase server on custom TCP port), '//hostname/' (NetBEUI), depending on the connection protocol used.
`username`
  The user name. Can be set with the `ibase.default_user` php.ini directive.
`password`
  The password for `username`. Can be set with the `ibase.default_password` php.ini directive.
`charset`
  `charset` is the default character set for a database.
`buffers`
  `buffers` is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.
`dialect`
  `dialect` selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.
`role`
  Functional only with InterBase 5 and up.
`sync`

### Return Values

Returns an Firebird/InterBase link identifier on success, or `false` on error.

### Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

### Examples

Example #1 ibase_connect() example

`<?php
$host = 'localhost:/path/to/your.gdb';
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>`

### See Also

- ibase_pconnect() - Open a persistent connection to an InterBase database
- ibase_close() - Close a connection to an InterBase database

# ibase_db_info

(PHP 5, PHP 7 < 7.4.0)

ibase_db_info — Request statistics about a database

### Description

ibase_db_info(
resource `$service_handle`,
string `$db`,
int `$action`,
int `$argument` = 0
): string
Warning

This function is currently not documented; only its argument list is available.

# ibase_delete_user

(PHP 5, PHP 7 < 7.4.0)

ibase_delete_user — Delete a user from a security database

### Description

ibase_delete_user(resource `$service_handle`, string `$user_name`): bool

### Parameters

`service_handle`
  The handle on the database server service.
`user_name`
  The login name of the user you want to delete from the database.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_add_user() - Add a user to a security database
- ibase_modify_user() - Modify a user to a security database

# ibase_drop_db

(PHP 5, PHP 7 < 7.4.0)

ibase_drop_db — Drops a database

### Description

ibase_drop_db(resource `$connection` = `null`): bool

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

### Parameters

`connection`
  An InterBase link identifier. If omitted, the last opened link is assumed.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_connect() - Open a connection to a database
- ibase_pconnect() - Open a persistent connection to an InterBase database

# ibase_errcode

(PHP 5, PHP 7 < 7.4.0)

ibase_errcode — Return an error code

### Description

ibase_errcode(): int

Returns the error code that resulted from the most recent InterBase function call.

### Parameters

This function has no parameters.

### Return Values

Returns the error code as an integer, or `false` if no error occurred.

### See Also

- ibase_errmsg() - Return error messages

# ibase_errmsg

(PHP 5, PHP 7 < 7.4.0)

ibase_errmsg — Return error messages

### Description

ibase_errmsg(): string

Returns the error message that resulted from the most recent InterBase function call.

### Parameters

This function has no parameters.

### Return Values

Returns the error message as a string, or `false` if no error occurred.

### See Also

- ibase_errcode() - Return an error code

# ibase_execute

(PHP 5, PHP 7 < 7.4.0)

ibase_execute — Execute a previously prepared query

### Description

ibase_execute(resource `$query`, mixed `...$values`): resource

Execute a query prepared by ibase_prepare().

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

### Parameters

`query`
  An InterBase query prepared by ibase_prepare().
`values`

### Return Values

If the query raises an error, returns `false`. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns `true`.

> Note: This function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return `true`.

### Examples

Example #1 ibase_execute() example

`<?php
$dbh = ibase_connect($host, $username, $password);
$updates = array(
1 => 'Eric',
5 => 'Filip',
7 => 'Larry'
);
$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");
foreach ($updates as $baz => $bar) {
ibase_execute($query, $bar, $baz);
}
?>`

### See Also

- ibase_query() - Execute a query on an InterBase database

# ibase_fetch_assoc

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_assoc — Fetch a result row from a query as an associative array

### Description

ibase_fetch_assoc(resource `$result`, int `$fetch_flag` = 0): array

Fetch a result row from a query as an associative array.

ibase_fetch_assoc() fetches one row of data from the `result`. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

### Parameters

`result`
  The result handle.
`fetch_flag`
  `fetch_flag` is a combination of the constants `IBASE_TEXT` and `IBASE_UNIXTIME` ORed together. Passing `IBASE_TEXT` will cause this function to return BLOB contents instead of BLOB ids. Passing `IBASE_UNIXTIME` will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

### Return Values

Returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or `false` if there are no more rows.

### See Also

- ibase_fetch_row() - Fetch a row from an InterBase database
- ibase_fetch_object() - Get an object from a InterBase database

# ibase_fetch_object

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_object — Get an object from a InterBase database

### Description

ibase_fetch_object(resource `$result_id`, int `$fetch_flag` = 0): object

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

### Parameters

`result_id`
  An InterBase result identifier obtained either by ibase_query() or ibase_execute().
`fetch_flag`
  `fetch_flag` is a combination of the constants `IBASE_TEXT` and `IBASE_UNIXTIME` ORed together. Passing `IBASE_TEXT` will cause this function to return BLOB contents instead of BLOB ids. Passing `IBASE_UNIXTIME` will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

### Return Values

Returns an object with the next row information, or `false` if there are no more rows.

### Examples

Example #1 ibase_fetch_object() example

`<?php
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->email . "\n";
}
ibase_close($dbh);
?>`

### See Also

- ibase_fetch_row() - Fetch a row from an InterBase database
- ibase_fetch_assoc() - Fetch a result row from a query as an associative array

# ibase_fetch_row

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_row — Fetch a row from an InterBase database

### Description

ibase_fetch_row(resource `$result_identifier`, int `$fetch_flag` = 0): array

ibase_fetch_row() fetches one row of data from the given result set.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or `false` if there are no more rows.

### Parameters

`result_identifier`
  An InterBase result identifier.
`fetch_flag`
  `fetch_flag` is a combination of the constants `IBASE_TEXT` and `IBASE_UNIXTIME` ORed together. Passing `IBASE_TEXT` will cause this function to return BLOB contents instead of BLOB ids. Passing `IBASE_UNIXTIME` will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

### Return Values

Returns an array that corresponds to the fetched row, or `false` if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

### See Also

- ibase_fetch_assoc() - Fetch a result row from a query as an associative array
- ibase_fetch_object() - Get an object from a InterBase database

# ibase_field_info

(PHP 5, PHP 7 < 7.4.0)

ibase_field_info — Get information about a field

### Description

ibase_field_info(resource `$result`, int `$field_number`): array

Returns an array with information about a field after a select query has been run.

### Parameters

`result`
  An InterBase result identifier.
`field_number`
  Field offset.

### Return Values

Returns an array with the following keys: `name`, `alias`, `relation`, `length` and `type`.

### Examples

Example #1 ibase_field_info() example

`<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
echo "name: ". $col_info['name']. "\n";
echo "alias: ". $col_info['alias']. "\n";
echo "relation: ". $col_info['relation']. "\n";
echo "length: ". $col_info['length']. "\n";
echo "type: ". $col_info['type']. "\n";
}
?>`

### See Also

- ibase_num_fields() - Get the number of fields in a result set

# ibase_free_event_handler

(PHP 5, PHP 7 < 7.4.0)

ibase_free_event_handler — Cancels a registered event handler

### Description

ibase_free_event_handler(resource `$event`): bool

This function causes the registered event handler specified by `event` to be cancelled. The callback function will no longer be called for the events it was registered to handle.

### Parameters

`event`
  An event resource, created by ibase_set_event_handler().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_set_event_handler() - Register a callback function to be called when events are posted

# ibase_free_query

(PHP 5, PHP 7 < 7.4.0)

ibase_free_query — Free memory allocated by a prepared query

### Description

ibase_free_query(resource `$query`): bool

Frees a prepared query.

### Parameters

`query`
  A query prepared with ibase_prepare().

### Return Values

Returns `true` on success or `false` on failure.

# ibase_free_result

(PHP 5, PHP 7 < 7.4.0)

ibase_free_result — Free a result set

### Description

ibase_free_result(resource `$result_identifier`): bool

Frees a result set.

### Parameters

`result_identifier`
  A result set created by ibase_query() or ibase_execute().

### Return Values

Returns `true` on success or `false` on failure.

# ibase_gen_id

(PHP 5, PHP 7 < 7.4.0)

ibase_gen_id — Increments the named generator and returns its new value

### Description

ibase_gen_id(string `$generator`, int `$increment` = 1, resource `$link_identifier` = `null`): mixed
Warning

This function is currently not documented; only its argument list is available.

### Return Values

Returns new generator value as integer, or as string if the value is too big.

# ibase_maintain_db

(PHP 5, PHP 7 < 7.4.0)

ibase_maintain_db — Execute a maintenance command on the database server

### Description

ibase_maintain_db(
resource `$service_handle`,
string `$db`,
int `$action`,
int `$argument` = 0
): bool
Warning

This function is currently not documented; only its argument list is available.

### Return Values

Returns `true` on success or `false` on failure.

# ibase_modify_user

(PHP 5, PHP 7 < 7.4.0)

ibase_modify_user — Modify a user to a security database

### Description

ibase_modify_user(
resource `$service_handle`,
string `$user_name`,
string `$password`,
string `$first_name` = ?,
string `$middle_name` = ?,
string `$last_name` = ?
): bool

### Parameters

`service_handle`
  The handle on the database server service.
`user_name`
  The login name of the database user to modify.
`password`
  The user's new password.
`first_name`
  The user's new first name.
`middle_name`
  The user's new middle name.
`last_name`
  The user's new last name.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ibase_add_user() - Add a user to a security database
- ibase_delete_user() - Delete a user from a security database

# ibase_name_result

(PHP 5, PHP 7 < 7.4.0)

ibase_name_result — Assigns a name to a result set

### Description

ibase_name_result(resource `$result`, string `$name`): bool

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF `name` statements.

### Parameters

`result`
  An InterBase result set.
`name`
  The name to be assigned.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ibase_name_result() example

`<?php
$result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
ibase_name_result($result, "my_cursor");
$updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");
for ($i = 0; ibase_fetch_row($result); ++$i) {
ibase_execute($updateqry, $i);
}
?>`

### See Also

- ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
- ibase_execute() - Execute a previously prepared query

# ibase_num_fields

(PHP 5, PHP 7 < 7.4.0)

ibase_num_fields — Get the number of fields in a result set

### Description

ibase_num_fields(resource `$result_id`): int

Get the number of fields in a result set.

### Parameters

`result_id`
  An InterBase result identifier.

### Return Values

Returns the number of fields as an integer.

### Examples

Example #1 ibase_num_fields() example

`<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
echo "name: " . $col_info['name'] . "\n";
echo "alias: " . $col_info['alias'] . "\n";
echo "relation: " . $col_info['relation'] . "\n";
echo "length: " . $col_info['length'] . "\n";
echo "type: " . $col_info['type'] . "\n";
}
?>`

### See Also

- ibase_field_info() - Get information about a field

# ibase_num_params

(PHP 5, PHP 7 < 7.4.0)

ibase_num_params — Return the number of parameters in a prepared query

### Description

ibase_num_params(resource `$query`): int

This function returns the number of parameters in the prepared query specified by `query`. This is the number of binding arguments that must be present when calling ibase_execute().

### Parameters

`query`
  The prepared query handle.

### Return Values

Returns the number of parameters as an integer.

### See Also

- ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
- ibase_param_info() - Return information about a parameter in a prepared query

# ibase_param_info

(PHP 5, PHP 7 < 7.4.0)

ibase_param_info — Return information about a parameter in a prepared query

### Description

ibase_param_info(resource `$query`, int `$param_number`): array

Returns an array with information about a parameter after a query has been prepared.

### Parameters

`query`
  An InterBase prepared query handle.
`param_number`
  Parameter offset.

### Return Values

Returns an array with the following keys: `name`, `alias`, `relation`, `length` and `type`.

### See Also

- ibase_field_info() - Get information about a field
- ibase_num_params() - Return the number of parameters in a prepared query

# ibase_pconnect

(PHP 5, PHP 7 < 7.4.0)

ibase_pconnect — Open a persistent connection to an InterBase database

### Description

ibase_pconnect(
string `$database` = ?,
string `$username` = ?,
string `$password` = ?,
string `$charset` = ?,
int `$buffers` = ?,
int `$dialect` = ?,
string `$role` = ?,
int `$sync` = ?
): resource

Opens a persistent connection to an InterBase database.

ibase_pconnect() acts very much like ibase_connect() with two major differences.

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

Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

### Parameters

`database`
  The `database` argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.
`username`
  The user name. Can be set with the `ibase.default_user` php.ini directive.
`password`
  The password for `username`. Can be set with the `ibase.default_password` php.ini directive.
`charset`
  `charset` is the default character set for a database.
`buffers`
  `buffers` is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.
`dialect`
  `dialect` selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.
`role`
  Functional only with InterBase 5 and up.
`sync`

### Return Values

Returns an InterBase link identifier on success, or `false` on error.

### See Also

- ibase_close() - Close a connection to an InterBase database
- ibase_connect() - Open a connection to a database

# ibase_prepare

(PHP 5, PHP 7 < 7.4.0)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

### Description

ibase_prepare(string `$query`): resource
ibase_prepare(resource `$link_identifier`, string `$query`): resource
ibase_prepare(resource `$link_identifier`, string `$trans`, string `$query`): resource

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

### Parameters

`query`
  An InterBase query.
`link_identifier`
  An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.
`trans`
  An InterBase transaction handle the query should be associated with. If omitted, the default transaction of the connection is assumed.

### Return Values

Returns a prepared query handle, or `false` on error.

# ibase_query

(PHP 5, PHP 7 < 7.4.0)

ibase_query — Execute a query on an InterBase database

### Description

ibase_query(resource `$link_identifier` = ?, string `$query`, int `$bind_args` = ?): resource

Performs a query on an InterBase database.

### Parameters

`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.
`query`
  An InterBase query.
`bind_args`

### Return Values

If the query raises an error, returns `false`. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns `true`.

> Note: In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return `true` for these statements if the query succeeded without affecting any rows.

### Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

### Examples

Example #1 ibase_query() example

`<?php
$host = 'localhost:/path/to/your.gdb';
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());
?>`

### See Also

- ibase_errmsg() - Return error messages
- ibase_fetch_row() - Fetch a row from an InterBase database
- ibase_fetch_object() - Get an object from a InterBase database
- ibase_free_result() - Free a result set

# ibase_restore

(PHP 5, PHP 7 < 7.4.0)

ibase_restore — Initiates a restore task in the service manager and returns immediately

### Description

ibase_restore(
resource `$service_handle`,
string `$source_file`,
string `$dest_db`,
int `$options` = 0,
bool `$verbose` = `false`
): mixed

This function passes the arguments to the (remote) database server. There it starts a new restore process. Therefore you won't get any responses.

### Parameters

`service_handle`
  A previously opened connection to the database server.
`source_file`
  The absolute path on the server where the backup file is located.
`dest_db`
  The path to create the new database on the server. You can also use database alias.
`options`

  Additional options to pass to the database server for restore. The `options` parameter can be a combination of the following constants: `IBASE_RES_DEACTIVATE_IDX`, `IBASE_RES_NO_SHADOW`, `IBASE_RES_NO_VALIDITY`, `IBASE_RES_ONE_AT_A_TIME`, `IBASE_RES_REPLACE`, `IBASE_RES_CREATE`, `IBASE_RES_USE_ALL_SPACE`, `IBASE_PRP_PAGE_BUFFERS`, `IBASE_PRP_SWEEP_INTERVAL`, `IBASE_RES_CREATE`. Read the section about Predefined Constants for further information.

`verbose`
  Since the restore process is done on the database server, you don't have any chance to get its output. This argument is useless.

### Return Values

Returns `true` on success or `false` on failure.

Since the restore process is done on the (remote) server, this function just passes the arguments to it. While the arguments are legal, you won't get `false`.

### Examples

Example #1 ibase_restore() example

`<?php
// Attach to database server by ip address and port
$service = ibase_service_attach ('10.1.11.200/3050', 'sysdba', 'masterkey');
// Start the restore process on database server
// Restore employee backup to the new emps.fdb database
// Don't use any special arguments
ibase_restore($service, '/srv/backup/employees.fbk', '/srv/firebird/emps.fdb');
// Free the attached connection
ibase_service_detach ($service);
?>`

Example #2 ibase_restore() example with arguments

`<?php
// Attach to database server by name and default port
$service = ibase_service_attach ('fb-server.contoso.local', 'sysdba', 'masterkey');
// Start the restore process on database server
// Restore to employee database using alias.
// Restore without indixes. Replace existing database.
ibase_restore($service, '/srv/backup/employees.fbk', 'employees.fdb', IBASE_RES_DEACTIVATE_IDX | IBASE_RES_REPLACE);
// Free the attached connection
ibase_service_detach ($service);
?>`

### See Also

- ibase_backup() - Initiates a backup task in the service manager and returns immediately

# ibase_rollback

(PHP 5, PHP 7 < 7.4.0)

ibase_rollback — Roll back a transaction

### Description

ibase_rollback(resource `$link_or_trans_identifier` = `null`): bool

Rolls back a transaction.

### Parameters

`link_or_trans_identifier`
  If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back.

### Return Values

Returns `true` on success or `false` on failure.

# ibase_rollback_ret

(PHP 5, PHP 7 < 7.4.0)

ibase_rollback_ret — Roll back a transaction without closing it

### Description

ibase_rollback_ret(resource `$link_or_trans_identifier` = `null`): bool

Rolls back a transaction without closing it.

### Parameters

`link_or_trans_identifier`
  If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

### Return Values

Returns `true` on success or `false` on failure.

# ibase_server_info

(PHP 5, PHP 7 < 7.4.0)

ibase_server_info — Request information about a database server

### Description

ibase_server_info(resource `$service_handle`, int `$action`): string

### Parameters

`service_handle`
  A previously created connection to the database server.
`action`
  A valid constant.

### Return Values

Returns mixed types depending on context.

### Examples

Example #1 ibase_service_attach() example

`<?php
// Attach to the remote Firebird server
if (($service = ibase_service_attach('10.1.1.254/3050', 'sysdba', 'masterkey')) != FALSE) {
// Successfully attached.
// Output the info
echo "Server version: " . ibase_server_info($service, IBASE_SVC_SERVER_VERSION) . "\n";
echo "Server implementation: " . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION) . "\n";
echo "Server users: " . print_r(ibase_server_info($service, IBASE_SVC_GET_USERS), true) . "\n";
echo "Server directory: " . ibase_server_info($service, IBASE_SVC_GET_ENV) . "\n";
echo "Server lock path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_LOCK) . "\n";
echo "Server lib path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_MSG) . "\n";
echo "Path of user db: " . ibase_server_info($service, IBASE_SVC_USER_DBPATH) . "\n";
echo "Established connections: " . print_r(ibase_server_info($service, IBASE_SVC_SVR_DB_INFO),true) . "\n";
// Detach from server (disconnect)
ibase_service_detach($service);
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}
?>`

The above example will output:

    Server version: LI-V3.0.4.33054 Firebird 3.0
    Server implementation: Firebird/Linux/AMD/Intel/x64
    Server users: Array
    (
        [0] => Array
            (
                [user_name] => SYSDBA
                [first_name] => Sql
                [middle_name] => Server
                [last_name] => Administrator
                [user_id] => 0
                [group_id] => 0
            )

    )

    Server directory: /etc/firebird/
    Server lock path: /tmp/firebird/
    Server lib path: /usr/lib64/firebird/lib/
    Path of user db: /var/lib/firebird/secdb/security3.fdb
    Established connections: Array
    (
        [attachments] => 3
        [databases] => 2
        [0] => /srv/firebird/poss.fdb
        [1] => /srv/firebird/employees.fdb
    )

# ibase_service_attach

(PHP 5, PHP 7 < 7.4.0)

ibase_service_attach — Connect to the service manager

### Description

ibase_service_attach(string `$host`, string `$dba_username`, string `$dba_password`): resource|false

### Parameters

`host`
  The name or ip address of the database host. You can define the port by adding '/' and port number. If no port is specified, port 3050 will be used.
`dba_username`
  The name of any valid user.
`dba_password`
  The user's password.

### Return Values

Returns a Interbase / Firebird link identifier on success or `false` on failure.

### Examples

Example #1 ibase_service_attach() example

`<?php
// Attach to the remote Firebird server by ip address
if (($service = ibase_service_attach('10.1.1.199', 'sysdba', 'masterkey')) != FALSE) {
// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);
// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
// Detach from server (disconnect)
ibase_service_detach($service);
// Output the info
echo "Server version: " . $server_version . "<br/>";
echo "Server implementation: " . $server_implementation;
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}
?>`

Example #2 ibase_service_attach() example using `hostname/port` syntax

`<?php
// Attach to the remote Firebird server by name. Use Port 3050.
if (($service = ibase_service_attach('FB-SRV-01.contoso.local/3050', 'sysdba', 'masterkey')) != FALSE) {
// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);
// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
// Detach from server (disconnect)
ibase_service_detach($service);
// Output the info
echo "Server version: " . $server_version . "<br/>";
echo "Server implementation: " . $server_implementation;
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}
?>`

### See Also

- ibase_service_detach() - Disconnect from the service manager

# ibase_service_detach

(PHP 5, PHP 7 < 7.4.0)

ibase_service_detach — Disconnect from the service manager

### Description

ibase_service_detach(resource `$service_handle`): bool

### Parameters

`service_handle`
  A previously created connection to the database server.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ibase_service_detach() example

`<?php
// Attach to the remote Firebird server by ip address
if (($service = ibase_service_attach('10.1.1.199', 'sysdba', 'masterkey')) != FALSE) {
// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);
// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
// Detach from server (disconnect)
if(ibase_service_detach($service) == FALSE) {
echo "Error on service detach.";
}
else {
echo "Successfully detached from service.";
}
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}
?>`

# ibase_set_event_handler

(PHP 5, PHP 7 < 7.4.0)

ibase_set_event_handler — Register a callback function to be called when events are posted

### Description

ibase_set_event_handler(callable `$event_handler`, string `$event_name`, string `...$even_names`): resource
ibase_set_event_handler(
resource `$connection`,
callable `$event_handler`,
string `$event_name`,
string `...$event_names`
): resource

This function registers a PHP user function as event handler for the specified events.

### Parameters

`event_handler`
  The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return `false` if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.
`event_name`
  An event name.
`event_names`
  At most 15 events allowed.

### Return Values

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

### Examples

Example #1 ibase_set_event_handler() example

`<?php
function event_handler($event_name, $link)
{
if ($event_name == "NEW ORDER") {
// process new order
ibase_query($link, "UPDATE orders SET status='handled'");
} else if ($event_name == "DB_SHUTDOWN") {
// free event handler
return false;
}
}
ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>`

### See Also

- ibase_free_event_handler() - Cancels a registered event handler
- ibase_wait_event() - Wait for an event to be posted by the database

# ibase_trans

(PHP 5, PHP 7 < 7.4.0)

ibase_trans — Begin a transaction

### Description

ibase_trans(int `$trans_args` = ?, resource `$link_identifier` = ?): resource
ibase_trans(resource `$link_identifier` = ?, int `$trans_args` = ?): resource

Begins a transaction.

> Note: The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

> Note: This function will accept multiple `trans_args` and `link_identifier` arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query! If you use transactions over multiple databases, you will have to specify both the `link_id` and `transaction_id` in calls to ibase_query() and ibase_prepare().

### Parameters

`trans_args`
  `trans_args` can be a combination of `IBASE_READ`, `IBASE_WRITE`, `IBASE_COMMITTED`, `IBASE_CONSISTENCY`, `IBASE_CONCURRENCY`, `IBASE_REC_VERSION`, `IBASE_REC_NO_VERSION`, `IBASE_WAIT` and `IBASE_NOWAIT`.
`link_identifier`
  An InterBase link identifier. If omitted, the last opened link is assumed.

### Return Values

Returns a transaction handle, or `false` on error.

# ibase_wait_event

(PHP 5, PHP 7 < 7.4.0)

ibase_wait_event — Wait for an event to be posted by the database

### Description

ibase_wait_event(string `$event_name`, string `...$event_names`): string
ibase_wait_event(resource `$connection`, string `$event_name`, string `...$event_names`): string

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

### Parameters

`event_name`
  The event name.
`event_names`

### Return Values

Returns the name of the event that was posted.

### See Also

- ibase_set_event_handler() - Register a callback function to be called when events are posted
- ibase_free_event_handler() - Cancels a registered event handler

## Table of Contents

- fbird_add_user — Alias of ibase_add_user
- fbird_affected_rows — Alias of ibase_affected_rows
- fbird_backup — Alias of ibase_backup
- fbird_blob_add — Alias of ibase_blob_add
- fbird_blob_cancel — Cancel creating blob
- fbird_blob_close — Alias of ibase_blob_close
- fbird_blob_create — Alias of ibase_blob_create
- fbird_blob_echo — Alias of ibase_blob_echo
- fbird_blob_get — Alias of ibase_blob_get
- fbird_blob_import — Alias of ibase_blob_import
- fbird_blob_info — Alias of ibase_blob_info
- fbird_blob_open — Alias of ibase_blob_open
- fbird_close — Alias of ibase_close
- fbird_commit — Alias of ibase_commit
- fbird_commit_ret — Alias of ibase_commit_ret
- fbird_connect — Alias of ibase_connect
- fbird_db_info — Alias of ibase_db_info
- fbird_delete_user — Alias of ibase_delete_user
- fbird_drop_db — Alias of ibase_drop_db
- fbird_errcode — Alias of ibase_errcode
- fbird_errmsg — Alias of ibase_errmsg
- fbird_execute — Alias of ibase_execute
- fbird_fetch_assoc — Alias of ibase_fetch_assoc
- fbird_fetch_object — Alias of ibase_fetch_object
- fbird_fetch_row — Alias of ibase_fetch_row
- fbird_field_info — Alias of ibase_field_info
- fbird_free_event_handler — Alias of ibase_free_event_handler
- fbird_free_query — Alias of ibase_free_query
- fbird_free_result — Alias of ibase_free_result
- fbird_gen_id — Alias of ibase_gen_id
- fbird_maintain_db — Alias of ibase_maintain_db
- fbird_modify_user — Alias of ibase_modify_user
- fbird_name_result — Alias of ibase_name_result
- fbird_num_fields — Alias of ibase_num_fields
- fbird_num_params — Alias of ibase_num_params
- fbird_param_info — Alias of ibase_param_info
- fbird_pconnect — Alias of ibase_pconnect
- fbird_prepare — Alias of ibase_prepare
- fbird_query — Alias of ibase_query
- fbird_restore — Alias of ibase_restore
- fbird_rollback — Alias of ibase_rollback
- fbird_rollback_ret — Alias of ibase_rollback_ret
- fbird_server_info — Alias of ibase_server_info
- fbird_service_attach — Alias of ibase_service_attach
- fbird_service_detach — Alias of ibase_service_detach
- fbird_set_event_handler — Alias of ibase_set_event_handler
- fbird_trans — Alias of ibase_trans
- fbird_wait_event — Alias of ibase_wait_event
- ibase_add_user — Add a user to a security database
- ibase_affected_rows — Return the number of rows that were affected by the previous query
- ibase_backup — Initiates a backup task in the service manager and returns immediately
- ibase_blob_add — Add data into a newly created blob
- ibase_blob_cancel — Cancel creating blob
- ibase_blob_close — Close blob
- ibase_blob_create — Create a new blob for adding data
- ibase_blob_echo — Output blob contents to browser
- ibase_blob_get — Get len bytes data from open blob
- ibase_blob_import — Create blob, copy file in it, and close it
- ibase_blob_info — Return blob length and other useful info
- ibase_blob_open — Open blob for retrieving data parts
- ibase_close — Close a connection to an InterBase database
- ibase_commit — Commit a transaction
- ibase_commit_ret — Commit a transaction without closing it
- ibase_connect — Open a connection to a database
- ibase_db_info — Request statistics about a database
- ibase_delete_user — Delete a user from a security database
- ibase_drop_db — Drops a database
- ibase_errcode — Return an error code
- ibase_errmsg — Return error messages
- ibase_execute — Execute a previously prepared query
- ibase_fetch_assoc — Fetch a result row from a query as an associative array
- ibase_fetch_object — Get an object from a InterBase database
- ibase_fetch_row — Fetch a row from an InterBase database
- ibase_field_info — Get information about a field
- ibase_free_event_handler — Cancels a registered event handler
- ibase_free_query — Free memory allocated by a prepared query
- ibase_free_result — Free a result set
- ibase_gen_id — Increments the named generator and returns its new value
- ibase_maintain_db — Execute a maintenance command on the database server
- ibase_modify_user — Modify a user to a security database
- ibase_name_result — Assigns a name to a result set
- ibase_num_fields — Get the number of fields in a result set
- ibase_num_params — Return the number of parameters in a prepared query
- ibase_param_info — Return information about a parameter in a prepared query
- ibase_pconnect — Open a persistent connection to an InterBase database
- ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
- ibase_query — Execute a query on an InterBase database
- ibase_restore — Initiates a restore task in the service manager and returns immediately
- ibase_rollback — Roll back a transaction
- ibase_rollback_ret — Roll back a transaction without closing it
- ibase_server_info — Request information about a database server
- ibase_service_attach — Connect to the service manager
- ibase_service_detach — Disconnect from the service manager
- ibase_set_event_handler — Register a callback function to be called when events are posted
- ibase_trans — Begin a transaction
- ibase_wait_event — Wait for an event to be posted by the database

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Predefined Constants
- Firebird/InterBase Functions
  - fbird_add_user — Alias of ibase_add_user
  - fbird_affected_rows — Alias of ibase_affected_rows
  - fbird_backup — Alias of ibase_backup
  - fbird_blob_add — Alias of ibase_blob_add
  - fbird_blob_cancel — Cancel creating blob
  - fbird_blob_close — Alias of ibase_blob_close
  - fbird_blob_create — Alias of ibase_blob_create
  - fbird_blob_echo — Alias of ibase_blob_echo
  - fbird_blob_get — Alias of ibase_blob_get
  - fbird_blob_import — Alias of ibase_blob_import
  - fbird_blob_info — Alias of ibase_blob_info
  - fbird_blob_open — Alias of ibase_blob_open
  - fbird_close — Alias of ibase_close
  - fbird_commit — Alias of ibase_commit
  - fbird_commit_ret — Alias of ibase_commit_ret
  - fbird_connect — Alias of ibase_connect
  - fbird_db_info — Alias of ibase_db_info
  - fbird_delete_user — Alias of ibase_delete_user
  - fbird_drop_db — Alias of ibase_drop_db
  - fbird_errcode — Alias of ibase_errcode
  - fbird_errmsg — Alias of ibase_errmsg
  - fbird_execute — Alias of ibase_execute
  - fbird_fetch_assoc — Alias of ibase_fetch_assoc
  - fbird_fetch_object — Alias of ibase_fetch_object
  - fbird_fetch_row — Alias of ibase_fetch_row
  - fbird_field_info — Alias of ibase_field_info
  - fbird_free_event_handler — Alias of ibase_free_event_handler
  - fbird_free_query — Alias of ibase_free_query
  - fbird_free_result — Alias of ibase_free_result
  - fbird_gen_id — Alias of ibase_gen_id
  - fbird_maintain_db — Alias of ibase_maintain_db
  - fbird_modify_user — Alias of ibase_modify_user
  - fbird_name_result — Alias of ibase_name_result
  - fbird_num_fields — Alias of ibase_num_fields
  - fbird_num_params — Alias of ibase_num_params
  - fbird_param_info — Alias of ibase_param_info
  - fbird_pconnect — Alias of ibase_pconnect
  - fbird_prepare — Alias of ibase_prepare
  - fbird_query — Alias of ibase_query
  - fbird_restore — Alias of ibase_restore
  - fbird_rollback — Alias of ibase_rollback
  - fbird_rollback_ret — Alias of ibase_rollback_ret
  - fbird_server_info — Alias of ibase_server_info
  - fbird_service_attach — Alias of ibase_service_attach
  - fbird_service_detach — Alias of ibase_service_detach
  - fbird_set_event_handler — Alias of ibase_set_event_handler
  - fbird_trans — Alias of ibase_trans
  - fbird_wait_event — Alias of ibase_wait_event
  - ibase_add_user — Add a user to a security database
  - ibase_affected_rows — Return the number of rows that were affected by the previous query
  - ibase_backup — Initiates a backup task in the service manager and returns immediately
  - ibase_blob_add — Add data into a newly created blob
  - ibase_blob_cancel — Cancel creating blob
  - ibase_blob_close — Close blob
  - ibase_blob_create — Create a new blob for adding data
  - ibase_blob_echo — Output blob contents to browser
  - ibase_blob_get — Get len bytes data from open blob
  - ibase_blob_import — Create blob, copy file in it, and close it
  - ibase_blob_info — Return blob length and other useful info
  - ibase_blob_open — Open blob for retrieving data parts
  - ibase_close — Close a connection to an InterBase database
  - ibase_commit — Commit a transaction
  - ibase_commit_ret — Commit a transaction without closing it
  - ibase_connect — Open a connection to a database
  - ibase_db_info — Request statistics about a database
  - ibase_delete_user — Delete a user from a security database
  - ibase_drop_db — Drops a database
  - ibase_errcode — Return an error code
  - ibase_errmsg — Return error messages
  - ibase_execute — Execute a previously prepared query
  - ibase_fetch_assoc — Fetch a result row from a query as an associative array
  - ibase_fetch_object — Get an object from a InterBase database
  - ibase_fetch_row — Fetch a row from an InterBase database
  - ibase_field_info — Get information about a field
  - ibase_free_event_handler — Cancels a registered event handler
  - ibase_free_query — Free memory allocated by a prepared query
  - ibase_free_result — Free a result set
  - ibase_gen_id — Increments the named generator and returns its new value
  - ibase_maintain_db — Execute a maintenance command on the database server
  - ibase_modify_user — Modify a user to a security database
  - ibase_name_result — Assigns a name to a result set
  - ibase_num_fields — Get the number of fields in a result set
  - ibase_num_params — Return the number of parameters in a prepared query
  - ibase_param_info — Return information about a parameter in a prepared query
  - ibase_pconnect — Open a persistent connection to an InterBase database
  - ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  - ibase_query — Execute a query on an InterBase database
  - ibase_restore — Initiates a restore task in the service manager and returns immediately
  - ibase_rollback — Roll back a transaction
  - ibase_rollback_ret — Roll back a transaction without closing it
  - ibase_server_info — Request information about a database server
  - ibase_service_attach — Connect to the service manager
  - ibase_service_detach — Disconnect from the service manager
  - ibase_set_event_handler — Register a callback function to be called when events are posted
  - ibase_trans — Begin a transaction
  - ibase_wait_event — Wait for an event to be posted by the database

# IBM DB2, Cloudscape and Apache Derby

# Introduction

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.

To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.

## Requirements on Linux or Unix

The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the `ibm_db2.instance_name` configuration option, or you can source the DB2 instance profile before invoking the PHP executable.

If you created a DB2 instance named `db2inst1` in /home/db2inst1/, for example, you can add the following line to php.ini:

    ibm_db2.instance_name=db2inst1

If you do not set this option in php.ini, you must issue the following command to modify your environment variables to enable access to DB2:

    bash$ source /home/db2inst1/sqllib/db2profile

To enable your PHP-enabled Web server to access these functions, you must either set the `ibm_db2.instance_name` configuration option in php.ini, or source the DB2 instance environment in your Web server start script (typically /etc/init.d/httpd or /etc/init.d/apache).

## Installation

To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on the system. DB2 does not install these by default, so it may be necessary to return to the DB2 installer and add this option. The DB2 Application Development Client includes the header files and is freely available for download from the IBM DB2 Universal Database » support site.

If the DB2 application development header files and libraries are added to a Linux or Unix operating system on which DB2 was already installed, the command db2iupdt -e must be issued to update the symbolic links to the header files and libraries in the DB2 instances.

ibm_db2 is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of the DB2 header files and libraries as follows:

    bash$ ./configure --with-IBM_DB2=/path/to/DB2

The configure command defaults to /opt/IBM/db2/V8.1.

> Note: Note for IIS users
> If the ibm_db2 driver is being used with Microsoft Internet Information Server (IIS), it may be necessary to do the following:

> - Install DB2 with extended operating system security.
> - Add the PHP binary path to the PATH system environment variable (default C:\php\).
> - Create another system environment variable equal to the path where the PHP.INI file is located (eg: PHPRC = C:\php\).
> - Add the IUSR_COMPUTERNAME to the DB2USERS group.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

ibm_db2 Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
ibm_db2.binmode | "1" | `INI_ALL` |
ibm_db2.i5_all_pconnect | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.4.9.
ibm_db2.i5_blank_userid | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_char_trim | "0" | `INI_SYSTEM` | Available as of ibm_db2 2.1.0.
ibm_db2.i5_dbcs_alloc | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.5.0.
ibm_db2.i5_guard_profile | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_ignore_userid | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.8.0.
ibm_db2.i5_job_sort | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.8.4.
ibm_db2.i5_log_verbose | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_max_pconnect | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_override_ccsid | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_servermode_subsystem | NULL | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.i5_sys_naming | "0" | `INI_SYSTEM` | Available as of ibm_db2 1.9.7.
ibm_db2.instance_name | NULL | `INI_SYSTEM` | Available as of ibm_db2 1.0.2.

Here's a short explanation of the configuration directives.

`ibm_db2.binmode` int

  This option controls the mode used for converting to and from binary data in the PHP application.

  - 1 (DB2_BINARY)
  - 2 (DB2_CONVERT)
  - 3 (DB2_PASSTHRU)
`ibm_db2.i5_all_pconnect` int

  This option forces all connections to be persistent on IBM i. Basically, all db2_connect() calls transparently become db2_pconnect() calls. By default, this option is `0`. This option is provided as a convenience for cases where persistent connections are faster. It should not be used in new applications.

  - 0 - Persistent and non-persistent connections can be made.
  - 1 - All connections are persistent.
`ibm_db2.i5_allow_commit` int

  This option controls the transaction isolation mode used. By default, this option is `0`, so commitment control isn't used. This option can be overridden when connecting if the array key `i5_commit` is set in the connection options array passed to db2_connect() or db2_pconnect().

  - 0 - commitment control is not used
  - 1 - read uncommitted, dirty reads possible.
  - 2 - read committed, dirty reads are not possible.
  - 3 - repeatable read, dirty reads and non-repeatable reads are not possible
  - 4 - serializeable, dirty reads, non-repeatable reads, and phantoms are not possible
`ibm_db2.i5_blank_userid` int

  This controls if a blank user ID should be allowed on IBM i. By default, this option is `0`. Unlike `ibm_db2.i5_ignore_userid`, this option doesn't force all user IDs to be empty or change job behaviour, but simply allows an empty user ID to be passed, for connecting to Db2 as the current user.

  - 0 - Don't allow a blank user ID to be passed.
  - 1 - Allow a blank user ID to be passed.
`ibm_db2.i5_char_trim` int

  This option controls if the end of strings are trimmed on IBM i. Since many tables use fixed column sizes padded with spaces, this is provided as a convenience. By default, this option is `0`.

  - 0 - Columns are not trimmed.
  - 1 - Spaces at the end of returned character columns are removed.
`ibm_db2.i5_dbcs_alloc` int

  This options affects the internal buffer allocation strategy on IBM i. By default, this option is `0`. When this option is set, buffers are allocated with a much larger size, in case the database underestimates a string's size when converting between encodings. This option uses six times as much memory for buffers (to account for the largest possible UTF-8 sequences), but may be needed if truncated data is returned.

  - 0 - Minimum size buffers are allocated.
  - 1 - Larger size buffers are allocated.
`ibm_db2.i5_guard_profile` int

  This option checks if the database user profile was switched when connecting to a persistent database connection on IBM i, and if so, disconnects from the database. By default, this option is set to `0`.

  - 0 - Don't check for profile swaps.
  - 1 - Check for profile swaps and disconnect if so.
`ibm_db2.i5_log_verbose` int

  This option sets if SQL diagnostic messages like warnings and errors are always sent to the PHP error log on IBM i. Normally, only a brief message on failure is sent (such as "statement execute failed") to the PHP error log, as this option is set to `0` by default. Note that you can still and should call i.e. db2_stmt_errormsg() manually as part of checking if functions fail.

  - 0 - Only logs brief messages.
  - 1 - Logs the SQL diagnostic message in addition to the brief message.
`ibm_db2.i5_ignore_userid` int

  This option ignores the user ID when connecting to the database when running on IBM i, and runs SQL/CLI functionality inside of the PHP job, instead of a separate job. By default, this option is `0`. When enabled, it no longer uses a separate database server job, and always uses the current user profile for the database, ignoring the username and password passed to db2_connect() and db2_pconnect().

  - 0 - Uses the specified credentials, and use an SQL/CLI server job.
  - 1 - Always use blank credentials, and run SQL/CLI in the PHP job.
`ibm_db2.i5_job_sort` int

  Controls the job sort option on IBM i. By default, this option is `0`. This corresponds to the IBM i SQL/CLI `SQL_ATTR_CONN_SORT_SEQUENCE` attribute.

  - 0 - Uses the `*HEX` sort option, sorting by bytes.
  - 1 - Uses the job sort sequence set for the PHP job.
  - 2 - Uses the job sort sequence set for the database job.
`ibm_db2.i5_max_pconnect` int
  This will affect how many times a persistent connection can be reused when running on IBM i. By default, this is set to `0`, which means a persistent connection can always be reused. This option can help work around issues in a long-running database job (i.e. if a procedure is leaking memory), but is obviously not a long-term fix.
`ibm_db2.i5_override_ccsid` int
  The PASE CCSID to use for character conversions from EBCDIC on IBM i. By default, this is `0`, which will select the default PASE job CCSID, which comes from the PASE locale settings. For example, setting this to `1208` will use UTF-8. This should only be modified if the PASE job CCSID isn't the expected CCSID, and the locale cannot be modified. To learn more about CCSIDs on IBM i, consult the » IBM documentation. To learn how locales on IBM i PASE are mapped to CCSIDs, consult the » IBM documentation.
`ibm_db2.i5_sys_naming` int

  This option controls the naming mode when connecting to an IBM i system. By default, this option is `0`. The naming mode affects how names are resolved and the allowed syntax for names. When set to `0`, this uses periods to qualify names and uses the default library or user ID to resolve names. When set to `1`, this uses slashes to qualify names and uses the job library list to resolve names.

  - 0 - Uses the SQL naming mode ("SCHEMA.TABLE").
  - 1 - Uses the system naming mode ("LIBRARY/FILE").
  To learn more about naming modes on IBM i, consult the » IBM documentation.
`ibm_db2.i5_servermode-subsystem` string
  This option changes which subsystem database server jobs run under on IBM i. By default, this option is `null`, so jobs will run under the default subsystem for QSQSRVR jobs.
`ibm_db2.instance_name` string

  On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. By default, this option is `null`. If this option is set, its value overrides the DB2INSTANCE environment variable setting.

  This option is ignored on Windows operating systems.

## Resource Types

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

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

`DB2_BINARY` (int)
  Specifies that binary data shall be returned as is. This is the default mode.
`DB2_CONVERT` (int)
  Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
`DB2_PASSTHRU` (int)
  Specifies that binary data shall be converted to a `null` value.
`DB2_SCROLLABLE` (int)
  Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
`DB2_FORWARD_ONLY` (int)
  Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
`DB2_PARAM_IN` (int)
  Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
`DB2_PARAM_OUT` (int)
  Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
`DB2_PARAM_INOUT` (int)
  Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
`DB2_PARAM_FILE` (int)
  Specifies that the column should be bound directly to a file for input.
`DB2_AUTOCOMMIT_ON` (int)
  Specifies that autocommit should be turned on.
`DB2_AUTOCOMMIT_OFF` (int)
  Specifies that autocommit should be turned off.
`DB2_DOUBLE` (int)
  Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
`DB2_LONG` (int)
  Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
`DB2_CHAR` (int)
  Specifies that the variable should be bound as a CHAR or VARCHAR data type.
`DB2_CASE_NATURAL` (int)
  Specifies that column names will be returned in their natural case.
`DB2_CASE_LOWER` (int)
  Specifies that column names will be returned in lower case.
`DB2_CASE_UPPER` (int)
  Specifies that column names will be returned in upper case.
`DB2_DEFERRED_PREPARE_ON` (int)
  Specifies that deferred prepare should be turned on for the specified statement resource.
`DB2_DEFERRED_PREPARE_OFF` (int)
  Specifies that deferred prepare should be turned off for the specified statement resource.

# IBM DB2 Functions

# db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

### Description

db2_autocommit(resource `$connection`, int `$value` = ?): int|bool

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

### Parameters

`connection`
  A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
`value`

  One of the following constants:

  `DB2_AUTOCOMMIT_OFF`
    Turns AUTOCOMMIT off.
  `DB2_AUTOCOMMIT_ON`
    Turns AUTOCOMMIT on.

### Return Values

When db2_autocommit() receives only the `connection` parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of `DB2_AUTOCOMMIT_OFF` indicates that AUTOCOMMIT is off, while a value of `DB2_AUTOCOMMIT_ON` indicates that AUTOCOMMIT is on.

When db2_autocommit() receives both the `connection` parameter and `autocommit` parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Returns `true` on success or `false` on failure.

### Examples

Example #1 Retrieving the AUTOCOMMIT value for a connection

In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.

`<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == DB2_AUTOCOMMIT_OFF) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>`

The above example will output:

    0 -- AUTOCOMMIT is off.

Example #2 Setting the AUTOCOMMIT value for a connection

In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.

`<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
print "Turning AUTOCOMMIT on succeeded.\n";
}
// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == DB2_AUTOCOMMIT_OFF) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>`

The above example will output:

    Turning AUTOCOMMIT on succeeded.
    1 -- AUTOCOMMIT is on.

### See Also

- db2_connect() - Returns a connection to a database
- db2_pconnect() - Returns a persistent connection to a database

# db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

### Description

db2_bind_param(
resource `$stmt`,
int `$parameter_number`,
string `$variable_name`,
int `$parameter_type` = `DB2_PARAM_IN`,
int `$data_type` = 0,
int `$precision` = -1,
int `$scale` = 0
): bool

Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().

### Parameters

`stmt`
  A prepared statement returned from db2_prepare().
`parameter_number`
  Specifies the 1-indexed position of the parameter in the prepared statement.
`variable_name`
  A string specifying the name of the PHP variable to bind to the parameter specified by `parameter_number`.
`parameter_type`
  A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (`DB2_PARAM_IN`), an output parameter (`DB2_PARAM_OUT`), or as a parameter that accepts input and returns output (`DB2_PARAM_INOUT`). To avoid memory overhead, you can also specify `DB2_PARAM_FILE` to bind the PHP variable to the name of a file that contains large object (BLOB, CLOB, or DBCLOB) data.
`data_type`
  A constant specifying the SQL data type that the PHP variable should be bound as: one of `DB2_BINARY`, `DB2_CHAR`, `DB2_DOUBLE`, or `DB2_LONG` .
`precision`
  Specifies the precision with which the variable should be bound to the database. This parameter can also be used for retrieving XML output values from stored procedures. A non-negative value specifies the maximum size of the XML data that will be retrieved from the database. If this parameter is not used, a default of 1MB will be assumed for retrieving the XML output value from the stored procedure.
`scale`
  Specifies the scale with which the variable should be bound to the database.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Binding PHP variables to a prepared statement

The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, `$lower_limit` is assigned a value before the call to db2_bind_param(), but `$upper_limit` is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().

`<?php
$sql = 'SELECT name, breed, weight FROM animals
WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);
// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;
db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);
// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;
if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
print "{$row[0]}, {$row[1]}, {$row[2]}\n";
}
}
?>`

The above example will output:

    Pook, cat, 3.2
    Rickety Ride, goat, 9.7
    Peaches, dog, 12.3

Example #2 Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

1. an input (IN) parameter that accepts the name of the first animal as input
2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string `TRUE` if an animal in the database matches that name
3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.
`<?php
$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);
$name = "Peaches";
$second_name = "Rickety Ride";
$weight = 0;
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);
print "Values of bound parameters _before_ CALL:\n";
print " 1: {$name} 2: {$second_name} 3: {$weight}\n\n";
if (db2_execute($stmt)) {
print "Values of bound parameters _after_ CALL:\n";
print " 1: {$name} 2: {$second_name} 3: {$weight}\n\n";
print "Results:\n";
while ($row = db2_fetch_array($stmt)) {
print " {$row[0]}, {$row[1]}, {$row[2]}\n";
}
}
?>`

The above example will output:

    Values of bound parameters _before_ CALL:
      1: Peaches 2: Rickety Ride 3: 0

    Values of bound parameters _after_ CALL:
      1: Peaches 2: TRUE 3: 22

    Results:
      Peaches, dog, 12.3
      Pook, cat, 3.2
      Rickety Ride, goat, 9.7

Example #3 Inserting a binary large object (BLOB) directly from a file

The data for large objects are typically stored in files, such as XML documents or audio files. Rather than reading an entire file into a PHP variable, and then binding that PHP variable into an SQL statement, you can avoid some memory overhead by binding the file directly to the input parameter of your SQL statement. The following example demonstrates how to bind a file directly into a BLOB column.

`<?php
$stmt = db2_prepare($conn, "INSERT INTO animal_pictures(picture) VALUES (?)");
$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
?>`

### See Also

- db2_execute() - Executes a prepared SQL statement
- db2_prepare() - Prepares an SQL statement to be executed

# db2_client_info

(PECL ibm_db2 >= 1.1.1)

db2_client_info — Returns an object with properties that describe the DB2 database client

### Description

db2_client_info(resource `$connection`): stdClass|false

This function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:

DB2 client properties
Property name | Return type | Description
--- | --- | ---
APPL_CODEPAGE | int | The application code page.
CONN_CODEPAGE | int | The code page for the current connection.
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database.
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51".
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
ODBC_SQL_CONFORMANCE | string | The level of ODBC SQL grammar supported by the client: MINIMUM Supports the minimum ODBC SQL grammar. CORE Supports the core ODBC SQL grammar. EXTENDED Supports extended ODBC SQL grammar.
ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000".

### Parameters

`connection`
  Specifies an active DB2 client connection.

### Return Values

Returns an object on a successful call, or `false` on failure

### Examples

Example #1 A db2_client_info() example

To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().

`<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );
if ($client) {
echo "DRIVER_NAME: "; var_dump( $client->DRIVER_NAME );
echo "DRIVER_VER: "; var_dump( $client->DRIVER_VER );
echo "DATA_SOURCE_NAME: "; var_dump( $client->DATA_SOURCE_NAME );
echo "DRIVER_ODBC_VER: "; var_dump( $client->DRIVER_ODBC_VER );
echo "ODBC_VER: "; var_dump( $client->ODBC_VER );
echo "ODBC_SQL_CONFORMANCE: "; var_dump( $client->ODBC_SQL_CONFORMANCE );
echo "APPL_CODEPAGE: "; var_dump( $client->APPL_CODEPAGE );
echo "CONN_CODEPAGE: "; var_dump( $client->CONN_CODEPAGE );
}
else {
echo "Error retrieving client information.
Perhaps your database connection was invalid.";
}
db2_close($conn);
?>`

The above example will output:

    DRIVER_NAME: string(8) "libdb2.a"
    DRIVER_VER: string(10) "08.02.0001"
    DATA_SOURCE_NAME: string(6) "SAMPLE"
    DRIVER_ODBC_VER: string(5) "03.51"
    ODBC_VER: string(10) "03.01.0000"
    ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
    APPL_CODEPAGE: int(819)
    CONN_CODEPAGE: int(819)

### See Also

- db2_server_info() - Returns an object with properties that describe the DB2 database server

# db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

### Description

db2_close(resource `$connection`): bool

This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.

If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.

### Parameters

`connection`
  Specifies an active DB2 client connection.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Closing a connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.

`<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
echo "Connection was successfully closed.";
}
?>`

The above example will output:

    Connection was successfully closed.

### See Also

- db2_connect() - Returns a connection to a database
- db2_pclose() - Closes a persistent database connection
- db2_pconnect() - Returns a persistent connection to a database

# db2_column_privileges

(PECL ibm_db2 >= 1.0.0)

db2_column_privileges — Returns a result set listing the columns and associated privileges for a table

### Description

db2_column_privileges(
resource `$connection`,
?string `$qualifier` = `null`,
?string `$schema` = `null`,
?string `$table_name` = `null`,
?string `$column_name` = `null`
): resource

Returns a result set listing the columns and associated privileges for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. To match all schemas, pass `null` or an empty string.
`table_name`
  The name of the table or view. To match all tables in the database, pass `null` or an empty string.
`column_name`
  The name of the column. To match all columns in the table, pass `null` or an empty string.

### Return Values

Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege for the column.
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users.

### See Also

- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_columns

(PECL ibm_db2 >= 1.0.0)

db2_columns — Returns a result set listing the columns and associated metadata for a table

### Description

db2_columns(
resource `$connection`,
?string `$qualifier` = `null`,
?string `$schema` = `null`,
?string `$table_name` = `null`,
?string `$column_name` = `null`
): resource

Returns a result set listing the columns and associated metadata for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. To match all schemas, pass `'%'`.
`table_name`
  The name of the table or view. To match all tables in the database, pass `null` or an empty string.
`column_name`
  The name of the column. To match all columns in the table, pass `null` or an empty string.

### Return Values

Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
DATA_TYPE | The SQL data type for the column represented as an integer value.
TYPE_NAME | A string representing the data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or `null` where scale is not applicable.
NUM_PREC_RADIX | An integer value of either `10` (representing an exact numeric data type), `2` (representing an approximate numeric data type), or `null` (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the column is nullable or not.
REMARKS | Description of the column.
COLUMN_DEF | Default value for the column.
SQL_DATA_TYPE | An integer value representing the size of the column.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or `null` for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or `null` for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the column in the table.
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_commit

(PECL ibm_db2 >= 1.0.0)

db2_commit — Commits a transaction

### Description

db2_commit(resource `$connection`): bool

Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.

### Parameters

`connection`
  A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
- db2_rollback() - Rolls back a transaction

# db2_conn_error

(PECL ibm_db2 >= 1.0.0)

db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt

### Description

db2_conn_error(?resource `$connection` = `null`): string

db2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns `false` in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.

If, however, the connection was successful but becomes invalid over time, you can pass the `connection` parameter to retrieve the SQLSTATE value for a specific connection.

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: `db2 '? `sqlstate-value`'`. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

### Parameters

`connection`
  A connection resource associated with a connection that initially succeeded, but which over time became invalid.

### Return Values

Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.

### Examples

Example #1 Retrieving an SQLSTATE value for a failed connection attempt

The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().

`<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
print "SQLSTATE value: " . db2_conn_error();
}
?>`

The above example will output:

    SQLSTATE value: 08001

### See Also

- db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
- db2_connect() - Returns a connection to a database
- db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
- db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

# db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

### Description

db2_conn_errormsg(?resource `$connection` = `null`): string

db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns `false` in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.

If, however, the connection was successful but becomes invalid over time, you can pass the `connection` parameter to retrieve the associated error message and SQLCODE value for a specific connection.

### Parameters

`connection`
  A connection resource associated with a connection that initially succeeded, but which over time became invalid.

### Return Values

Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.

### Examples

Example #1 Retrieving the error message returned by a failed connection attempt

The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().

`<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
print db2_conn_errormsg();
}
?>`

The above example will output:

    [IBM][CLI Driver] SQL1013N  The database alias name
    or database name "BADNAME" could not be found.  SQLSTATE=42705
     SQLCODE=-1013

### See Also

- db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
- db2_connect() - Returns a connection to a database
- db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
- db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

# db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

### Description

db2_connect(
string `$database`,
?string `$username`,
?string `$password`,
array `$options` = []
): resource|false

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

### Parameters

`database`
  For a cataloged connection to a database, `database` represents the database alias in the DB2 client catalog.

  For an uncataloged connection to a database, `database` represents a complete connection string in the following format:

      DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;

  > Note:

  > When connecting to Db2 on IBM i, the underlying system calls » SQLDriverConnect, which only accepts DSN, UID, and PWD for the » connection string. Like so:

  >     DSN=database;UID=username;PWD=password;

  where the parameters represent the following values:
  `database`
    The name of the database.
  `hostname`
    The hostname or IP address of the database server.
  `port`
    The TCP/IP port on which the database is listening for requests.
  `username`
    The username with which you are connecting to the database.
  `password`
    The password with which you are connecting to the database.
`username`
  The username with which you are connecting to the database. For uncataloged connections, you must pass a `null` value or empty string.
`password`
  The password with which you are connecting to the database. For uncataloged connections, you must pass a `null` value or empty string.
`options`

  An associative array of connection options that affect the behavior of the connection, where valid array keys include:

  `autocommit`
    Passing the `DB2_AUTOCOMMIT_ON` value turns autocommit on for this connection handle. Passing the `DB2_AUTOCOMMIT_OFF` value turns autocommit off for this connection handle.
  `DB2_ATTR_CASE`
    Passing the `DB2_CASE_NATURAL` value specifies that column names are returned in natural case. Passing the `DB2_CASE_LOWER` value specifies that column names are returned in lower case. Passing the `DB2_CASE_UPPER` value specifies that column names are returned in upper case.
  `CURSOR`
    Passing the `DB2_FORWARD_ONLY` value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers. Passing the `DB2_SCROLLABLE` value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

  The following new option is available in ibm_db2 version 1.7.0 and later.

  `trustedcontext`
    Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option(). This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection. To catalog the database, use following commands:

        db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
        db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
        db2 "update dbm cfg using svcename <SERVICENAME>"
        db2set DB2COMM=TCPIP

  The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

  `i5_lib`
    A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.
  `i5_naming`
    `DB2_I5_NAMING_ON` value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job. `DB2_I5_NAMING_OFF` value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.
  `i5_commit`

    The `i5_commit` attribute should be set before the db2_connect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_connect() for the connection handle.

    > Note: The php.ini setting `ibm_db2.i5_allow_commit`==0 or `DB2_I5_TXN_NO_COMMIT` is the default, but may be overridden with the `i5_commit` option.

    `DB2_I5_TXN_NO_COMMIT` - Commitment control is not used. `DB2_I5_TXN_READ_UNCOMMITTED` - Dirty reads, nonrepeatable reads, and phantoms are possible. `DB2_I5_TXN_READ_COMMITTED` - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible. `DB2_I5_TXN_REPEATABLE_READ` - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible. `DB2_I5_TXN_SERIALIZABLE` - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible
  `i5_query_optimize`
    `DB2_FIRST_IO` All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. `DB2_ALL_IO` All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.
  `i5_dbcs_alloc`
    `DB2_I5_DBCS_ALLOC_ON` value turns on DB2 6X allocation scheme for DBCS translation column size growth. `DB2_I5_DBCS_ALLOC_OFF` value turns off DB2 6X allocation scheme for DBCS translation column size growth. Note: php.ini setting `ibm_db2.i5_dbcs_alloc`==0 or `DB2_I5_DBCS_ALLOC_OFF` is the default, but may be overridden with the `i5_dbcs_alloc` option.
  `i5_date_fmt`
    `DB2_I5_FMT_ISO` - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default. `DB2_I5_FMT_USA` - The United States date format mm/dd/yyyy is used. `DB2_I5_FMT_EUR` - The European date format dd.mm.yyyy is used. `DB2_I5_FMT_JIS` - The Japanese Industrial Standard date format yyyy-mm-dd is used. `DB2_I5_FMT_MDY` - The date format mm/dd/yyyy is used. `DB2_I5_FMT_DMY` - The date format dd/mm/yyyy is used. `DB2_I5_FMT_YMD` - The date format yy/mm/dd is used. `DB2_I5_FMT_JUL` - The Julian date format yy/ddd is used. `DB2_I5_FMT_JOB` - The job default is used.
  `i5_date_sep`
    `DB2_I5_SEP_SLASH` - A slash ( / ) is used as the date separator. This is the default. `DB2_I5_SEP_DASH` - A dash ( - ) is used as the date separator. `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the date separator. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the date separator. `DB2_I5_SEP_BLANK` - A blank is used as the date separator. `DB2_I5_SEP_JOB` - The job default is used
  `i5_time_fmt`
    `DB2_I5_FMT_ISO` - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default. `DB2_I5_FMT_USA` - The United States time format hh:mmxx is used, where xx is AM or PM. `DB2_I5_FMT_EUR` - The European time format hh.mm.ss is used. `DB2_I5_FMT_JIS` - The Japanese Industrial Standard time format hh:mm:ss is used. `DB2_I5_FMT_HMS` - The hh:mm:ss format is used.
  `i5_time_sep`
    `DB2_I5_SEP_COLON` - A colon ( : ) is used as the time separator. This is the default. `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the time separator. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the time separator. `DB2_I5_SEP_BLANK` - A blank is used as the time separator. `DB2_I5_SEP_JOB` - The job default is used.
  `i5_decimal_sep`
    `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the decimal separator. This is the default. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the decimal separator. `DB2_I5_SEP_JOB` - The job default is used.

  The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

  `i5_libl`
    A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

    > Note: `i5_libl` calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

### Return Values

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns `false`.

### Examples

Example #1 Creating a cataloged connection

Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.

`<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$conn = db2_connect($database, $user, $password);
if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>`

The above example will output:

    Connection succeeded.

Example #2 Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

`<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');
if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>`

The above example will output:

    Connection succeeded.

Example #3 Creating a connection with autocommit off by default

Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.

`<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
if ($conn) {
echo "Connection succeeded.\n";
if (db2_autocommit($conn)) {
echo "Autocommit is on.\n";
}
else {
echo "Autocommit is off.\n";
}
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>`

The above example will output:

    Connection succeeded.
    Autocommit is off.

Example #4 i5/OS best performance

To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application use the default host, userid, and password for your db2_connect().

`<?php
$library = "ADC";
$i5 = db2_connect("", "", "", array("i5_lib"=>"qsys2"));
$result = db2_exec($i5,
"select * from systables where table_schema = '$library'");
while ($row = db2_fetch_both($result)) {
echo $row['TABLE_NAME']."</br>";
}
db2_close($i5);
?>`

The above example will output:

    ANIMALS
    NAMES
    PICTURES

Example #5 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

`<?php
$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";
$tc_user = "tcuser";
$tc_pass = "tcpassword";
$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);
$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";
if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");
//Do some work as user 1.
//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);
$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.
if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}
db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>`

The above example will output:

    Explicit trusted connection succeeded.
    User has been switched.

### See Also

- db2_close() - Closes a database connection
- db2_pconnect() - Returns a persistent connection to a database

# db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

### Description

db2_cursor_type(resource `$stmt`): int

Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.

### Parameters

`stmt`
  A valid statement resource.

### Return Values

Returns either `DB2_FORWARD_ONLY` if the statement resource uses a forward-only cursor or `DB2_SCROLLABLE` if the statement resource uses a scrollable cursor.

### See Also

- db2_prepare() - Prepares an SQL statement to be executed

# db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

### Description

db2_escape_string(string `$string_literal`): string

Prepends backslashes to special characters in the string argument.

### Parameters

`string_literal`
  The string that contains special characters that need to be modified. Characters that are prepended with a backslash are `\x00`, `\n`, `\r`, `\`, `'`, `"` and `\x1a`.

### Return Values

Returns `string_literal` with the special characters noted above prepended with backslashes.

### Examples

Example #1 A db2_escape_string() example

Result of using the db2_escape_string() function

`<?php
$conn = db2_connect($database, $user, $password);
if ($conn) {
$str[0] = "All characters: \x00 , \n , \r , \ , ' , \" , \x1a .";
$str[1] = "Backslash (\). Single quote ('). Double quote (\")";
$str[2] = "The NULL character \0 must be quoted as well";
$str[3] = "Intersting characters: \x1a , \x00 .";
$str[4] = "Nothing to quote";
$str[5] = 200676;
$str[6] = "";
foreach( $str as $string ) {
echo "db2_escape_string: " . db2_escape_string($string). "\n";
}
}
?>`

The above example will output:

    db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
    db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
    db2_escape_string: The NULL character \0 must be quoted as well
    db2_escape_string: Intersting characters: \Z , \0 .
    db2_escape_string: Nothing to quote
    db2_escape_string: 200676
    db2_escape_string:

### See Also

- db2_prepare() - Prepares an SQL statement to be executed

# db2_exec

(PECL ibm_db2 >= 1.0.0)

db2_exec — Executes an SQL statement directly

### Description

db2_exec(resource `$connection`, string `$statement`, array `$options` = []): resource|false

Executes an SQL statement directly.

If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.

If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.

### Parameters

`connection`
  A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
`statement`
  An SQL statement. The statement cannot contain any parameter markers.
`options`
  An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality. For a description of valid statement options, see db2_set_option().

### Return Values

Returns a statement resource if the SQL statement was issued successfully, or `false` if the database failed to execute the SQL statement.

### Examples

Example #1 Creating a table with db2_exec()

The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.

`<?php
$conn = db2_connect($database, $user, $password);
// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
print "Successfully created the table.\n";
}
// Populate the test table
$animals = array(
array(0, 'cat', 'Pook', 3.2),
array(1, 'dog', 'Peaches', 12.3),
array(2, 'horse', 'Smarty', 350.0),
array(3, 'gold fish', 'Bubbles', 0.1),
array(4, 'budgerigar', 'Gizmo', 0.2),
array(5, 'goat', 'Rickety Ride', 9.7),
array(6, 'llama', 'Sweater', 150)
);
foreach ($animals as $animal) {
$rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
if ($rc) {
print "Insert... ";
}
}
?>`

The above example will output:

    Successfully created the table.
    Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Example #2 Executing a SELECT statement with a scrollable cursor

The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().

`<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
WHERE weight < 10.0
ORDER BY name";
if ($conn) {
require_once 'prepare.inc';
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)) {
print "$row[0]\n";
}
}
?>`

The above example will output:

    Bubbles
    Gizmo
    Pook
    Rickety Ride

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = 'SELECT * FROM XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" VARCHAR (50) PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) AS T
WHERE NAME = \'Kathy Smith\'
';
$stmt = db2_exec($conn, $query);
while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE\n");
}
db2_close($conn);
?>`

The above example will output:

    1000     Kathy Smith     416-555-1358
    1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM" BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
B.POID = C.PONUM AND
A.NAME = \'Kathy Smith\'
';
$stmt = db2_exec($conn, $query);
while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}
db2_close($conn);
?>`

The above example will output:

    1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
declare boundary-space strip;
declare default element namespace "http://posample.org";
<promoList> {
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
<promoitem> {
$prod,
<startdate> {$start} </startdate>,
<enddate> {$end} </enddate>,
<promoprice> {$promo} </promoprice>
} </promoitem>
)
} </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';
$stmt = db2_exec($conn, $query);
while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
db2_close($conn);
?>`

The above example will output:

    <promoList xmlns="http://posample.org">
        <promoitem>
        <product pid="100-100-01">
            <description>
                <name>Snow Shovel, Basic 22 inch</name>
                <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
                <price>9.99</price>
                <weight>1 kg</weight>
            </description>
        </product>
        <startdate>2004-11-19</startdate>
        <enddate>2004-12-19</enddate>
        <promoprice>7.25</promoprice>
        </promoitem>
    </promoList>

### See Also

- db2_execute() - Executes a prepared SQL statement
- db2_prepare() - Prepares an SQL statement to be executed

# db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

### Description

db2_execute(resource `$stmt`, array `$parameters` = []): bool

db2_execute() executes an SQL statement that was prepared by db2_prepare().

If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the `stmt` resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().

Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().

### Parameters

`stmt`
  A prepared statement returned from db2_prepare().
`parameters`
  An array of input parameters matching any parameter markers contained in the prepared statement.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

`<?php
$pet = array(0, 'cat', 'Pook', 3.2);
$insert = 'INSERT INTO animals (id, breed, name, weight)
VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
$result = db2_execute($stmt, $pet);
if ($result) {
print "Successfully added new pet.";
}
}
?>`

The above example will output:

    Successfully added new pet.

Example #2 Calling a stored procedure with an OUT parameter

The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable `$my_pets` to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of `$num_pets` changes to reflect the value returned by the stored procedure for that OUT parameter.

`<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>`

The above example will output:

    I have 7 pets!

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = 'SELECT * FROM XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" VARCHAR (50) PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) AS T
WHERE NAME = ?
';
$stmt = db2_prepare($conn, $query);
$name = 'Kathy Smith';
if ($stmt) {
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_execute($stmt);
while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE\n");
}
}
db2_close($conn);
?>`

The above example will output:

    1000     Kathy Smith     416-555-1358
    1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM" BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
B.POID = C.PONUM AND
A.NAME = ?
';
$stmt = db2_prepare($conn, $query);
$name = 'Kathy Smith';
if ($stmt) {
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_execute($stmt);
while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}
}
db2_close($conn);
?>`

The above example will output:

    1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

`<?php
$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");
$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
declare boundary-space strip;
declare default element namespace "http://posample.org";
<promoList> {
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
<promoitem> {
$prod,
<startdate> {$start} </startdate>,
<enddate> {$end} </enddate>,
<promoprice> {$promo} </promoprice>
} </promoitem>
)
} </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';
$stmt = db2_prepare($conn, $query);
$pid = "100-100-01";
if ($stmt) {
db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
db2_execute($stmt);
while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
}
db2_close($conn);
?>`

The above example will output:

    <promoList xmlns="http://posample.org">
        <promoitem>
        <product pid="100-100-01">
            <description>
                <name>Snow Shovel, Basic 22 inch</name>
                <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
                <price>9.99</price>
                <weight>1 kg</weight>
            </description>
        </product>
        <startdate>2004-11-19</startdate>
        <enddate>2004-12-19</enddate>
        <promoprice>7.25</promoprice>
        </promoitem>
    </promoList>

### See Also

- db2_exec() - Executes an SQL statement directly
- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_prepare() - Prepares an SQL statement to be executed
- db2_result() - Returns a single column from a row in the result set

# db2_fetch_array

(PECL ibm_db2 >= 1.0.1)

db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set

### Description

db2_fetch_array(resource `$stmt`, int `$row_number` = -1): array|false

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

### Parameters

`stmt`
  A valid `stmt` resource containing a result set.
`row_number`
  Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

### Return Values

Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns `false` if there are no rows left in the result set, or if the row requested by `row_number` does not exist in the result set.

### Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
while ($row = db2_fetch_array($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row[1], $row[2], $row[3]);
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_array() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_array() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_array($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row[1], $row[2], $row[3]);
$i = $i + 2;
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

### See Also

- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_object() - Returns an object with properties representing columns in the fetched row
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_result() - Returns a single column from a row in the result set

# db2_fetch_assoc

(PECL ibm_db2 >= 1.0.0)

db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set

### Description

db2_fetch_assoc(resource `$stmt`, int `$row_number` = -1): array|false

Returns an array, indexed by column name, representing a row in a result set.

### Parameters

`stmt`
  A valid `stmt` resource containing a result set.
`row_number`
  Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

### Return Values

Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns `false` if there are no rows left in the result set, or if the row requested by `row_number` does not exist in the result set.

### Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
while ($row = db2_fetch_assoc($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
$i = $i + 2;
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

### See Also

- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_object() - Returns an object with properties representing columns in the fetched row
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_result() - Returns a single column from a row in the result set

# db2_fetch_both

(PECL ibm_db2 >= 1.0.0)

db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set

### Description

db2_fetch_both(resource `$stmt`, int `$row_number` = -1): array|false

Returns an array, indexed by both column name and position, representing a row in a result set. Note that the row returned by db2_fetch_both() requires more memory than the single-indexed arrays returned by db2_fetch_assoc() or db2_fetch_array().

### Parameters

`stmt`
  A valid `stmt` resource containing a result set.
`row_number`
  Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

### Return Values

Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns `false` if there are no rows left in the result set, or if the row requested by `row_number` does not exist in the result set.

### Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
while ($row = db2_fetch_both($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_both() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_both($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row['NAME'], $row[2], $row['WEIGHT']);
$i = $i + 2;
}
?>`

The above example will output:

    0     Pook             cat                                    3.20
    5     Rickety Ride     goat                                   9.70
    2     Smarty           horse                                350.00

### See Also

- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_object() - Returns an object with properties representing columns in the fetched row
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_result() - Returns a single column from a row in the result set

# db2_fetch_object

(PECL ibm_db2 >= 1.0.0)

db2_fetch_object — Returns an object with properties representing columns in the fetched row

### Description

db2_fetch_object(resource `$stmt`, int `$row_number` = -1): stdClass|false

Returns an object in which each property represents a column returned in the row fetched from a result set.

### Parameters

`stmt`
  A valid `stmt` resource containing a result set.
`row_number`
  Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

### Return Values

Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.

The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.

If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.

Returns `false` if no row was retrieved.

### Examples

Example #1 A db2_fetch_object() example

The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".

`<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT breed, RTRIM(name) AS name
FROM animals
WHERE id = ?";
if ($conn) {
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(0));
while ($pet = db2_fetch_object($stmt)) {
echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
}
db2_close($conn);
}
?>`

The above example will output:

    Come here, Pook, my little cat!

### See Also

- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_result() - Returns a single column from a row in the result set

# db2_fetch_row

(PECL ibm_db2 >= 1.0.0)

db2_fetch_row — Sets the result set pointer to the next row or requested row

### Description

db2_fetch_row(resource `$stmt`, int `$row_number` = -1): bool

Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.

To retrieve individual fields from the result set, call the db2_result() function.

Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.

### Parameters

`stmt`
  A valid `stmt` resource.
`row_number`
  With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

### Return Values

Returns `true` if the requested row exists in the result set. Returns `false` if the requested row does not exist in the result set.

### Examples

Example #1 Iterating through a result set

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

`<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
$name = db2_result($stmt, 0);
$breed = db2_result($stmt, 1);
print "$name $breed";
}
?>`

The above example will output:

    cat Pook
    gold fish Bubbles
    budgerigar Gizmo
    goat Rickety Ride

Example #2 i5/OS recommended alternatives to db2_fetch_row/db2_result

On i5/OS it is recommended that you use db2_fetch_both(), db2_fetch_array(), or db2_fetch_object() over db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have more issues with various column types in `EBCIDIC` to `ASCII` translation, including possible truncation in `DBCS` applications. You may also find the performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object() to be superior to db2_fetch_row()/db2_result().

`<?php
$conn = db2_connect("","","");
$sql = 'SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_CREATED, ROUTINE_BODY, IN_PARMS, OUT_PARMS, INOUT_PARMS, PARAMETER_STYLE, EXTERNAL_NAME, EXTERNAL_LANGUAGE FROM QSYS2.SYSROUTINES FETCH FIRST 2 ROWS ONLY';
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_both($stmt)){
echo "<br>db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)){
echo "<br>db2_fetch_array {$row[1]} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_object($stmt)){
echo "<br>db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
}
db2_close($conn);
?>`

The above example will output:

    db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
    db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
    db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
    db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
    db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
    db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000

### See Also

- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_object() - Returns an object with properties representing columns in the fetched row
- db2_result() - Returns a single column from a row in the result set

# db2_field_display_size

(PECL ibm_db2 >= 1.0.0)

db2_field_display_size — Returns the maximum number of bytes required to display a column

### Description

db2_field_display_size(resource `$stmt`, int|string `$column`): int|false

Returns the maximum number of bytes required to display a column in a result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns `false`.

### See Also

- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

### Description

db2_field_name(resource `$stmt`, int|string `$column`): string|false

Returns the name of the specified column in the result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_num

(PECL ibm_db2 >= 1.0.0)

db2_field_num — Returns the position of the named column in a result set

### Description

db2_field_num(resource `$stmt`, int|string `$column`): int|false

Returns the position of the named column in a result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_precision

(PECL ibm_db2 >= 1.0.0)

db2_field_precision — Returns the precision of the indicated column in a result set

### Description

db2_field_precision(resource `$stmt`, int|string `$column`): int|false

Returns the precision of the indicated column in a result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_scale

(PECL ibm_db2 >= 1.0.0)

db2_field_scale — Returns the scale of the indicated column in a result set

### Description

db2_field_scale(resource `$stmt`, int|string `$column`): int|false

Returns the scale of the indicated column in a result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_type

(PECL ibm_db2 >= 1.0.0)

db2_field_type — Returns the data type of the indicated column in a result set

### Description

db2_field_type(resource `$stmt`, int|string `$column`): string|false

Returns the data type of the indicated column in a result set.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_field_width

(PECL ibm_db2 >= 1.0.0)

db2_field_width — Returns the width of the current value of the indicated column in a result set

### Description

db2_field_width(resource `$stmt`, int|string `$column`): int|false

Returns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.

### Parameters

`stmt`
  Specifies a statement resource containing a result set.
`column`
  Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

### Return Values

Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns `false`.

### See Also

- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set

# db2_foreign_keys

(PECL ibm_db2 >= 1.0.0)

db2_foreign_keys — Returns a result set listing the foreign keys for a table

### Description

db2_foreign_keys(
resource `$connection`,
?string `$qualifier`,
?string `$schema`,
string `$table_name`
): resource

Returns a result set listing the foreign keys for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. If `schema` is `null`, db2_foreign_keys() matches the schema for the current connection.
`table_name`
  The name of the table.

### Return Values

Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:

Column name | Description
--- | ---
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM | Name of the schema for the table containing the primary key.
PKTABLE_NAME | Name of the table containing the primary key.
PKCOLUMN_NAME | Name of the column containing the primary key.
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key.
FKTABLE_NAME | Name of the table containing the foreign key.
FKCOLUMN_NAME | Name of the column containing the foreign key.
KEY_SEQ | 1-indexed position of the column in the key.
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE.
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE.
FK_NAME | The name of the foreign key.
PK_NAME | The name of the primary key.
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

### Description

db2_free_result(resource `$stmt`): bool

Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.

### Parameters

`stmt`
  A valid statement resource.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- db2_free_stmt() - Frees resources associated with the indicated statement resource

# db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

### Description

db2_free_stmt(resource `$stmt`): bool

Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.

### Parameters

`stmt`
  A valid statement resource.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- db2_free_result() - Frees resources associated with a result set

# db2_get_option

(PECL ibm_db2 >= 1.6.0)

db2_get_option — Retrieves an option value for a statement resource or a connection resource

### Description

db2_get_option(resource `$resource`, string `$option`): string|false

Retrieves the value of a specified option value for a statement resource or a connection resource.

### Parameters

`resource`
  A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().
`option`

  A valid statement or connection options. The following new options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be set during execution with db2_get_option().

  > Note: Prior versions of ibm_db2 do not support these new options. When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value. To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

  `userid`

    `SQL_ATTR_INFO_USERID` - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

  `acctstr`

    `SQL_ATTR_INFO_ACCTSTR` - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

  `applname`

    `SQL_ATTR_INFO_APPLNAME` - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

  `wrkstnname`

    `SQL_ATTR_INFO_WRKSTNNAME` - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
--- | --- | ---
|  | Connection | Statement | Result Set
userid | `SQL_ATTR_INFO_USERID` | X | X | -
acctstr | `SQL_ATTR_INFO_ACCTSTR` | X | X | -
applname | `SQL_ATTR_INFO_APPLNAME` | X | X | -
wrkstnname | `SQL_ATTR_INFO_WRKSTNNAME` | X | X | -

### Return Values

Returns the current setting of the connection attribute provided on success or `false` on failure.

### Examples

Example #1 Setting and retrieving parameters through a connection resource

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
/* Obtain Connection Resource */
$conn = db2_connect($database, $user, $password);
echo "Client attributes passed through connection string:\n";
/* Create the associative options array with valid key-value pairs */
/* Assign the attributes through connection string */
/* Access the options specified */
$options1 = array('userid' => 'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";
$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";
$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";
$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";
echo "Client attributes passed post-connection:\n";
/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";
$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";
$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";
$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>`

The above example will output:

    Client attributes passed through connection string:
    db2inst1
    account
    myapp
    workstation
    Client attributes passed post-connection:
    db2inst1
    account
    myapp
    workstation

### See Also

- db2_connect() - Returns a connection to a database
- db2_cursor_type() - Returns the cursor type used by a statement resource
- db2_exec() - Executes an SQL statement directly
- db2_set_option() - Set options for connection or statement resources
- db2_pconnect() - Returns a persistent connection to a database
- db2_prepare() - Prepares an SQL statement to be executed

# db2_last_insert_id

(PECL ibm_db2 >= 1.7.1)

db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection

### Description

db2_last_insert_id(resource `$resource`): ?string

Returns the auto generated ID of the last insert query that successfully executed on this connection.

The result of this function is not affected by any of the following:

- A single row INSERT statement with a VALUES clause for a table without an identity column.
- A multiple row INSERT statement with a VALUES clause.
- An INSERT statement with a fullselect.
- A ROLLBACK TO SAVEPOINT statement.

### Parameters

`resource`
  A valid connection resource as returned from db2_connect() or db2_pconnect(). The value of this parameter cannot be a statement resource or result set resource.

### Return Values

Returns the auto generated ID of last insert query that successfully executed on this connection.

### Examples

Example #1 A db2_last_insert_id() example

The following example shows how to return the auto generated ID of last insert query that successfully executed on this connection.

`<?php
$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";
$conn = db2_connect($database, $user, $password);
if($conn) {
$createTable = "CREATE TABLE lastInsertID
(id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
$insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";
$stmt = @db2_exec($conn, $createTable);
/* Checking for single row inserted. */
$stmt = db2_exec($conn, $insertTable);
$ret = db2_last_insert_id($conn);
if($ret) {
echo "Last Insert ID is : " . $ret . "\n";
} else {
echo "No Last insert ID.\n";
}
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>`

The above example will output:

    Last Insert ID is : 1

# db2_lob_read

(PECL ibm_db2 >= 1.6.0)

db2_lob_read — Gets a user defined size of LOB files with each invocation

### Description

db2_lob_read(resource `$stmt`, int `$colnum`, int `$length`): string|false

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

### Parameters

`stmt`
  A valid `stmt` resource containing LOB data.
`colnum`
  A valid column number in the result set of the `stmt` resource.
`length`
  The size of the LOB data to be retrieved from the `stmt` resource.

### Return Values

Returns the amount of data the user specifies. Returns `false` if the data cannot be retrieved.

### Examples

Example #1 Iterating through different types of data

`<?php
/* Database Connection Parameters */
$db = 'SAMPLE';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Obtain Connection Resource */
$conn = db2_connect($db,$username,$password);
if ($conn) {
$drop = 'DROP TABLE clob_stream';
$result = @db2_exec( $conn, $drop );
$create = 'CREATE TABLE clob_stream (id INTEGER, my_clob CLOB)';
$result = db2_exec( $conn, $create );
$variable = "";
$stmt = db2_prepare($conn, "INSERT INTO clob_stream (id,my_clob) VALUES (1, ?)");
$variable = "THIS IS A CLOB TEST. THIS IS A CLOB TEST.";
db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
db2_execute($stmt);
$sql = "SELECT id,my_clob FROM clob_stream";
$result = db2_prepare($conn, $sql);
db2_execute($result);
db2_fetch_row($result);
$i = 0;
/* Read LOB data */
while ($data = db2_lob_read($result, 2, 6)) {
echo "Loop $i: $data\n";
$i = $i + 1;
}
$drop = 'DROP TABLE blob_stream';
$result = @db2_exec( $conn, $drop );
$create = 'CREATE TABLE blob_stream (id INTEGER, my_blob CLOB)';
$result = db2_exec( $conn, $create );
$variable = "";
$stmt = db2_prepare($conn, "INSERT INTO blob_stream (id,my_blob) VALUES (1, ?)");
$variable = "THIS IS A BLOB TEST. THIS IS A BLOB TEST.";
db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
db2_execute($stmt);
$sql = "SELECT id,my_blob FROM blob_stream";
$result = db2_prepare($conn, $sql);
db2_execute($result);
db2_fetch_row($result);
$i = 0;
/* Read LOB data */
while ($data = db2_lob_read($result, 2, 6)) {
echo "Loop $i: $data\n";
$i = $i + 1;
}
} else {
echo 'no connection: ' . db2_conn_errormsg();
}
?>`

The above example will output:

    Loop 0: THIS I
    Loop 1: S A CL
    Loop 2: OB TES
    Loop 3: T. THI
    Loop 4: S IS A
    Loop 5:  CLOB
    Loop 6: TEST.
    Loop 0: THIS I
    Loop 1: S A BL
    Loop 2: OB TES
    Loop 3: T. THI
    Loop 4: S IS A
    Loop 5:  BLOB
    Loop 6: TEST.

### See Also

- db2_bind_param() - Binds a PHP variable to an SQL statement parameter
- db2_exec() - Executes an SQL statement directly
- db2_execute() - Executes a prepared SQL statement
- db2_fetch_row() - Sets the result set pointer to the next row or requested row
- db2_prepare() - Prepares an SQL statement to be executed
- db2_result() - Returns a single column from a row in the result set

# db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

### Description

db2_next_result(resource `$stmt`): resource|false

A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.

### Parameters

`stmt`
  A prepared statement returned from db2_exec() or db2_execute().

### Return Values

Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns `false` if the stored procedure did not return another result set.

### Examples

Example #1 Calling a stored procedure that returns multiple result sets

In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.

`<?php
$conn = db2_connect($database, $user, $password);
if ($conn) {
$stmt = db2_exec($conn, 'CALL multiResults()');
print "Fetching first result set\n";
while ($row = db2_fetch_array($stmt)) {
var_dump($row);
}
print "\nFetching second result set\n";
$res = db2_next_result($stmt);
if ($res) {
while ($row = db2_fetch_array($res)) {
var_dump($row);
}
}
print "\nFetching third result set\n";
$res2 = db2_next_result($stmt);
if ($res2) {
while ($row = db2_fetch_array($res2)) {
var_dump($row);
}
}
db2_close($conn);
}
?>`

The above example will output:

    Fetching first result set
    array(2) {
      [0]=>
      string(16) "Bubbles         "
      [1]=>
      int(3)
    }
    array(2) {
      [0]=>
      string(16) "Gizmo           "
      [1]=>
      int(4)
    }

    Fetching second result set
    array(4) {
      [0]=>
      string(16) "Sweater         "
      [1]=>
      int(6)
      [2]=>
      string(5) "llama"
      [3]=>
      string(6) "150.00"
    }
    array(4) {
      [0]=>
      string(16) "Smarty          "
      [1]=>
      int(2)
      [2]=>
      string(5) "horse"
      [3]=>
      string(6) "350.00"
    }

    Fetching third result set
    array(1) {
      [0]=>
      string(16) "Bubbles         "
    }
    array(1) {
      [0]=>
      string(16) "Gizmo           "
    }

# db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

### Description

db2_num_fields(resource `$stmt`): int|false

Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.

### Parameters

`stmt`
  A valid statement resource containing a result set.

### Return Values

Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns `false` if the statement resource is not a valid input value.

### Examples

Example #1 Retrieving the number of fields in a result set

The following example demonstrates how to retrieve the number of fields returned in a result set.

`<?php
$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);
echo "There are {$columns} columns in the result set.";
?>`

The above example will output:

    There are 4 columns in the result set.

### See Also

- db2_execute() - Executes a prepared SQL statement
- db2_field_display_size() - Returns the maximum number of bytes required to display a column
- db2_field_name() - Returns the name of the column in the result set
- db2_field_num() - Returns the position of the named column in a result set
- db2_field_precision() - Returns the precision of the indicated column in a result set
- db2_field_scale() - Returns the scale of the indicated column in a result set
- db2_field_type() - Returns the data type of the indicated column in a result set
- db2_field_width() - Returns the width of the current value of the indicated column in a result set

# db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

### Description

db2_num_rows(resource `$stmt`): int|false

Returns the number of rows deleted, inserted, or updated by an SQL statement.

To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.

If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns `false`.

> Note: If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the bool return value of the fetch functions to achieve the equivalent functionality with much better performance.

### Parameters

`stmt`
  A valid `stmt` resource containing a result set.

### Return Values

Returns the number of rows affected by the last SQL statement issued by the specified statement handle, or `false` on failure

# db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

### Description

db2_pclose(resource `$connection`): bool

This function closes a DB2 client connection created with db2_pconnect() and returns the corresponding resources to the database server.

> Note: This function is only available on i5/OS in response to i5/OS system administration requests.

If you have a persistent DB2 client connection created with db2_pconnect(), you may use this function to close the connection. To avoid substantial connection performance penalties, this function should only be used in rare cases when the persistent connection has become unresponsive or the persistent connection will not be needed for a long period of time.

### Parameters

`connection`
  Specifies an active DB2 client connection.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Closing a persistent connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2 i5/OS database.

`<?php
$conn = db2_pconnect('', '', '');
$rc = db2_pclose($conn);
if ($rc) {
echo "Connection was successfully closed.";
}
?>`

The above example will output:

    Connection was successfully closed.

### See Also

- db2_close() - Closes a database connection
- db2_pconnect() - Returns a persistent connection to a database

# db2_pconnect

(PECL ibm_db2 >= 1.0.0)

db2_pconnect — Returns a persistent connection to a database

### Description

db2_pconnect(
string `$database`,
?string `$username`,
?string `$password`,
array `$options` = []
): resource|false

Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

For more information on persistent connections, refer to Persistent Database Connections.

Calling db2_close() on a persistent connection always returns `true`, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.

Users running version 1.9.0 or later of ibm_db2 should be aware that the extension will perform a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.

### Parameters

`database`
  For a cataloged connection to a database, `database` represents the database alias in the DB2 client catalog.

  For an uncataloged connection to a database, `database` represents a complete connection string in the following format:

      DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;

  > Note:

  > When connecting to Db2 on IBM i, the underlying system calls » SQLDriverConnect, which only accepts DSN, UID, and PWD for the » connection string. Like so:

  >     DSN=database;UID=username;PWD=password;

  where the parameters represent the following values:
  `database`
    The name of the database.
  `hostname`
    The hostname or IP address of the database server.
  `port`
    The TCP/IP port on which the database is listening for requests.
  `username`
    The username with which you are connecting to the database.
  `password`
    The password with which you are connecting to the database.
`username`
  The username with which you are connecting to the database.
`password`
  The password with which you are connecting to the database.
`options`

  An associative array of connection options that affect the behavior of the connection, where valid array keys include:

  `autocommit`
    Passing the `DB2_AUTOCOMMIT_ON` value turns autocommit on for this connection handle. Passing the `DB2_AUTOCOMMIT_OFF` value turns autocommit off for this connection handle.
  `DB2_ATTR_CASE`
    Passing the `DB2_CASE_NATURAL` value specifies that column names are returned in natural case. Passing the `DB2_CASE_LOWER` value specifies that column names are returned in lower case. Passing the `DB2_CASE_UPPER` value specifies that column names are returned in upper case.
  `CURSOR`
    Passing the `DB2_FORWARD_ONLY` value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers. Passing the `DB2_SCROLLABLE` value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

  The following new option is available in ibm_db2 version 1.7.0 and later.

  `trustedcontext`
    Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option(). This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection. To catalog the database, use following commands:

        db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
        db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
        db2 "update dbm cfg using svcename <SERVICENAME>"
        db2set DB2COMM=TCPIP

  The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

  Tip

  Conflicting connection attributes used in conjunction with persistent connections can produce indeterminate results on i5/OS. Site policies should be establish for all applications using each persistent connection user profile. The default DB2_AUTOCOMMIT_ON is suggested when using persistent connections.

  `i5_lib`
    A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.
  `i5_naming`
    `DB2_I5_NAMING_ON` value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job. `DB2_I5_NAMING_OFF` value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.
  `i5_commit`

    The `i5_commit` attribute should be set before the db2_pconnect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_pconnect() for the connection handle.

    > Note: The php.ini setting `ibm_db2.i5_allow_commit`==0 or `DB2_I5_TXN_NO_COMMIT` is the default, but may be overridden with the `i5_commit` option.

    `DB2_I5_TXN_NO_COMMIT` - Commitment control is not used. `DB2_I5_TXN_READ_UNCOMMITTED` - Dirty reads, nonrepeatable reads, and phantoms are possible. `DB2_I5_TXN_READ_COMMITTED` - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible. `DB2_I5_TXN_REPEATABLE_READ` - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible. `DB2_I5_TXN_SERIALIZABLE` - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible
  `i5_query_optimize`
    `DB2_FIRST_IO` All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. `DB2_ALL_IO` All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.
  `i5_dbcs_alloc`
    `DB2_I5_DBCS_ALLOC_ON` value turns on DB2 6X allocation scheme for DBCS translation column size growth.

    `DB2_I5_DBCS_ALLOC_OFF` value turns off DB2 6X allocation scheme for DBCS translation column size growth.

    > Note: The php.ini setting `ibm_db2.i5_dbcs_alloc`==0 or `DB2_I5_DBCS_ALLOC_OFF` is the default, but may be overridden with the `i5_dbcs_alloc` option.

  `i5_date_fmt`
    `DB2_I5_FMT_ISO` - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default. `DB2_I5_FMT_USA` - The United States date format mm/dd/yyyy is used. `DB2_I5_FMT_EUR` - The European date format dd.mm.yyyy is used. `DB2_I5_FMT_JIS` - The Japanese Industrial Standard date format yyyy-mm-dd is used. `DB2_I5_FMT_MDY` - The date format mm/dd/yyyy is used. `DB2_I5_FMT_DMY` - The date format dd/mm/yyyy is used. `DB2_I5_FMT_YMD` - The date format yy/mm/dd is used. `DB2_I5_FMT_JUL` - The Julian date format yy/ddd is used. `DB2_I5_FMT_JOB` - The job default is used.
  `i5_date_sep`
    `DB2_I5_SEP_SLASH` - A slash ( / ) is used as the date separator. This is the default. `DB2_I5_SEP_DASH` - A dash ( - ) is used as the date separator. `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the date separator. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the date separator. `DB2_I5_SEP_BLANK` - A blank is used as the date separator. `DB2_I5_SEP_JOB` - The job default is used
  `i5_time_fmt`
    `DB2_I5_FMT_ISO` - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default. `DB2_I5_FMT_USA` - The United States time format hh:mmxx is used, where xx is AM or PM. `DB2_I5_FMT_EUR` - The European time format hh.mm.ss is used. `DB2_I5_FMT_JIS` - The Japanese Industrial Standard time format hh:mm:ss is used. `DB2_I5_FMT_HMS` - The hh:mm:ss format is used.
  `i5_time_sep`
    `DB2_I5_SEP_COLON` - A colon ( : ) is used as the time separator. This is the default. `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the time separator. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the time separator. `DB2_I5_SEP_BLANK` - A blank is used as the time separator. `DB2_I5_SEP_JOB` - The job default is used.
  `i5_decimal_sep`
    `DB2_I5_SEP_PERIOD` - A period ( . ) is used as the decimal separator. This is the default. `DB2_I5_SEP_COMMA` - A comma ( , ) is used as the decimal separator. `DB2_I5_SEP_JOB` - The job default is used.

  The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

  `i5_libl`

    A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

    > Note: i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

### Return Values

Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the `database`, `username`, and `password` parameters. If the connection attempt fails, db2_pconnect() returns `false`.

### Changelog

Version | Description
--- | ---
PECL ibm_db2 1.9.0 | Active transactions within a persistent connection will be rolled back at the end of each request.
PECL ibm_db2 1.8.0 | The `i5_libl` option is available for i5/OS users.
PECL ibm_db2 1.7.0 | The `trustedcontext` option is available.
PECL ibm_db2 1.5.1 | The `i5_lib`, `i5_naming`, `i5_commit`, `i5_query_optimize`, `i5_dbcs_alloc`, `i5_date_fmt`, `i5_date_sep`, `i5_time_fmt`, `i5_time_sep` and `i5_decimal_sep` options are available for i5/OS users.

### Examples

Example #1 A db2_pconnect() example

In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.

`<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$pconn = db2_pconnect($database, $user, $password);
if ($pconn) {
echo "Persistent connection succeeded.";
}
else {
echo "Persistent connection failed.";
}
$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
echo "Second persistent connection succeeded.";
}
else {
echo "Second persistent connection failed.";
}
?>`

The above example will output:

    Persistent connection succeeded.
    Second persistent connection succeeded.

Example #2 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

`<?php
$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";
$tc_user = "tcuser";
$tc_pass = "tcpassword";
$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);
$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";
if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");
//Do some work as user 1.
//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);
$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.
if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}
db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>`

The above example will output:

    Explicit trusted connection succeeded.
    User has been switched.

### See Also

- db2_connect() - Returns a connection to a database

# db2_prepare

(PECL ibm_db2 >= 1.0.0)

db2_prepare — Prepares an SQL statement to be executed

### Description

db2_prepare(resource `$connection`, string `$statement`, array `$options` = []): resource|false

db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (`?` characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().

There are three main advantages to using prepared statements in your application:

- Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.
- Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.
- Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().

### Parameters

`connection`
  A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
`statement`
  An SQL statement, optionally containing one or more parameter markers..
`options`
  An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality. For a description of valid statement options, see db2_set_option().

### Return Values

Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns `false` if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().

### Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

`<?php
$animals = array(
array(0, 'cat', 'Pook', 3.2),
array(1, 'dog', 'Peaches', 12.3),
array(2, 'horse', 'Smarty', 350.0),
);
$insert = 'INSERT INTO animals (id, breed, name, weight)
VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
foreach ($animals as $animal) {
$result = db2_execute($stmt, $animal);
}
}
?>`

### See Also

- db2_bind_param() - Binds a PHP variable to an SQL statement parameter
- db2_execute() - Executes a prepared SQL statement
- db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
- db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

# db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

### Description

db2_primary_keys(
resource `$connection`,
?string `$qualifier`,
?string `$schema`,
string `$table_name`
): resource

Returns a result set listing the primary keys for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. If `schema` is `null`, db2_primary_keys() matches the schema for the current connection.
`table_name`
  The name of the table.

### Return Values

Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema for the table containing the primary key.
TABLE_NAME | Name of the table containing the primary key.
COLUMN_NAME | Name of the column containing the primary key.
KEY_SEQ | 1-indexed position of the column in the key.
PK_NAME | The name of the primary key.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

### Description

db2_procedure_columns(
resource `$connection`,
?string `$qualifier`,
string `$schema`,
string `$procedure`,
?string `$parameter`
): resource

Returns a result set listing the parameters for one or more stored procedures.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the procedures. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`procedure`
  The name of the procedure. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`parameter`
  The name of the parameter. This parameter accepts a search pattern containing `_` and `%` as wildcards. If this parameter is `null`, all parameters for the specified stored procedures are returned.

### Return Values

Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
PROCEDURE_CAT | The catalog that contains the procedure. The value is `null` if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
COLUMN_NAME | Name of the parameter.
COLUMN_TYPE | An integer value representing the type of the parameter:
Return value | Parameter type
--- | ---
1 (SQL_PARAM_INPUT) | Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) | Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT) | Output (OUT) parameter.
DATA_TYPE | The SQL data type for the parameter represented as an integer value.
TYPE_NAME | A string representing the data type for the parameter.
COLUMN_SIZE | An integer value representing the size of the parameter.
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter.
DECIMAL_DIGITS | The scale of the parameter, or `null` where scale is not applicable.
NUM_PREC_RADIX | An integer value of either `10` (representing an exact numeric data type), `2` (representing an approximate numeric data type), or `null` (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the parameter is nullable or not.
REMARKS | Description of the parameter.
COLUMN_DEF | Default value for the parameter.
SQL_DATA_TYPE | An integer value representing the size of the parameter.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or `null` for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or `null` for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement.
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns `null` values and 'NO' means that the parameter does not accept or return `null` values.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

### Description

db2_procedures(
resource `$connection`,
?string `$qualifier`,
string `$schema`,
string `$procedure`
): resource

Returns a result set listing the stored procedures registered in a database.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the procedures. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`procedure`
  The name of the procedure. This parameter accepts a search pattern containing `_` and `%` as wildcards.

### Return Values

Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
PROCEDURE_CAT | The catalog that contains the procedure. The value is `null` if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETS | Number of result sets returned by the stored procedure.
REMARKS | Any comments about the stored procedure.
PROCEDURE_TYPE | Always returns `1`, indicating that the stored procedure does not return a return value.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

### Description

db2_result(resource `$stmt`, int|string `$column`): ?mixed

Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.

### Parameters

`stmt`
  A valid `stmt` resource.
`column`
  Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

### Return Values

Returns the value of the requested field if the field exists in the result set. Returns `null` if the field does not exist, and issues a warning.

### Examples

Example #1 A db2_result() example

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

`<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
$name = db2_result($stmt, 0);
$breed = db2_result($stmt, 'BREED');
print "$name $breed";
}
?>`

The above example will output:

    cat Pook
    gold fish Bubbles
    budgerigar Gizmo
    goat Rickety Ride

### See Also

- db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_object() - Returns an object with properties representing columns in the fetched row
- db2_fetch_row() - Sets the result set pointer to the next row or requested row

# db2_rollback

(PECL ibm_db2 >= 1.0.0)

db2_rollback — Rolls back a transaction

### Description

db2_rollback(resource `$connection`): bool

Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.

### Parameters

`connection`
  A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Rolling back a DELETE statement

In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of `0` to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.

`<?php
$conn = db2_connect($database, $user, $password);
if ($conn) {
$stmt = db2_exec($conn, "SELECT count(*) FROM animals");
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";
// Turn AUTOCOMMIT off
db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);
// Delete all rows from ANIMALS
db2_exec($conn, "DELETE FROM animals");
$stmt = db2_exec($conn, "SELECT count(*) FROM animals");
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";
// Roll back the DELETE statement
db2_rollback( $conn );
$stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";
db2_close($conn);
}
?>`

The above example will output:

    7
    0
    7

### See Also

- db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
- db2_commit() - Commits a transaction

# db2_server_info

(PECL ibm_db2 >= 1.1.1)

db2_server_info — Returns an object with properties that describe the DB2 database server

### Description

db2_server_info(resource `$connection`): stdClass|false

This function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:

Database server properties
Property name | Return type | Description
--- | --- | ---
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of `DB2` followed by the operating system on which the database server is running.
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
DB_CODEPAGE | int | The code page of the database to which you are connected.
DB_NAME | string | The name of the database to which you are connected.
DFT_ISOLATION | string | The default transaction isolation level supported by the server: UR Uncommitted read: changes are immediately visible by all concurrent transactions. CS Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction. RS Read stability: a transaction can add or remove rows matching a search condition or a pending transaction. RR Repeatable read: data affected by pending transaction is not available to other transactions. NC No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.
IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier.
INST_NAME | string | The instance on the database server that contains the database.
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDS | array | An array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSE | bool | `true` if the database server supports the use of `%` and `_` wildcard characters. `false` if the database server does not support these wildcard characters.
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNS | bool | `true` if the database server supports columns that can be defined as NOT NULL, `false` if the database server does not support columns defined as NOT NULL.
PROCEDURES | bool | `true` if the database server supports the use of the CALL statement to call stored procedures, `false` if the database server does not support the CALL statement.
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCE | string | The level of conformance to the ANSI/ISO SQL-92 specification offered by the database server: ENTRY Entry-level SQL-92 compliance. FIPS127 FIPS-127-2 transitional compliance. FULL Full level SQL-92 compliance. INTERMEDIATE Intermediate level SQL-92 compliance.

### Parameters

`connection`
  Specifies an active DB2 client connection.

### Return Values

Returns an object on a successful call, or `false` on failure

### Examples

Example #1 A db2_server_info() example

To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().

`<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
$server = db2_server_info( $conn );
if ($server) {
echo "DBMS_NAME: "; var_dump( $server->DBMS_NAME );
echo "DBMS_VER: "; var_dump( $server->DBMS_VER );
echo "DB_CODEPAGE: "; var_dump( $server->DB_CODEPAGE );
echo "DB_NAME: "; var_dump( $server->DB_NAME );
echo "INST_NAME: "; var_dump( $server->INST_NAME );
echo "SPECIAL_CHARS: "; var_dump( $server->SPECIAL_CHARS );
echo "KEYWORDS: "; var_dump( sizeof($server->KEYWORDS) );
echo "DFT_ISOLATION: "; var_dump( $server->DFT_ISOLATION );
echo "ISOLATION_OPTION: ";
$il = '';
foreach( $server->ISOLATION_OPTION as $opt )
{
$il .= $opt." ";
}
var_dump( $il );
echo "SQL_CONFORMANCE: "; var_dump( $server->SQL_CONFORMANCE );
echo "PROCEDURES: "; var_dump( $server->PROCEDURES );
echo "IDENTIFIER_QUOTE_CHAR: "; var_dump( $server->IDENTIFIER_QUOTE_CHAR );
echo "LIKE_ESCAPE_CLAUSE: "; var_dump( $server->LIKE_ESCAPE_CLAUSE );
echo "MAX_COL_NAME_LEN: "; var_dump( $server->MAX_COL_NAME_LEN );
echo "MAX_ROW_SIZE: "; var_dump( $server->MAX_ROW_SIZE );
echo "MAX_IDENTIFIER_LEN: "; var_dump( $server->MAX_IDENTIFIER_LEN );
echo "MAX_INDEX_SIZE: "; var_dump( $server->MAX_INDEX_SIZE );
echo "MAX_PROC_NAME_LEN: "; var_dump( $server->MAX_PROC_NAME_LEN );
echo "MAX_SCHEMA_NAME_LEN: "; var_dump( $server->MAX_SCHEMA_NAME_LEN );
echo "MAX_STATEMENT_LEN: "; var_dump( $server->MAX_STATEMENT_LEN );
echo "MAX_TABLE_NAME_LEN: "; var_dump( $server->MAX_TABLE_NAME_LEN );
echo "NON_NULLABLE_COLUMNS: "; var_dump( $server->NON_NULLABLE_COLUMNS );
db2_close($conn);
}
?>`

The above example will output:

    DBMS_NAME: string(9) "DB2/LINUX"
    DBMS_VER: string(10) "08.02.0000"
    DB_CODEPAGE: int(1208)
    DB_NAME: string(6) "SAMPLE"
    INST_NAME: string(8) "db2inst1"
    SPECIAL_CHARS: string(2) "@#"
    KEYWORDS: int(179)
    DFT_ISOLATION: string(2) "CS"
    ISOLATION_OPTION: string(12) "UR CS RS RR "
    SQL_CONFORMANCE: string(7) "FIPS127"
    PROCEDURES: bool(true)
    IDENTIFIER_QUOTE_CHAR: string(1) """
    LIKE_ESCAPE_CLAUSE: bool(true)
    MAX_COL_NAME_LEN: int(30)
    MAX_ROW_SIZE: int(32677)
    MAX_IDENTIFIER_LEN: int(18)
    MAX_INDEX_SIZE: int(1024)
    MAX_PROC_NAME_LEN: int(128)
    MAX_SCHEMA_NAME_LEN: int(30)
    MAX_STATEMENT_LEN: int(2097152)
    MAX_TABLE_NAME_LEN: int(128)
    NON_NULLABLE_COLUMNS: bool(true)

### See Also

- db2_client_info() - Returns an object with properties that describe the DB2 database client

# db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

### Description

db2_set_option(resource `$resource`, array `$options`, int `$type`): bool

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

### Parameters

`resource`
  A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().
`options`

  An associative array containing valid statement or connection options. This parameter can be used to change autocommit values, cursor types (scrollable or forward), and to specify the case of the column names (lower, upper, or natural) that will appear in a result set.

  `autocommit`
    Passing `DB2_AUTOCOMMIT_ON` turns autocommit on for the specified connection resource. Passing `DB2_AUTOCOMMIT_OFF` turns autocommit off for the specified connection resource.
  `cursor`
    Passing `DB2_FORWARD_ONLY` specifies a forward-only cursor for a statement resource. This is the default cursor type, and is supported by all database servers. Passing `DB2_SCROLLABLE` specifies a scrollable cursor for a statement resource. Scrollable cursors enable result set rows to be accessed in non-sequential order, but are only supported by IBM DB2 Universal Database databases.
  `binmode`
    Passing `DB2_BINARY` specifies that binary data will be returned as is. This is the default mode. This is the equivalent of setting `ibm_db2.binmode=1` in php.ini. Passing `DB2_CONVERT` specifies that binary data will be converted to hexadecimal encoding, and will be returned as such. This is the equivalent of setting `ibm_db2.binmode=2` in php.ini. Passing `DB2_PASSTHRU` specifies that binary data will be converted to `null`. This is the equivalent of setting `ibm_db2.binmode=3` in php.ini.
  `db2_attr_case`
    Passing `DB2_CASE_LOWER` specifies that column names of the result set are returned in lower case. Passing `DB2_CASE_UPPER` specifies that column names of the result set are returned in upper case. Passing `DB2_CASE_NATURAL` specifies that column names of the result set are returned in natural case.
  `deferred_prepare`
    Passing `DB2_DEFERRED_PREPARE_ON` turns deferred prepare on for the specified statement resource. Passing `DB2_DEFERRED_PREPARE_OFF` turns deferred prepare off for the specified statement resource.

  The following new i5/OS options are available in ibm_db2 version 1.5.1 and later. These options apply only when running PHP and ibm_db2 natively on i5 systems.

  `i5_fetch_only`
    `DB2_I5_FETCH_ON` - Cursors are read-only and cannot be used for positioned updates or deletes. This is the default unless `SQL_ATTR_FOR_FETCH_ONLY` environment has been set to `SQL_FALSE`. `DB2_I5_FETCH_OFF` - Cursors can be used for positioned updates and deletes.

  The following new option is available in ibm_db2 version 1.8.0 and later.

  `rowcount`
    `DB2_ROWCOUNT_PREFETCH_ON` - Client can request the full row count prior to fetching, which means that db2_num_rows() returns the number of rows selected even when a `ROLLFORWARD_ONLY` cursor is used. `DB2_ROWCOUNT_PREFETCH_OFF` - Client cannot request the full row count prior to fetching.

  The following new options are available in ibm_db2 version 1.7.0 and later.

  `trusted_user`
    To switch the user to a trusted user, pass the User ID (String) of the trusted user as the value of this key. This option can be set on a connection resource only. To use this option, trusted context must be enabled on the connection resource.
  `trusted_password`
    The password (String) that corresponds to the user specified by the trusted_user key.

  The following new options are available in ibm_db2 version 1.6.0 and later. These options provide useful tracking information that can be accessed during execution with db2_get_option().

  > Note: When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value. To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

  `userid`

    `SQL_ATTR_INFO_USERID` - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

  `acctstr`

    `SQL_ATTR_INFO_ACCTSTR` - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

  `applname`

    `SQL_ATTR_INFO_APPLNAME` - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

  `wrkstnname`

    `SQL_ATTR_INFO_WRKSTNNAME` - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

    > Note: DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

`type`
  An integer value that specifies the type of resource that was passed into the function. The type of resource and this value must correspond. Passing `1` as the value specifies that a connection resource has been passed into the function. Passing any integer not equal to `1` as the value specifies that a statement resource has been passed into the function.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
--- | --- | ---
|  | Connection | Statement | Result Set
autocommit | `DB2_AUTOCOMMIT_ON` | X | - | -
autocommit | `DB2_AUTOCOMMIT_OFF` | X | - | -
cursor | `DB2_SCROLLABLE` | - | X | -
cursor | `DB2_FORWARD_ONLY` | - | X | -
binmode | `DB2_BINARY` | X | X | -
binmode | `DB2_CONVERT` | X | X | -
binmode | `DB2_PASSTHRU` | X | X | -
db2_attr_case | `DB2_CASE_LOWER` | X | X | -
db2_attr_case | `DB2_CASE_UPPER` | X | X | -
db2_attr_case | `DB2_CASE_NATURAL` | X | X | -
deferred_prepare | `DB2_DEFERRED_PREPARE_ON` | - | X | -
deferred_prepare | `DB2_DEFERRED_PREPARE_OFF` | - | X | -
i5_fetch_only | `DB2_I5_FETCH_ON` | - | X | -
i5_fetch_only | `DB2_I5_FETCH_OFF` | - | X | -
rowcount | `DB2_ROWCOUNT_PREFETCH_ON` | - | X | -
rowcount | `DB2_ROWCOUNT_PREFETCH_OFF` | - | X | -
trusted_user | `<USER NAME> (String)` | X | - | -
trusted_password | `<PASSWORD> (String)` | X | - | -
userid | `SQL_ATTR_INFO_USERID` | X | X | -
acctstr | `SQL_ATTR_INFO_ACCTSTR` | X | X | -
applname | `SQL_ATTR_INFO_APPLNAME` | X | X | -
wrkstnname | `SQL_ATTR_INFO_WRKSTNNAME` | X | X | -

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting one parameter with a connection resource

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_ON);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Options Set Successfully

Example #2 Setting multiple parameters with a connection resource

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Options Set Successfully

Example #3 Setting multiple parameters with an invalid key

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'MY_INVALID_KEY' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Could Not Set Options

Example #4 Setting multiple parameters with an invalid value

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => 'INVALID_VALUE',
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Could Not Set Options

Example #5 Setting multiple parameters with a connection resource and the wrong type

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Could Not Set Options

Example #6 Setting multiple parameters with the wrong resource

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');
/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>`

The above example will output:

    Could Not Set Options

Example #7 Putting it all together

`<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';
/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";
/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');
/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' => DB2_CASE_LOWER,
'cursor' => DB2_SCROLLABLE);
$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');
/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));
/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '<br /><br />';
print_r(db2_fetch_assoc($stmt, 1));
?>`

The above example will output:

    Array
    (
        [empno] => 000140
        [firstnme] => HEATHER
        [midinit] => A
        [lastname] => NICHOLLS
        [workdept] => C01
        [phoneno] => 1793
        [hiredate] => 1976-12-15
        [job] => ANALYST
        [edlevel] => 18
        [sex] => F
        [birthdate] => 1946-01-19
        [salary] => 28420.00
        [bonus] => 600.00
        [comm] => 2274.00
    )

    Array
    (
        [empno] => 000130
        [firstnme] => DELORES
        [midinit] => M
        [lastname] => QUINTANA
        [workdept] => C01
        [phoneno] => 4578
        [hiredate] => 1971-07-28
        [job] => ANALYST
        [edlevel] => 16
        [sex] => F
        [birthdate] => 1925-09-15
        [salary] => 23800.00
        [bonus] => 500.00
        [comm] => 1904.00
    )

Example #8 i5/OS cursors are read-only

`<?php
$conn = db2_connect("", "", "", array("i5_lib"=>"nobody"));
$stmt = db2_prepare($conn, 'select * from names where first = ?');
$name = "first2";
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
$options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
db2_set_option($stmt,$options,0);
if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
echo "{$row[0]} {$row[1]}";
}
}
?>`

The above example will output:

    first2 last2

### See Also

- db2_connect() - Returns a connection to a database
- db2_pconnect() - Returns a persistent connection to a database
- db2_exec() - Executes an SQL statement directly
- db2_prepare() - Prepares an SQL statement to be executed
- db2_cursor_type() - Returns the cursor type used by a statement resource

# db2_special_columns

(PECL ibm_db2 >= 1.0.0)

db2_special_columns — Returns a result set listing the unique row identifier columns for a table

### Description

db2_special_columns(
resource `$connection`,
?string `$qualifier`,
string `$schema`,
string `$table_name`,
int `$scope`
): resource

Returns a result set listing the unique row identifier columns for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables.
`table_name`
  The name of the table.
`scope`

  Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

  Integer value | SQL constant | Description
  --- | --- | ---
  0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
  1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
  2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

### Return Values

Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:

Column name | Description
--- | ---
SCOPE |
Integer value | SQL constant | Description
--- | --- | ---
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.
COLUMN_NAME | Name of the unique column.
DATA_TYPE | SQL data type for the column.
TYPE_NAME | Character string representation of the SQL data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or `null` where scale is not applicable.
NUM_PREC_RADIX | An integer value of either `10` (representing an exact numeric data type), `2` (representing an approximate numeric data type), or `null` (representing a data type for which radix is not applicable).
PSEUDO_COLUMN | Always returns 1.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

### Description

db2_statistics(
resource `$connection`,
?string `$qualifier`,
?string `$schema`,
string `$table_name`,
bool `$unique`
): resource

Returns a result set listing the index and statistics for a table.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema that contains the targeted table. If this parameter is `null`, the statistics and indexes are returned for the schema of the current user.
`table_name`
  The name of the table.
`unique`
  When `unique` is `true`, the information for all indexes in the table are returned. Otherwise, only the information for unique indexes in the table are returned.

### Return Values

Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | The catalog that contains the table. The value is `null` if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
NON_UNIQUE | An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself:
Return value | Parameter type
--- | ---
0 (SQL_FALSE) | The index allows duplicate values.
1 (SQL_TRUE) | The index values must be unique.
`null` | This row is statistics information for the table itself.
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME | A string representing the name of the index.
TYPE | An integer value representing the type of information contained in this row of the result set:
Return value | Parameter type
--- | ---
0 (SQL_TABLE_STAT) | The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED) | The row contains information about a clustered index.
2 (SQL_INDEX_HASH) | The row contains information about a hashed index.
3 (SQL_INDEX_OTHER) | The row contains information about a type of index that is neither clustered nor hashed.
ORDINAL_POSITION | The 1-indexed position of the column in the index. `null` if the row contains statistics information about the table itself.
COLUMN_NAME | The name of the column in the index. `null` if the row contains statistics information about the table itself.
ASC_OR_DESC | `A` if the column is sorted in ascending order, `D` if the column is sorted in descending order, `null` if the row contains statistics information about the table itself.
CARDINALITY | If the row contains information about an index, this column contains an integer value representing the number of unique values in the index. If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table.
PAGES | If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index. If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table.
FILTER_CONDITION | Always returns `null`.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_stmt_error

(PECL ibm_db2 >= 1.0.0)

db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement

### Description

db2_stmt_error(?resource `$stmt` = `null`): string

Returns a string containing the SQLSTATE value returned by an SQL statement.

If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: `db2 '? `sqlstate-value`'`. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

### Parameters

`stmt`
  A valid statement resource.

### Return Values

Returns a string containing an SQLSTATE value.

### See Also

- db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
- db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
- db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

# db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

### Description

db2_stmt_errormsg(?resource `$stmt` = `null`): string

Returns a string containing the last SQL statement error message.

If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

### Parameters

`stmt`
  A valid statement resource.

### Return Values

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

### See Also

- db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
- db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
- db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement

# db2_table_privileges

(PECL ibm_db2 >= 1.0.0)

db2_table_privileges — Returns a result set listing the tables and associated privileges in a database

### Description

db2_table_privileges(
resource `$connection`,
?string `$qualifier` = `null`,
?string `$schema` = `null`,
?string `$table_name` = `null`
): resource

Returns a result set listing the tables and associated privileges in a database.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`table_name`
  The name of the table. This parameter accepts a search pattern containing `_` and `%` as wildcards.

### Return Values

Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | The catalog that contains the table. The value is `null` if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE.
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_tables() - Returns a result set listing the tables and associated metadata in a database

# db2_tables

(PECL ibm_db2 >= 1.0.0)

db2_tables — Returns a result set listing the tables and associated metadata in a database

### Description

db2_tables(
resource `$connection`,
?string `$qualifier` = `null`,
?string `$schema` = `null`,
?string `$table_name` = `null`,
?string `$table_type` = `null`
): resource

Returns a result set listing the tables and associated metadata in a database.

### Parameters

`connection`
  A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
`qualifier`
  A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass `null` or an empty string.
`schema`
  The schema which contains the tables. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`table_name`
  The name of the table. This parameter accepts a search pattern containing `_` and `%` as wildcards.
`table_type`
  A list of comma-delimited table type identifiers. To match all table types, pass `null` or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.

### Return Values

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
--- | ---
TABLE_CAT | The catalog that contains the table. The value is `null` if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
TABLE_TYPE | Table type identifier for the table.
REMARKS | Description of the table.

### See Also

- db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
- db2_columns() - Returns a result set listing the columns and associated metadata for a table
- db2_foreign_keys() - Returns a result set listing the foreign keys for a table
- db2_primary_keys() - Returns a result set listing primary keys for a table
- db2_procedure_columns() - Returns a result set listing stored procedure parameters
- db2_procedures() - Returns a result set listing the stored procedures registered in a database
- db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
- db2_statistics() - Returns a result set listing the index and statistics for a table
- db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database

## Table of Contents

- db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
- db2_bind_param — Binds a PHP variable to an SQL statement parameter
- db2_client_info — Returns an object with properties that describe the DB2 database client
- db2_close — Closes a database connection
- db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
- db2_columns — Returns a result set listing the columns and associated metadata for a table
- db2_commit — Commits a transaction
- db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
- db2_conn_errormsg — Returns the last connection error message and SQLCODE value
- db2_connect — Returns a connection to a database
- db2_cursor_type — Returns the cursor type used by a statement resource
- db2_escape_string — Used to escape certain characters
- db2_exec — Executes an SQL statement directly
- db2_execute — Executes a prepared SQL statement
- db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
- db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
- db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
- db2_fetch_object — Returns an object with properties representing columns in the fetched row
- db2_fetch_row — Sets the result set pointer to the next row or requested row
- db2_field_display_size — Returns the maximum number of bytes required to display a column
- db2_field_name — Returns the name of the column in the result set
- db2_field_num — Returns the position of the named column in a result set
- db2_field_precision — Returns the precision of the indicated column in a result set
- db2_field_scale — Returns the scale of the indicated column in a result set
- db2_field_type — Returns the data type of the indicated column in a result set
- db2_field_width — Returns the width of the current value of the indicated column in a result set
- db2_foreign_keys — Returns a result set listing the foreign keys for a table
- db2_free_result — Frees resources associated with a result set
- db2_free_stmt — Frees resources associated with the indicated statement resource
- db2_get_option — Retrieves an option value for a statement resource or a connection resource
- db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
- db2_lob_read — Gets a user defined size of LOB files with each invocation
- db2_next_result — Requests the next result set from a stored procedure
- db2_num_fields — Returns the number of fields contained in a result set
- db2_num_rows — Returns the number of rows affected by an SQL statement
- db2_pclose — Closes a persistent database connection
- db2_pconnect — Returns a persistent connection to a database
- db2_prepare — Prepares an SQL statement to be executed
- db2_primary_keys — Returns a result set listing primary keys for a table
- db2_procedure_columns — Returns a result set listing stored procedure parameters
- db2_procedures — Returns a result set listing the stored procedures registered in a database
- db2_result — Returns a single column from a row in the result set
- db2_rollback — Rolls back a transaction
- db2_server_info — Returns an object with properties that describe the DB2 database server
- db2_set_option — Set options for connection or statement resources
- db2_special_columns — Returns a result set listing the unique row identifier columns for a table
- db2_statistics — Returns a result set listing the index and statistics for a table
- db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
- db2_stmt_errormsg — Returns a string containing the last SQL statement error message
- db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
- db2_tables — Returns a result set listing the tables and associated metadata in a database

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- IBM DB2 Functions
  - db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
  - db2_bind_param — Binds a PHP variable to an SQL statement parameter
  - db2_client_info — Returns an object with properties that describe the DB2 database client
  - db2_close — Closes a database connection
  - db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
  - db2_columns — Returns a result set listing the columns and associated metadata for a table
  - db2_commit — Commits a transaction
  - db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
  - db2_conn_errormsg — Returns the last connection error message and SQLCODE value
  - db2_connect — Returns a connection to a database
  - db2_cursor_type — Returns the cursor type used by a statement resource
  - db2_escape_string — Used to escape certain characters
  - db2_exec — Executes an SQL statement directly
  - db2_execute — Executes a prepared SQL statement
  - db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
  - db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
  - db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
  - db2_fetch_object — Returns an object with properties representing columns in the fetched row
  - db2_fetch_row — Sets the result set pointer to the next row or requested row
  - db2_field_display_size — Returns the maximum number of bytes required to display a column
  - db2_field_name — Returns the name of the column in the result set
  - db2_field_num — Returns the position of the named column in a result set
  - db2_field_precision — Returns the precision of the indicated column in a result set
  - db2_field_scale — Returns the scale of the indicated column in a result set
  - db2_field_type — Returns the data type of the indicated column in a result set
  - db2_field_width — Returns the width of the current value of the indicated column in a result set
  - db2_foreign_keys — Returns a result set listing the foreign keys for a table
  - db2_free_result — Frees resources associated with a result set
  - db2_free_stmt — Frees resources associated with the indicated statement resource
  - db2_get_option — Retrieves an option value for a statement resource or a connection resource
  - db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
  - db2_lob_read — Gets a user defined size of LOB files with each invocation
  - db2_next_result — Requests the next result set from a stored procedure
  - db2_num_fields — Returns the number of fields contained in a result set
  - db2_num_rows — Returns the number of rows affected by an SQL statement
  - db2_pclose — Closes a persistent database connection
  - db2_pconnect — Returns a persistent connection to a database
  - db2_prepare — Prepares an SQL statement to be executed
  - db2_primary_keys — Returns a result set listing primary keys for a table
  - db2_procedure_columns — Returns a result set listing stored procedure parameters
  - db2_procedures — Returns a result set listing the stored procedures registered in a database
  - db2_result — Returns a single column from a row in the result set
  - db2_rollback — Rolls back a transaction
  - db2_server_info — Returns an object with properties that describe the DB2 database server
  - db2_set_option — Set options for connection or statement resources
  - db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  - db2_statistics — Returns a result set listing the index and statistics for a table
  - db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  - db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  - db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  - db2_tables — Returns a result set listing the tables and associated metadata in a database

# MongoDB Extension

This extension is developed atop the » libmongoc and » libbson libraries. It provides a minimal API for core driver functionality: commands, queries, writes, connection management, and BSON serialization.

Userland PHP libraries that depend on this extension may provide higher level APIs, such as query builders, individual command helper methods, and GridFS. Application developers should consider using this extension in conjunction with the » MongoDB PHP library, which implements the same higher level APIs found in MongoDB drivers for other languages. This separation of concerns allows the extension to focus on essential features for which an extension implementation is paramount for performance.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

As of version 1.21.0, the extension requires PHP 8.1 or higher. Previous versions of the extension allow compatibility with older PHP versions.

The extension requires » libbson and » libmongoc, and will use bundled versions of both libraries by default. System libraries may also be used, as discussed in the manual installation documentation.

The extension, via libmongoc, optionally depends on a TLS library (e.g. OpenSSL) and will use it if available. If the build process fails to find a TLS library, users should check that the appropriate development package (e.g. `libssl-dev`) and » pkg-config are both installed. The process for detecting and configuring TLS libraries is discussed in more detail in the manual installation documentation.

» Cyrus SASL is an optional dependency to support Kerberos authentication and will be used if available.

> Note: Due to potential problems representing 64-bit integers on 32-bit platforms, users are advised to use 64-bit environments. When using a 32-bit platform, be aware that any 64-bit integer read from the database will be returned as a MongoDB\BSON\Int64 instance instead of a PHP integer type.

## Installation

## Installing the MongoDB PHP Extension with PIE

> Note: PHP Installer for Extensions (PIE) is a new tool that will deprecate PECL. We recommend using PIE to install extensions. Find out more at » https://github.com/php/pie

To install the MongoDB extension using PIE, run the following command:

    pie install mongodb/mongodb-extension

## Installing the MongoDB PHP Extension with PECL

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: » https://pecl.php.net/package/mongodb

Linux, Unix, and macOS users may run the following command to install the extension:

    $ sudo pecl install mongodb

On systems with multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), each version of PHP will have its own pecl command and php.ini file(s). Additionally, each PHP environments (e.g. CLI, web) may use separate php.ini files.

As of extension version 1.17.0, PECL will prompt for various `configure` options. To install the extension with default options in a non-interactive script, empty string input may be piped to `pecl install` using the `yes` command:

    $ yes '' | sudo pecl install mongodb

A complete list of supported `configure` options can be found in the `package.xml` file included in the PECL package. To install the extension with specific `configure` options in a non-interactive script, the `--configureoptions` option for `pecl install` may be used:

    $ sudo pecl install --configureoptions='with-mongodb-system-libs="yes" enable-mongodb-developer-flags="no"' mongodb

By default, installing the extension via PECL will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to automatically configure them.

> Note: If the build process fails to find an SSL library, check that the development packages (e.g. `libssl-dev`) and » pkg-config are both installed. If that does not resolve the problem, consider using the manual installation process.

Finally, add the following line to the php.ini file for each environment that will need to use the extension:

    extension=mongodb.so

## Installing the MongoDB PHP Extension on macOS with Homebrew

» Homebrew 1.5.0 deprecated the » Homebrew/php tap and removed formulae for individual PHP extensions. Going forward, macOS users are advised to install the » php formula and follow the standard PECL installation instructions using the pecl command provided by the Homebrew PHP installation.

Alternatively, the » shivammathur/extensions tap provides formulae for individual PHP extensions. For example, to install the extension for PHP 8.4, run:

    $ brew install shivammathur/extensions/mongodb@8.4

Please note that only the latest extension version is available in brew.

> Note: Install required dependencies

> To ensure that SSL support can be configured correctly, make sure that the `openssl` and `pkgconf` formulae are installed. If either of these packages are missing, the extension will be compiled with Secure Transport, which can lead to compatibility issues.

## Installing the MongoDB PHP Extension on Windows

Precompiled binaries are attached to the project's » Github releases. Archives are published for various combinations of PHP version, thread safety (TS or NTS), and architecture (x86 or x64). Determining the correct archive for the PHP environment and extract the php_mongodb.dll file to the extension directory ("ext" by default).

Add the following line to the php.ini file for each environment that will need to use the extension:

    extension=php_mongodb.dll

Failure to select the correct binary will result in an error when attempting to load the extension DLL at runtime:

    PHP Warning:  PHP Startup: Unable to load dynamic library 'mongodb'

Ensure that the downloaded DLL corresponds to the following PHP runtime properties:

- PHP version (`PHP_VERSION`)
- Thread safety (`PHP_ZTS`)
- Architecture (`PHP_INT_SIZE`)

In addition to the aforementioned constants, these properties can also be inferred from phpinfo(). If a system has multiple PHP runtimes installed, double-check that the phpinfo() output is for the correct environment.

> Note: Additional DLL dependencies for Windows Users

> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsasl.dll

## Building the MongoDB PHP Driver from source

For developers and users interested in the latest bugfixes, the extension may be compiled from the latest source code on » Github. Run the following commands to clone and build the project:

    $ git clone https://github.com/mongodb/mongo-php-driver.git
    $ cd mongo-php-driver
    $ git submodule update --init
    $ phpize
    $ ./configure
    $ make all
    $ sudo make install

On systems with multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), each version of PHP will have its own phpize command and php.ini file(s). Additionally, each PHP environments (e.g. CLI, web) may use separate php.ini files.

By default, the extension will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to configure them automatically. If these libraries are already installed as system libraries, the extension can utilize them by specifying `--with-mongodb-system-libs=yes` as an option to `configure`.

For a complete list of `configure` options, run configure --help.

When using bundled versions of libmongoc and libmongocrypt, the extension will also attempt to select an SSL library according to the `--with-mongodb-ssl` `configure` option. As of extension version 1.17.0, OpenSSL is always preferred by default. Previously, Secure Transport was the default on macOS and OpenSSL was the default on all other platforms.

> Note:

> If the build process fails to find an SSL library, check that the development packages (e.g. `libssl-dev`) and » pkg-config are both installed.

> When using Homebrew on macOS, it is common for a system to have multiple versions of OpenSSL installed. To ensure that the desired version of OpenSSL is selected, the `PKG_CONFIG_PATH` environment variable may be used to control the search path for `pkg-config`.

The final build step, make install, will report where mongodb.so has been installed, similar to:

    Installing shared extensions:     /usr/lib/php/extensions/debug-non-zts-20220829/

Ensure that the extension_dir option in php.ini points to the directory where mongodb.so was installed. The option may be queried by running:

    $ php -i | grep extension_dir
      extension_dir => /usr/lib/php/extensions/debug-non-zts-20220829 =>
                       /usr/lib/php/extensions/debug-non-zts-20220829

If the directories differ, either change extension_dir in php.ini or manually move mongodb.so to the correct directory.

Finally, add the following line to the php.ini file for each environment that will need to use the extension:

    extension=mongodb.so

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mongodb Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mongodb.debug | "" | `INI_ALL` |

Here's a short explanation of the configuration directives.

`mongodb.debug` string

  This option can be used to enable or disable trace-level debug logging in the extension (and libmongoc).

  Specify an empty string, `"0"`, `"off"`, `"no"`, or `"false"` to disable logging.

  Specify `"stderr"` or `"stdout"` to log to `stderr` or `stdout`, respectively.

  Specify `"1"`, `"on"`, `"yes"`, or `"true"` to log to a new temporary file within the default system temp directory (i.e. sys_get_temp_dir()).

  Specify any other string to log to a new temporary file within that directory. If the directory cannot be used, the default system temp directory will be used instead.

  > Note:

  > Please note that the debug log can contain sensitive information, such as credentials to the MongoDB server and full documents written to or read from the server. Please review any debug logs before sharing them with other people.

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

`MONGODB_VERSION` (string)
  x.y.z style version number of the extension
`MONGODB_STABILITY` (string)
  Current stability (alpha/beta/stable)

# Tutorials

## Table of Contents

- Using the PHP Library for MongoDB (PHPLIB)
- Application Performance Monitoring (APM)

In this section you will find several tutorials on how to use the MongoDB driver for PHP.

## Using the PHP Library for MongoDB (PHPLIB)

After the initial extension set-up, we will continue explaining how to get started with the corresponding userland library to write our first project.

## Installing the PHP Library with Composer

The last thing we still need to install to get started on the application itself, is the PHP library.

The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website.

Install the library by running:

    $ composer require mongodb/mongodb

It will output something akin to:

    ./composer.json has been created
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
      - Installing mongodb/mongodb (1.0.0)
        Downloading: 100%

    Writing lock file
    Generating autoload files

Composer will create several files: `composer.json`, `composer.lock`, and a `vendor` directory that will contain the library and any other dependencies your project might require.

## Using the PHP Library

In addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:

`<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';`

With this done, you can now use any of the functionality as described in the » library documentation.

If you have used MongoDB drivers in other languages, the library's API should look familiar. It contains a » Client class for connecting to MongoDB, a » Database class for database-level operations (e.g. commands, collection management), and a » Collection class for collection-level operations (e.g. » CRUD methods, index management).

As an example, this is how you insert a document into the beers collection of the demo database:

`<?php
require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>`

Since the inserted document did not contain an `_id` field, the extension will generate an MongoDB\BSON\ObjectId for the server to use as the `_id`. This value is also made available to the caller via the result object returned by the `insertOne` method.

After insertion, you can query for the data that you have just inserted. For that, you use the `find` method, which returns an iterable cursor:

`<?php
require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>`

While it may not be apparent in the examples, BSON documents and arrays are unserialized as special classes in the library by default. These classes extend ArrayObject for usability and implement the extension's MongoDB\BSON\Serializable and MongoDB\BSON\Unserializable interfaces to ensure that values preserve their type when serialized back into BSON. This avoids a caveat in the legacy `mongo` extension where arrays might turn into documents, and vice versa. See the Persisting Data specification for more information on how values are converted between PHP and BSON.

## Application Performance Monitoring (APM)

The extension contains an event subscriber API, which allows applications to monitor commands and internal activity pertaining to the » Server Discovery and Monitoring Specification. This tutorial will demonstrate command monitoring using the MongoDB\Driver\Monitoring\CommandSubscriber interface.

The MongoDB\Driver\Monitoring\CommandSubscriber interface defines three methods: `commandStarted`, `commandSucceeded`, and `commandFailed`. Each of these three methods accept a single `event` argument of a specific class for the respective event. For example, the `commandSucceeded`'s `$event` argument is a MongoDB\Driver\Monitoring\CommandSucceededEvent object.

In this tutorial we will implement a subscriber that creates a list of all the query profiles and the average time they took.

## Subscriber Class Scaffolding

We start with the framework for our subscriber:

`<?php
class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event ): void
{
}
public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event ): void
{
}
public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event ): void
{
}
}
?>`

## Registering the Subscriber

Once a subscriber object is instantiated, it needs to be registered with the extensions's monitoring system. This is done by calling MongoDB\Driver\Monitoring\addSubscriber() or MongoDB\Driver\Manager::addSubscriber() to register the subscriber globally or with a specific Manager, respectively.

`<?php
\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );
?>`

## Implementing the Logic

With the object registered, the only thing left is to implement the logic in the subscriber class. To correlate the two events that make up a successfully executed command (commandStarted and commandSucceeded), each event object exposes a `requestId` field.

To record the average time per query shape, we will start by checking for a `find` command in the commandStarted event. We will then add an item to the `pendingCommands` property indexed by its `requestId` and with its value representing the query shape.

If we receive a corresponding commandSucceeded event with the same `requestId`, we add the duration of the event (from `durationMicros`) to the total time and increment the operation count.

If a corresponding commandFailed event is encountered, we just remove the entry from the `pendingCommands` property.

`<?php
class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
private $pendingCommands = [];
private $queryShapeStats = [];
/* Creates a query shape out of the filter argument. Right now it only
* takes the top level fields into account */
private function createQueryShape( array $filter )
{
return json_encode( array_keys( $filter ) );
}
public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event ): void
{
if ( 'find' === $event->getCommandName() )
{
$queryShape = $this->createQueryShape( (array) $event->getCommand()->filter );
$this->pendingCommands[$event->getRequestId()] = $queryShape;
}
}
public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event ): void
{
$requestId = $event->getRequestId();
if ( array_key_exists( $requestId, $this->pendingCommands ) )
{
$this->queryShapeStats[$this->pendingCommands[$requestId]]['count']++;
$this->queryShapeStats[$this->pendingCommands[$requestId]]['duration'] += $event->getDurationMicros();
unset( $this->pendingCommands[$requestId] );
}
}
public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event ): void
{
if ( array_key_exists( $event->getRequestId(), $this->pendingCommands ) )
{
unset( $this->pendingCommands[$event->getRequestId()] );
}
}
public function __destruct()
{
foreach( $this->queryShapeStats as $shape => $stats )
{
echo "Shape: ", $shape, " (", $stats['count'], ")\n ",
$stats['duration'] / $stats['count'], "µs\n\n";
}
}
}
$m = new \MongoDB\Driver\Manager( 'mongodb://localhost:27016' );
/* Add the subscriber */
\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );
/* Do a bunch of queries */
$query = new \MongoDB\Driver\Query( [
'region_slug' => 'scotland-highlands', 'age' => [ '$gte' => 20 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );
$query = new \MongoDB\Driver\Query( [
'region_slug' => 'scotland-lowlands', 'age' => [ '$gte' => 15 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );
$query = new \MongoDB\Driver\Query( [ 'region_slug' => 'scotland-lowlands' ] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );
?>`

# Explains the driver architecture, and special features

## Table of Contents

- Architecture
- Connections
- Persisting Data

## Architecture Overview

This article explains how all the different components of the PHP driver fit together, from base system libraries, through the extension, and to the PHP libraries on top.

At the top of this stack sits a » PHP library, which is distributed as a » Composer package. This library provides an API consistent with other MongoDB » drivers and implements various cross-driver » specifications. While the extension can be used directly, the library has minimal overhead and should be a common dependency for most applications built with MongoDB.

Sitting below that library is a PHP extension, which is distributed through » PECL. The extension forms the glue between PHP and our system libraries (» libmongoc, » libbson, and » libmongocrypt). Its public API provides only the most essential functionality:

- Connection management
- BSON encoding and decoding
- Object document serialization (to support ODM libraries)
- Executing commands, queries, and write operations
- Handling cursors for command and query results

Driver Source Code and JIRA Projects
Project | GitHub | JIRA
--- | --- | ---
PHP Library | » mongodb/mongo-php-library | » PHPLIB
PHP Extension | » mongodb/mongo-php-driver | » PHPC

## Connection handling and persistence

> Note: On Unix platforms, the extension is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

## Connection and topology persistence (PHP version since 1.2.0)

All versions of the extension since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.

When MongoDB\Driver\Manager::__construct() is invoked, a hash is created from its arguments (i.e. URI string and array options). The extension will attempt to find a previously persisted » libmongoc client object for that hash. If an existing client cannot be found for the hash, a new client will be created and persisted for future use. This behavior can be disabled via the `"disableClientPersistence"` driver option.

Each client contains its own database connections and a view of the server topology (e.g. standalone, replica set, shard cluster). By persisting the client between PHP requests, the extension is able to re-use established database connections and remove the need for » discovering the server topology on each request.

Consider the following example:

`<?php
$managers = [
new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017'),
new MongoDB\Driver\Manager('mongodb://rs1.example.com,rs2.example.com/', ['replicaSet' => 'myReplicaSet']),
];
foreach ($managers as $manager) {
$manager->executeCommand('test', new MongoDB\Driver\Command(['ping' => 1]));
}
?>`

The first two Manager objects will share the same » libmongoc client since their constructor arguments are identical. The third and fourth objects will each use their own client. In total, three clients will be created and the PHP worker executing this script will open two connections to `127.0.0.1` and one connection to each of `rs1.example.com` and `rs2.example.com`. If the extension discovers additional members of the replica set after issuing `hello` commands, it will open additional connections to those servers as well.

If the same worker executes the script again in a second request, the three clients will be re-used and no new connections will be made. Depending on how long ago the previous request was served, the extension may need to issue additional `hello` commands to update its view of the topologies.

## Socket persistence (PHP versions before 1.2.0)

Versions of the extension before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the extension persists individual database connections but not authentication state or topology information. This means that the extension needs to issue commands at the start of each request to authenticate and » discover the server topology.

Database connections are persisted by a hash derived from the server's host, port, and the URI string used to construct the MongoDB\Driver\Manager. The constructor's array options are not included in this hash.

> Note: Versions of the extension >= 1.1.8 and < 1.2.0 do not persist sockets for SSL connections. See » PHPC-720 for additional information.

Despite its shortcomings with persisting SSL connections when and topology information, this version of the extension supports all SSL context options since it uses PHP's Streams API.

## Serialization and deserialization of PHP variables into MongoDB

This document discusses how compound structures (i.e. documents, arrays, and objects) are converted between BSON and PHP values.

## Serialization to BSON

## Arrays

If an array is a packed array — i.e. empty array or the keys start at 0 and are sequential without gaps: BSON array.

If the array is not packed — i.e. having associative (string) keys, the keys don't start at 0, or when there are gaps:: BSON object

A top-level (root) document, always serializes as a BSON document.

## Examples

These serialize as a BSON array:

    [ 8, 5, 2, 3 ] => [ 8, 5, 2, 3 ]
    [ 0 => 4, 1 => 9 ] => [ 4, 9 ]

These serialize as a BSON document:

    [ 0 => 1, 2 => 8, 3 => 12 ] => { "0" : 1, "2" : 8, "3" : 12 }
    [ "foo" => 42 ] => { "foo" : 42 }
    [ 1 => 9, 0 => 10 ] => { "1" : 9, "0" : 10 }

Note that the five examples are extracts of a full document, and represent only one value inside a document.

## Objects

If an object is of the stdClass class, serialize as a BSON document.

If an object is a supported class that implements MongoDB\BSON\Type, then use the BSON serialization logic for that specific type. MongoDB\BSON\Type instances (excluding MongoDB\BSON\Serializable may only be serialized as a document field value. Attempting to serialize such an object as a root document will throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of an unknown class implementing the MongoDB\BSON\Type interface, then throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of any other class, without implementing any special interface, serialize as a BSON document. Keep only public properties, and ignore protected and private properties.

If an object is of a class that implements the MongoDB\BSON\Serializable interface, call MongoDB\BSON\Serializable::bsonSerialize() and use the returned array or stdClass to serialize as a BSON document or array. The BSON type will be determined by the following:

1. Root documents must be serialized as a BSON document.

2. MongoDB\BSON\Persistable objects must be serialized as a BSON document.

3. If MongoDB\BSON\Serializable::bsonSerialize() returns a packed array, serialize as a BSON array.

4. If MongoDB\BSON\Serializable::bsonSerialize() returns a non-packed array or stdClass, serialize as a BSON document.

5. If MongoDB\BSON\Serializable::bsonSerialize() did not return an array or stdClass, throw an MongoDB\Driver\Exception\UnexpectedValueException exception.

If an object is of a class that implements the MongoDB\BSON\Persistable interface (which implies MongoDB\BSON\Serializable), obtain the properties in a similar way as in the previous paragraphs, but also add an additional property __pclass as a Binary value, with subtype `0x80` and data bearing the fully qualified class name of the object that is being serialized.

The __pclass property is added to the array or object returned by MongoDB\BSON\Serializable::bsonSerialize(), which means it will overwrite any __pclass key/property in the MongoDB\BSON\Serializable::bsonSerialize() return value. If you want to avoid this behaviour and set your own __pclass value, you must not implement MongoDB\BSON\Persistable and should instead implement MongoDB\BSON\Serializable directly.

## Examples

`<?php
class stdClass
{
public $foo = 42;
} // => {"foo": 42}
class MyClass
{
public $foo = 42;
protected $prot = 'wine';
private $fpr = 'cheese';
} // => {"foo": 42}
class AnotherClass1 implements MongoDB\BSON\Serializable
{
public $foo = 42;
protected $prot = 'wine';
private $fpr = 'cheese';
public function bsonSerialize(): array
{
return ['foo' => $this->foo, 'prot' => $this->prot];
}
} // => {"foo": 42, "prot": "wine"}
class AnotherClass2 implements MongoDB\BSON\Serializable
{
public $foo = 42;
public function bsonSerialize(): self
{
return $this;
}
} // => MongoDB\Driver\Exception\UnexpectedValueException("bsonSerialize() did not return an array or stdClass")
class AnotherClass3 implements MongoDB\BSON\Serializable
{
private $elements = ['foo', 'bar'];
public function bsonSerialize(): array
{
return $this->elements;
}
} // => {"0": "foo", "1": "bar"}
/**
* Nesting Serializable classes
*/
class AnotherClass4 implements MongoDB\BSON\Serializable
{
private $elements = [0 => 'foo', 2 => 'bar'];
public function bsonSerialize(): array
{
return $this->elements;
}
} // => {"0": "foo", "2": "bar"}
class ContainerClass1 implements MongoDB\BSON\Serializable
{
public $things;
public function __construct()
{
$this->things = new AnotherClass4();
}
function bsonSerialize(): array
{
return ['things' => $this->things];
}
} // => {"things": {"0": "foo", "2": "bar"}}
class AnotherClass5 implements MongoDB\BSON\Serializable
{
private $elements = [0 => 'foo', 2 => 'bar'];
public function bsonSerialize(): array
{
return array_values($this->elements);
}
} // => {"0": "foo", "1": "bar"} as a root class
// ["foo", "bar"] as a nested value
class ContainerClass2 implements MongoDB\BSON\Serializable
{
public $things;
public function __construct()
{
$this->things = new AnotherClass5();
}
public function bsonSerialize(): array
{
return ['things' => $this->things];
}
} // => {"things": ["foo", "bar"]}
class AnotherClass6 implements MongoDB\BSON\Serializable
{
private $elements = ['foo', 'bar'];
function bsonSerialize(): object
{
return (object) $this->elements;
}
} // => {"0": "foo", "1": "bar"}
class ContainerClass3 implements MongoDB\BSON\Serializable
{
public $things;
public function __construct()
{
$this->things = new AnotherClass6();
}
public function bsonSerialize(): array
{
return ['things' => $this->things];
}
} // => {"things": {"0": "foo", "1": "bar"}}
class UpperClass implements MongoDB\BSON\Persistable
{
public $foo = 42;
protected $prot = 'wine';
private $fpr = 'cheese';
private $data;
public function bsonUnserialize(array $data): void
{
$this->data = $data;
}
public function bsonSerialize(): array
{
return ['foo' => $this->foo, 'prot' => $this->prot];
}
} // => {"foo": 42, "prot": "wine", "__pclass": {"$type": "80", "$binary": "VXBwZXJDbGFzcw=="}}
?>`

## Deserialization from BSON

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

The legacy `mongo` extension deserialized both BSON documents and arrays as PHP arrays. While PHP arrays are convenient to work with, this behavior was problematic because different BSON types could deserialize to the same PHP value (e.g. `{"0": "foo"}` and `["foo"]`) and make it impossible to infer the original BSON type. By default, the `mongodb` extension addresses this concern by ensuring that BSON arrays and documents are converted to PHP arrays and objects, respectively.

For compound types, there are three data types:

root

  refers to the top-level BSON document only

document

  refers to embedded BSON documents only

array

  refers to a BSON array

Besides the three collective types, it is also possible to configure specific fields in your document to map to the data types mentioned below. As an example, the following type map allows you to map each embedded document within an `"addresses"` array to an Address class and each `"city"` field within those embedded address documents to a City class:

    [
        'fieldPaths' => [
            'addresses.$' => 'MyProject\Address',
            'addresses.$.city' => 'MyProject\City',
        ],
    ]

Each of those three data types, as well as the field specific mappings, can be mapped against different PHP types. The possible mapping values are:

not set or NULL (default)

  - A BSON array will be deserialized as a PHP array.

  - A BSON document (root or embedded) without a __pclass property [1] becomes a PHP stdClass object, with each BSON document key set as a public stdClass property.

  - A BSON document (root or embedded) with a __pclass property [1] becomes a PHP object of the class name as defined by the __pclass property.

    If the named class implements the MongoDB\BSON\Persistable interface, then the properties of the BSON document, including the __pclass property, are sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

    If the named class does not exist or does not implement the MongoDB\BSON\Persistable interface, stdClass will be used and each BSON document key (including __pclass) will be set as a public stdClass property.

    The __pclass functionality relies on the property being part of a retrieved MongoDB document. If you use a projection when querying for documents, you need to include the __pclass field in the projection for this functionality to work.

`"array"`

  Turns a BSON array or BSON document into a PHP array. There will be no special treatment of a __pclass property [1], but it may be set as an element in the returned array if it was present in the BSON document.

`"object"` or `"stdClass"`

  Turns a BSON array or BSON document into a stdClass object. There will be no special treatment of a __pclass property [1], but it may be set as a public property in the returned object if it was present in the BSON document.

`"bson"`

  Turns a BSON array into a MongoDB\BSON\PackedArray and a BSON document into a MongoDB\BSON\Document, regardless of whether the BSON document has a __pclass property [1].

  > Note: The `bson` value is only available for the three root types, not in the field specific mappings.

any other string

  Defines the class name that the BSON array or BSON object should be deserialized as. For BSON objects that include __pclass properties, that class will take priority.

  If the named class does not exist, is not concrete (i.e. it is abstract or an interface), or does not implement MongoDB\BSON\Unserializable then an MongoDB\Driver\Exception\InvalidArgumentException exception is thrown.

  If the BSON object has a __pclass property and that class exists and implements MongoDB\BSON\Persistable it will supersede the class provided in the type map.

  The properties of the BSON document, including the __pclass property if it exists, will be sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

## TypeMaps

TypeMaps can be set through the MongoDB\Driver\Cursor::setTypeMap() method on a MongoDB\Driver\Cursor object, or the `$typeMap` argument of MongoDB\BSON\toPHP(), MongoDB\BSON\Document::toPHP(), and MongoDB\BSON\PackedArray::toPHP(). Each of the three classes (root, document, and array) can be individually set, in addition to the field specific types.

If the value in the map is NULL, it means the same as the default value for that item.

## Examples

These examples use the following classes:

MyClass

  which does not implement any interface

YourClass

  which implements MongoDB\BSON\Unserializable

OurClass

  which implements MongoDB\BSON\Persistable

TheirClass

  which extends OurClass

The MongoDB\BSON\Unserializable::bsonUnserialize() method of YourClass, OurClass, TheirClass iterate over the array and set the properties without modifications. It also sets the `$unserialized` property to `true`:

`<?php
function bsonUnserialize( array $map )
{
foreach ( $map as $k => $value )
{
$this->$k = $value;
}
$this->unserialized = true;
}`

    /* typemap: [] (all defaults) */
    { "foo": "yes", "bar" : false }
      -> stdClass { $foo => 'yes', $bar => false }

    { "foo": "no", "array" : [ 5, 6 ] }
      -> stdClass { $foo => 'no', $array => [ 5, 6 ] }

    { "foo": "no", "obj" : { "embedded" : 3.14 } }
      -> stdClass { $foo => 'no', $obj => stdClass { $embedded => 3.14 } }

    { "foo": "yes", "__pclass": "MyClass" }
      -> stdClass { $foo => 'yes', $__pclass => 'MyClass' }

    { "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "MyClass" } }
      -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'MyClass') }

    { "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "YourClass") }
      -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass') }

    { "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "OurClass") }
      -> OurClass { $foo => 'yes', $__pclass => Binary(0x80, 'OurClass'), $unserialized => true }

    { "foo": "yes", "__pclass": { "$type" : "44", "$binary" : "YourClass") }
      -> stdClass { $foo => 'yes', $__pclass => Binary(0x44, 'YourClass') }

    /* typemap: [ "root" => "MissingClass" ] */
    { "foo": "yes" }
      -> MongoDB\Driver\Exception\InvalidArgumentException("MissingClass does not exist")

    /* typemap: [ "root" => "MyClass" ] */
    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
      -> MongoDB\Driver\Exception\InvalidArgumentException("MyClass does not implement Unserializable interface")

    /* typemap: [ "root" => "MongoDB\BSON\Unserializable" ] */
    { "foo": "yes" }
      -> MongoDB\Driver\Exception\InvalidArgumentException("Unserializable is not a concrete class")

    /* typemap: [ "root" => "YourClass" ] */
    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MongoDB\BSON\Unserializable" } }
      -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MongoDB\BSON\Unserializable"), $unserialized => true }

    /* typemap: [ "root" => "YourClass" ] */
    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
      -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MyClass"), $unserialized => true }

    /* typemap: [ "root" => "YourClass" ] */
    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
      -> OurClass { $foo => "yes", $__pclass => Binary(0x80, "OurClass"), $unserialized => true }

    /* typemap: [ "root" => "YourClass" ] */
    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
      -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

    /* typemap: [ "root" => "OurClass" ] */
    { foo: "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
      -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

    /* typemap: [ 'root' => 'YourClass' ] */
    { foo: "yes", "__pclass" : { "$type": "80", "$binary": "YourClass" } }
      -> YourClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass'), $unserialized => true }

    /* typemap: [ 'root' => 'array', 'document' => 'array' ] */
    { "foo": "yes", "bar" : false }
      -> [ "foo" => "yes", "bar" => false ]

    { "foo": "no", "array" : [ 5, 6 ] }
      -> [ "foo" => "no", "array" => [ 5, 6 ] ]

    { "foo": "no", "obj" : { "embedded" : 3.14 } }
      -> [ "foo" => "no", "obj" => [ "embedded => 3.14 ] ]

    { "foo": "yes", "__pclass": "MyClass" }
      -> [ "foo" => "yes", "__pclass" => "MyClass" ]

    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
      -> [ "foo" => "yes", "__pclass" => Binary(0x80, "MyClass") ]

    { "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
      -> [ "foo" => "yes", "__pclass" => Binary(0x80, "OurClass") ]

    /* typemap: [ 'root' => 'object', 'document' => 'object' ] */
    { "foo": "yes", "__pclass": { "$type": "80", "$binary": "MyClass" } }
      -> stdClass { $foo => "yes", "__pclass" => Binary(0x80, "MyClass") }

# Security

## Table of Contents

- Request Injection Attacks
- Script Injection Attacks

## Request Injection Attacks

If you are passing `$_GET` (or `$_POST`) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST requests, which could then become unwanted $-queries.

A fairly innocuous example: suppose you are looking up a user's information with the request http://www.example.com?username=bob. Your application creates the query `$q = new \MongoDB\Driver\Query( [ 'username' => $_GET['username'] ])`.

Someone could subvert this by getting http://www.example.com?username[$ne]=foo, which PHP will magically turn into an associative array, turning your query into `$q = new \MongoDB\Driver\Query( [ 'username' => [ '$ne' => 'foo' ] ] )`, which will return all users not named "foo" (all of your users, probably).

This is a fairly easy attack to defend against: make sure $_GET and $_POST parameters are the type you expect before you send them to the database. PHP has the filter_var() function to assist with this.

Note that this type of attack can be used with any database interaction that locates a document, including updates, upserts, deletes, and findAndModify commands.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

## Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the `scope` field of MongoDB\BSON\Javascript, not interpolated into the JavaScript string. This can come up when using `$where` clauses in queries, mapReduce and group commands, and any other time you may pass JavaScript into the database.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

`<?php
$m = new MongoDB\Driver\Manager;
// Don't do this!!!
$username = $_GET['field'];
$cmd = new \MongoDB\Driver\Command( [
'eval' => "print('Hello, $username!');"
] );
$r = $m->executeCommand( 'dramio', $cmd );
?>`

However, what if a malicious user passes in some JavaScript?

`<?php
$m = new MongoDB\Driver\Manager;
// Don't do this!!!
$username = $_GET['field'];
// $username is set to "'); db.users.drop(); print('"
$cmd = new \MongoDB\Driver\Command( [
'eval' => "print('Hello, $username!');"
] );
$r = $m->executeCommand( 'dramio', $cmd );
?>`

Now MongoDB executes the JavaScript string `"print('Hello, '); db.users.drop(); print('!');"`. This attack is easy to avoid: use `args` to pass variables from PHP to JavaScript:

`<?php
$m = new MongoDB\Driver\Manager;
$_GET['field'] = 'derick';
$args = [ $_GET['field'] ];
$cmd = new \MongoDB\Driver\Command( [
'eval' => "function greet(username) { print('Hello, ' + username + '!'); }",
'args' => $args,
] );
$r = $m->executeCommand( 'dramio', $cmd );
?>`

This adds an argument to the JavaScript scope, which gets used as argument for the `greet` function. Now if someone tries to send malicious code, MongoDB will harmlessly print `Hello, '); db.dropDatabase(); print('!`.

Using arguments helps to prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! It is best to avoid executing any JavaScript on the server in the first place.

You are strongly recommended to stay clear of the » $where clause with queries, as it impacts performance significantly. Where possible, use either normal query operators, or the » Aggregation Framework.

As alternative to » MapReduce, which uses JavaScript, consider using the » Aggregation Framework. Unlike Map/Reduce, it uses an idiomatic language to construct queries, without having to write, and use, the slower JavaScript approach that Map/Reduce requires.

The » eval command has been deprecated since MongoDB 3.0, and should also be avoided.

# MongoDB Extension Classes

## Table of Contents

- MongoDB\Driver\Manager
- MongoDB\Driver\Command
- MongoDB\Driver\Query
- MongoDB\Driver\BulkWrite
- MongoDB\Driver\BulkWriteCommand
- MongoDB\Driver\Session
- MongoDB\Driver\ClientEncryption
- MongoDB\Driver\ServerApi
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\ReadPreference
- MongoDB\Driver\ReadConcern
- MongoDB\Driver\Cursor
- MongoDB\Driver\CursorId
- MongoDB\Driver\CursorInterface
- MongoDB\Driver\Server
- MongoDB\Driver\ServerDescription
- MongoDB\Driver\TopologyDescription
- MongoDB\Driver\WriteConcernError
- MongoDB\Driver\WriteError
- MongoDB\Driver\WriteResult
- MongoDB\Driver\BulkWriteCommandResult

# The MongoDB\Driver\Manager class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\Manager is the main entry point to the extension. It is responsible for maintaining connections to MongoDB (be it standalone server, replica set, or sharded cluster).

No connection to MongoDB is made upon instantiating the Manager. This means the MongoDB\Driver\Manager can always be constructed, even though one or more MongoDB servers are down.

Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

## Class synopsis

final class MongoDB\Driver\Manager {
/* Methods */
final public addSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void
final public __construct(?string `$uri` = `null`, ?array `$uriOptions` = `null`, ?array `$driverOptions` = `null`)
final public createClientEncryption(array `$options`): MongoDB\Driver\ClientEncryption
final public executeBulkWrite(string `$namespace`, MongoDB\Driver\BulkWrite `$bulk`, ?array `$options` = `null`): MongoDB\Driver\WriteResult
final public executeBulkWriteCommand(MongoDB\Driver\BulkWriteCommand `$bulk`, ?array `$options` = `null`): MongoDB\Driver\BulkWriteCommandResult
final public executeCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeQuery(string `$namespace`, MongoDB\Driver\Query `$query`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeReadCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeReadWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public getEncryptedFieldsMap(): array|object|null
final public getReadConcern(): MongoDB\Driver\ReadConcern
final public getReadPreference(): MongoDB\Driver\ReadPreference
final public getServers(): array
final public getWriteConcern(): MongoDB\Driver\WriteConcern
final public removeSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void
final public selectServer(?MongoDB\Driver\ReadPreference `$readPreference` = `null`): MongoDB\Driver\Server
final public startSession(?array `$options` = `null`): MongoDB\Driver\Session
}

## Examples

Example #1 MongoDB\Driver\Manager::__construct() basic example

var_dump()ing a MongoDB\Driver\Manager will print out various details about the manager that are otherwise not normally exposed. This can be useful to debug how the driver views your MongoDB setup, and which options are used.

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager);
?>`

The above example will output something similar to:

    object(MongoDB\Driver\Manager)#1 (2) {
      ["uri"]=>
      string(26) "mongodb://127.0.0.1:27017/"
      ["cluster"]=>
      array(0) {
      }
    }

# MongoDB\Driver\Manager::addSubscriber

(mongodb >=1.10.0)

MongoDB\Driver\Manager::addSubscriber — Registers a monitoring event subscriber with this Manager

### Description

final public MongoDB\Driver\Manager::addSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void

Registers a monitoring event subscriber with this Manager. The subscriber will be notified of all events for this Manager.

> Note: If `subscriber` is already registered with this Manager, this function is a no-op. If `subscriber` is also registered globally, it will still only be notified once of each event for this Manager.

### Parameters

`subscriber` (MongoDB\Driver\Monitoring\Subscriber)

  A monitoring event subscriber to register with this Manager.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `subscriber` is a MongoDB\Driver\Monitoring\LogSubscriber, since loggers can only be registered globally.

### See Also

- MongoDB\Driver\Manager::removeSubscriber() - Unregisters a monitoring event subscriber with this Manager
- MongoDB\Driver\Monitoring\Subscriber
- MongoDB\Driver\Monitoring\CommandSubscriber
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- Application Performance Monitoring (APM)

# MongoDB\Driver\Manager::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Manager::__construct — Create new MongoDB Manager

### Description

final public MongoDB\Driver\Manager::__construct(?string `$uri` = `null`, ?array `$uriOptions` = `null`, ?array `$driverOptions` = `null`)

Constructs a new MongoDB\Driver\Manager object with the specified options.

> Note: Per the » Server Discovery and Monitoring Specification, this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed.

> Note: When specifying any SSL or TLS URI options via the connection string or `uriOptions` parameter, the extension will implicitly enable TLS for its connections. To avoid this, either explicitly disable the `tls` option or don't specify any TLS options.

> Note: On Unix platforms, the extension is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

### Parameters

`uri`

  A » mongodb:// connection URI:

      mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[defaultAuthDb][?options]]

  Defaults to `"mongodb://127.0.0.1:27017"` if unspecified.

  For details on supported URI options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the extension does not implement connection pools.

  The `uri` is a URL, hence any special characters in its components need to be URL encoded according to » RFC 3986. This is particularly relevant to the username and password, which can often include special characters such as `@`, `:`, or `%`. When connecting via a Unix domain socket, the socket path may contain special characters such as slashes and must be encoded. The rawurlencode() function may be used to encode constituent parts of the URI.

  The `defaultAuthDb` component may be used to specify the database name associated with the user's credentials; however the `authSource` URI option will take priority if specified. If neither `defaultAuthDb` nor `authSource` are specified, the `admin` database will be used by default. The `defaultAuthDb` component has no effect in the absence of user credentials.

`uriOptions`

  Additional » connection string options, which will overwrite any options with the same name in the `uri` parameter.

  uriOptions
  Option | Type | Description
  --- | --- | ---
  appname | string | MongoDB 3.4+ has the ability to annotate connections with metadata provided by the connecting client. This metadata is included in the server's logs upon establishing a connection and also recorded in slow query logs when database profiling is enabled. This option may be used to specify an application name, which will be included in the metadata. The value cannot exceed 128 characters in length.
  authMechanism | string | The authentication mechanism that MongoDB will use to authenticate the connection. For additional details and a list of supported values, see » Authentication Options in the MongoDB manual.
  authMechanismProperties | array | Properties for the selected authentication mechanism. For additional details and a list of supported properties, see the » Driver Authentication Specification. Note: When not specified in the URI string, this option is expressed as an array of key/value pairs. The keys and values in this array should be strings.
  authSource | string | The database name associated with the user's credentials. Defaults to the database component of the connection URI, or the `admin` database if both are unspecified. For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be `"$external"`.
  compressors | string | A prioritized, comma-delimited list of compressors that the client wants to use. Messages are only compressed if the client and server share any compressors in common, and the compressor used in each direction will depend on the individual configuration of the server or driver. See the » Driver Compression Specification for more information.
  connectTimeoutMS | int | The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds.
  directConnection | bool | This option can be used to control replica set discovery behavior when only a single host is provided in the connection string. By default, providing a single member in the connection string will establish a direct connection or discover additional members depending on whether the `"replicaSet"` URI option is omitted or present, respectively. Specify `false` to force discovery to occur (if `"replicaSet"` is omitted) or specify `true` to force a direct connection (if `"replicaSet"` is present).
  heartbeatFrequencyMS | int | Specifies the interval in milliseconds between the driver's checks of the MongoDB topology, counted from the end of the previous check until the beginning of the next one. Defaults to 60,000 milliseconds. Per the » Server Discovery and Monitoring Specification, this value cannot be less than 500 milliseconds.
  journal | bool | Corresponds to the default write concern's `journal` parameter. If `true`, writes will require acknowledgement from MongoDB that the operation has been written to the journal. For details, see MongoDB\Driver\WriteConcern.
  loadBalanced | bool | Specifies whether the driver is connecting to a MongoDB cluster through a load balancer. If `true`, the driver may only connect to a single host (specified by either the connection string or SRV lookup), the `"directConnection"` URI option cannot be `true`, and the `"replicaSet"` URI option must be omitted. Defaults to `false`.
  localThresholdMS | int | The size in milliseconds of the latency window for selecting among multiple suitable MongoDB instances while resolving a read preference. Defaults to 15 milliseconds.
  maxStalenessSeconds | int | Corresponds to the read preference's `"maxStalenessSeconds"`. Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. By default, there is no maximum staleness and clients will not consider a secondary’s lag when choosing where to direct a read operation. For details, see MongoDB\Driver\ReadPreference. If specified, the max staleness must be a signed 32-bit integer greater than or equal to `MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS` (i.e. 90 seconds).
  password | string | The password for the user being authenticated. This option is useful if the password contains special characters, which would otherwise need to be URL encoded for the connection URI.
  readConcernLevel | string | Corresponds to the read concern's `level` parameter. Specifies the level of read isolation. For details, see MongoDB\Driver\ReadConcern.
  readPreference | string | Corresponds to the read preference's `mode` parameter. Defaults to `"primary"`. For details, see MongoDB\Driver\ReadPreference.
  readPreferenceTags | array | Corresponds to the read preference's `tagSets` parameter. Tag sets allow you to target read operations to specific members of a replica set. For details, see MongoDB\Driver\ReadPreference. Note: When not specified in the URI string, this option is expressed as an array consistent with the format expected by MongoDB\Driver\ReadPreference::__construct().
  replicaSet | string | Specifies the name of the replica set.
  retryReads | bool | Specifies whether or not the driver should automatically retry certain read operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to `true`. See the » Retryable Reads Specification for more information.
  retryWrites | bool | Specifies whether or not the driver should automatically retry certain write operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to `true`. See » Retryable Writes in the MongoDB manual for more information.
  serverSelectionTimeoutMS | int | Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds.
  serverSelectionTryOnce | bool | When `true`, instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error. When `false`, the driver blocks and searches for a server up to the `"serverSelectionTimeoutMS"` value. Defaults to `true`.
  socketCheckIntervalMS | int | If a socket has not been used recently, the driver must check it via a `hello` command before using it for any operation. Defaults to 5,000 milliseconds.
  socketTimeoutMS | int | The time in milliseconds to attempt a send or receive on a socket before timing out. Defaults to 300,000 milliseconds (i.e. five minutes).
  srvMaxHosts | int | The maximum number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. Defaults to `0` (i.e. no maximum).
  srvServiceName | string | The service name to use for SRV lookup in initial DNS seedlist discovery and SRV polling. Defaults to `"mongodb"`.
  tls | bool | Initiates the connection with TLS/SSL if `true`. Defaults to `false`.
  tlsAllowInvalidCertificates | bool | Specifies whether or not the driver should error when the server's TLS certificate is invalid. Defaults to `false`. Warning Disabling certificate validation creates a vulnerability.
  tlsAllowInvalidHostnames | bool | Specifies whether or not the driver should error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Defaults to `false`. Warning Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.
  tlsCAFile | string | Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default.
  tlsCertificateKeyFile | string | Path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated.
  tlsCertificateKeyFilePassword | string | Password to decrypt the client private key (i.e. `"tlsCertificateKeyFile"` URI option) to be used for TLS connections.
  tlsDisableCertificateRevocationCheck | bool | If `true`, the driver will not attempt to check certificate revocation status (e.g. OCSP, CRL). Defaults to `false`.
  tlsDisableOCSPEndpointCheck | bool | If `true`, the driver will not attempt to contact an OCSP responder endpoint if needed (i.e. an OCSP response is not stapled). Defaults to `false`.
  tlsInsecure | bool | Relax TLS constraints as much as possible. Specifying `true` for this option has the same effect as specifying `true` for both the `"tlsAllowInvalidCertificates"` and `"tlsAllowInvalidHostnames"` URI options. Defaults to `false`. Warning Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.
  username | string | The username for the user being authenticated. This option is useful if the username contains special characters, which would otherwise need to be URL encoded for the connection URI.
  w | int|string | Corresponds to the default write concern's `w` parameter. For details, see MongoDB\Driver\WriteConcern.
  wTimeoutMS | int|string | Corresponds to the default write concern's `wtimeout` parameter. Specifies a time limit, in milliseconds, for the write concern. For details, see MongoDB\Driver\WriteConcern. If specified, `wTimeoutMS` must be a signed 32-bit integer greater than or equal to zero.
  zlibCompressionLevel | int | Specifies the compression level to use for the zlib compressor. This option has no effect if `zlib` is not included in the `"compressors"` URI option. See the » Driver Compression Specification for more information.

`driverOptions`

  driverOptions
  Option | Type | Description
  --- | --- | ---
  autoEncryption | array | Provides options to enable automatic client-side field level encryption. The list of options is described in the table below. Note: Automatic encryption is an enterprise-only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error (see » libmongocrypt: Auto Encryption Allow-List). To bypass automatic encryption for all operations, set `bypassAutoEncryption` to `true`. Automatic encryption requires the authenticated user to have the » listCollections privilege action. Explicit encryption/decryption and automatic decryption is a community feature. The driver can still automatically decrypt when `bypassAutoEncryption` is `true`.
  ca_dir | string | Path to a correctly hashed certificate directory. The system certificate store will be used by default.
  crl_file | string | Path to a certificate revocation list file.
  disableClientPersistence | bool | If `true`, this Manager will use a new libmongoc client, which will not be persisted or shared with other Manager objects. When this Manager object is freed, its client will be destroyed and any connections will be closed. Defaults to `false`. Note: Disabling client persistence is not generally recommended.
  driver | array | Allows a higher level library to append its own metadata to the server handshake. By default, the extension submits its own name, version, and platform (i.e. PHP version) in the handshake. Strings can be specified for the `"name"`, `"version"`, and `"platform"` keys of this array, and will be appended to the respective field(s) in the handshake document. Note: Handshake information is limited to 512 bytes. The extension will truncate handshake data to fit within this 512-byte string. Higher level libraries are encouraged to keep their own metadata concise.
  serverApi | MongoDB\Driver\ServerApi | This option is used to declare a server API version for the manager. If omitted, no API version is declared.

  Options supported by automatic encryption through the `autoEncryption` driver option:

  autoEncryption
  Option | Type | Description
  --- | --- | ---
  keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
  keyVaultNamespace | string | A fully qualified namespace (e.g. `"databaseName.collectionName"`) denoting the collection that contains all data keys used for encryption and decryption. This option is required.
  kmsProviders | array | A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include `"aws"`, `"azure"`, `"gcp"`, `"kmip"`, and `"local"` and at least one must be specified. If an empty document is specified for `"aws"`, `"azure"`, or `"gcp"`, the driver will attempt to configure the provider using » Automatic Credentials. The format for `"aws"` is as follows:
      aws: {
          accessKeyId: <string>,
          secretAccessKey: <string>,
          sessionToken: <optional string>
      }
  The format for `"azure"` is as follows:
      azure: {
          tenantId: <string>,
          clientId: <string>,
          clientSecret: <string>,
          identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
      }
  The format for `"gcp"` is as follows:
      gcp: {
          email: <string>,
          privateKey: <base64 string>|<MongoDB\BSON\Binary>,
          endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
      }
  The format for `"kmip"` is as follows:
      kmip: {
          endpoint: <string>
      }
  The format for `"local"` is as follows:
      local: {
          // 96-byte master key used to encrypt/decrypt data keys
          key: <base64 string>|<MongoDB\BSON\Binary>
      }
  tlsOptions | array | A document containing the TLS configuration for one or more KMS providers. Supported providers include `"aws"`, `"azure"`, `"gcp"`, and `"kmip"`. All providers support the following options:
      <provider>: {
          tlsCaFile: <optional string>,
          tlsCertificateKeyFile: <optional string>,
          tlsCertificateKeyFilePassword: <optional string>,
          tlsDisableOCSPEndpointCheck: <optional bool>
      }
  schemaMap | array|object | Map of collection namespaces to a local JSON schema. This is used to configure automatic encryption. See » Automatic Encryption Rules in the MongoDB manual for more information. It is an error to specify a collection in both `schemaMap` and `encryptedFieldsMap`. Note: Supplying a `schemaMap` provides more security than relying on JSON schemas obtained from the server. It protects against a malicious server advertising a false JSON schema, which could trick the client into sending unencrypted data that should be encrypted. Note: Schemas supplied in the `schemaMap` only apply to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
  bypassAutoEncryption | bool | If `true`, `mongocryptd` will not be spawned automatically. This is used to disable automatic encryption. Defaults to `false`.
  bypassQueryAnalysis | bool | If `true`, automatic analysis of outgoing commands will be disabled and `mongocryptd` will not be spawned automatically. This enables the use case of explicit encryption for querying indexed fields without requiring the enterprise licensed `crypt_shared` library or `mongocryptd` process. Defaults to `false`.
  encryptedFieldsMap | array|object | Map of collection namespaces to an `encryptedFields` document. This is used to configure queryable encryption. See » Field Encryption and Queryability in the MongoDB manual for more information. It is an error to specify a collection in both `encryptedFieldsMap` and `schemaMap`. Note: Supplying an `encryptedFieldsMap` provides more security than relying on an `encryptedFields` obtained from the server. It protects against a malicious server advertising a false `encryptedFields`.
  extraOptions | array | The `extraOptions` relate to the `mongocryptd` process. The following options are supported: `mongocryptdURI` (string): URI to connect to an existing `mongocryptd` process. Defaults to `"mongodb://localhost:27020"`. `mongocryptdBypassSpawn` (bool): If `true`, prevent the driver from spawning `mongocryptd`. Defaults to `false`. `mongocryptdSpawnPath` (string): Absolute path to search for `mongocryptd` binary. Defaults to empty string and consults system paths. `mongocryptdSpawnArgs` (array): Array of string arguments to pass to `mongocryptd` when spawning. Defaults to `["--idleShutdownTimeoutSecs=60"]`. `cryptSharedLibPath` (string): Absolute path to `crypt_shared` shared library. Defaults to empty string and consults system paths. `cryptSharedLibRequired` (bool): If `true`, require the driver to load `crypt_shared`. Defaults to `false`. See the » Client-Side Encryption Specification for more information.

  > Note: Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error. To bypass automatic encryption for all operations, set `bypassAutoEncryption=true` in `autoEncryption`. For more information on allowed operations, see the » Client-Side Encryption Specification.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the `uri` format is invalid

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `"canonicalizeHostname"` URI option was removed. Use the `"CANONICALIZE_HOST_NAME"` property of the `"authMechanismProperties"` URI option instead. The `"gssapiServiceName"` URI option was removed. Use the `"SERVICE_NAME"` property of the `"authMechanismProperties"` URI option instead. The `"safe"` URI option was removed. Use the `"w"` and `"wTimeoutMS"` URI options instead. The `"ssl"` URI option was removed. Use the `"tls"` URI option instead. The `"allow_invalid_hostname"` driver option was removed. Use the `"tlsAllowInvalidHostnames"` URI option instead. The `"ca_file"` driver option was removed. Use the `"tlsCAFile"` URI option instead. The `"context"` driver option was removed. All context options were deprecated in favor of the various URI options related to TLS. The `"pem_file"` driver option was removed. Use the `"tlsCertificateKeyFile"` URI option instead. The `"pem_pwd"` driver option was removed. Use the `"tlsCertificateKeyFilePassword"` URI option instead. The `"weak_cert_validation"` driver option was removed. Use the `"tlsAllowInvalidCertificates"` URI option instead.
PECL mongodb 1.16.0 | The AWS KMS provider for client-side encryption now accepts a `"sessionToken"` option, which can be used to authenticate with temporary AWS credentials. Added `"tlsDisableOCSPEndpointCheck"` to the `"tlsOptions"` field of the `"autoEncryption"` driver option. If an empty document is specified for the `"azure"` or `"gcp"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.
PECL mongodb 1.15.0 | If an empty document is specified for the `"aws"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.
PECL mongodb 1.14.0 | Added the `"bypassQueryAnalysis"` and `"encryptedFieldsMap"` auto encryption options. Additional options pertaining to `crypt_shared` are now supported in the `"extraOptions"` auto encryption option.
PECL mongodb 1.13.0 | Added the `"srvMaxHosts"` and `"srvServiceName"` URI options.
PECL mongodb 1.12.0 | KMIP is now supported as a KMS provider for client-side encryption and may be configured in the `"kmsProviders"` field of the `"autoEncryption"` driver option. Additionally, TLS options for KMS providers may now be configured in the `"tlsOptions"` field of the `"autoEncryption"` driver option.
PECL mongodb 1.11.0 | Added the `"loadBalanced"` URI option.
PECL mongodb 1.10.0 | Added the `"disableClientPersistence"` driver option. Azure and GCP are now supported as KMS providers for client-side encryption and may be configured in the `"kmsProviders"` field of the `"autoEncryption"` driver option. Base64-encoded strings are now accepted as an alternative to MongoDB\BSON\Binary for options within `"kmsProviders"`.
PECL mongodb 1.8.0 | Added the `"directConnection"`, `"tlsDisableCertificateRevocationCheck"`, and `"tlsDisableOCSPEndpointCheck"` URI options. Added the `"driver"` driver option.
PECL mongodb 1.7.0 | Added the `"autoEncryption"` driver option. Specifying any SSL or TLS option via the `driverOptions` parameter will now implicitly enable TLS, as is done for the corresponding URI options.
PECL mongodb 1.6.0 | Added the `"retryReads"`, `"tls"`, `"tlsAllowInvalidCertificates"`, `"tlsAllowInvalidHostnames"`, `"tlsCAFile"`, `"tlsCertificateKeyFile"`, `"tlsCertificateKeyFilePassword"`, and `"tlsInsecure"` URI options. The `"retryWrites"` URI option defaults to `true`. Specifying any SSL or TLS URI option via the connection string or `uriOptions` parameter will now implicitly enable TLS unless `ssl` or `tls` is `false`. TLS is not implicitly enabled for any options in the `driverOptions` parameter, which is unchanged from previous versions.
PECL mongodb 1.5.0 | `"wtimeoutMS"` is now always validated and applied to the write concern. Previously, the option was ignored if `"w"` was <= 1, since the timeout only applies to replication.
PECL mongodb 1.4.0 | Added the `"compressors"`, `"retryWrites"`, and `"zlibCompressionLevel"` URI options.
PECL mongodb 1.3.0 | The `uriOptions` argument now accepts `"authMechanism"` and `"authMechanismProperties"` options. Previously, these options were only supported in the `uri` argument.
PECL mongodb 1.2.0 | The `uri` argument defaults to `"mongodb://127.0.0.1/"`. The default port remains `27017`. Added the `"appname"` URI option. Added the `"allow_invalid_hostname"`, `"ca_file"`, `"ca_dir"`, `"clr_file"`, `"pem_file"`, `"pem_pwd"`, and `"weak_cert_validation"` driver options. The PHP Streams API is no longer used for socket communication. The `"connectTimeoutMS"` URI option now defaults to 10 seconds instead of default_socket_timeout in previous versions. Additionally, the extension no longer supports all SSL context options via the `"context"` driver option.
PECL mongodb 1.1.0 | The `uri` argument is optional and defaults to `"mongodb://localhost:27017/"`.

### Examples

Example #1 MongoDB\Driver\Manager::__construct() basic examples

Connecting to standalone MongoDB node:

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://example.com:27017");
?>`

Connecting to standalone MongoDB node via a Unix domain socket. The socket path may include special characters such as slashes and should be encoded with rawurlencode().

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://" . rawurlencode("/tmp/mongodb-27017.sock"));
?>`

Connecting to a replica set:

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
?>`

Connecting to a sharded cluster (i.e. one or more mongos instances):

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://mongos1.example.com,mongos2.example.com/");
?>`

Connecting to MongoDB with authentication credentials for a particular user and database:

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://myusername:mypassword@example.com/?authSource=databaseName");
?>`

Connecting to MongoDB with authentication credentials for a particular user and database, where the username or password includes special characters (e.g. `@`, `:`, `%`). In the following example, the password string `myp@ss:w%rd` has been manually escaped; however, rawurlencode() may also be used to escape URI components that may contain special characters.

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%25rd@example.com/?authSource=databaseName");
?>`

Connecting to MongoDB with X509 authentication:

`<?php
$manager = new MongoDB\Driver\Manager(
"mongodb://example.com/?ssl=true&authMechanism=MONGODB-X509",
[],
[
"pem_file" => "/path/to/client.pem",
]
);
?>`

### See Also

- Connection handling and persistence
- » MongoDB Connection String Format

# MongoDB\Driver\Manager::createClientEncryption

(mongodb >=1.7.0)

MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object

### Description

final public MongoDB\Driver\Manager::createClientEncryption(array `$options`): MongoDB\Driver\ClientEncryption

Constructs a new MongoDB\Driver\ClientEncryption object with the specified options.

### Parameters

`options`

  options
  Option | Type | Description
  --- | --- | ---
  keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
  keyVaultNamespace | string | A fully qualified namespace (e.g. `"databaseName.collectionName"`) denoting the collection that contains all data keys used for encryption and decryption. This option is required.
  kmsProviders | array | A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include `"aws"`, `"azure"`, `"gcp"`, `"kmip"`, and `"local"` and at least one must be specified. If an empty document is specified for `"aws"`, `"azure"`, or `"gcp"`, the driver will attempt to configure the provider using » Automatic Credentials. The format for `"aws"` is as follows:
      aws: {
          accessKeyId: <string>,
          secretAccessKey: <string>,
          sessionToken: <optional string>
      }
  The format for `"azure"` is as follows:
      azure: {
          tenantId: <string>,
          clientId: <string>,
          clientSecret: <string>,
          identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
      }
  The format for `"gcp"` is as follows:
      gcp: {
          email: <string>,
          privateKey: <base64 string>|<MongoDB\BSON\Binary>,
          endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
      }
  The format for `"kmip"` is as follows:
      kmip: {
          endpoint: <string>
      }
  The format for `"local"` is as follows:
      local: {
          // 96-byte master key used to encrypt/decrypt data keys
          key: <base64 string>|<MongoDB\BSON\Binary>
      }
  tlsOptions | array | A document containing the TLS configuration for one or more KMS providers. Supported providers include `"aws"`, `"azure"`, `"gcp"`, and `"kmip"`. All providers support the following options:
      <provider>: {
          tlsCaFile: <optional string>,
          tlsCertificateKeyFile: <optional string>,
          tlsCertificateKeyFilePassword: <optional string>,
          tlsDisableOCSPEndpointCheck: <optional bool>
      }

### Return Values

Returns a new MongoDB\Driver\ClientEncryption instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support

### Changelog

Version | Description
--- | ---
PECL mongodb 1.16.0 | The AWS KMS provider for client-side encryption now accepts a `"sessionToken"` option, which can be used to authenticate with temporary AWS credentials. Added `"tlsDisableOCSPEndpointCheck"` to the `"tlsOptions"` option. If an empty document is specified for the `"azure"` or `"gcp"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.
PECL mongodb 1.15.0 | If an empty document is specified for the `"aws"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.
PECL mongodb 1.12.0 | KMIP is now supported as a KMS provider for client-side encryption and may be configured in the `"kmsProviders"` option. Added the `"tlsOptions"` option.
PECL mongodb 1.10.0 | Azure and GCP are now supported as KMS providers for client-side encryption and may be configured in the `"kmsProviders"` option. Base64-encoded strings are now accepted as an alternative to MongoDB\BSON\Binary for options within `"kmsProviders"`.

### See Also

- MongoDB\Driver\ClientEncryption::__construct() - Create a new ClientEncryption object
- » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual

# MongoDB\Driver\Manager::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations

### Description

final public MongoDB\Driver\Manager::executeBulkWrite(string `$namespace`, MongoDB\Driver\BulkWrite `$bulk`, ?array `$options` = `null`): MongoDB\Driver\WriteResult

Executes one or more write operations on the primary server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`bulk` (MongoDB\Driver\BulkWrite)

  The write(s) to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

### Return Values

Returns MongoDB\Driver\WriteResult on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` does not contain any write operations.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\WriteConcern instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\WriteConcern object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is now thrown if `bulk` does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

### Examples

Example #1 MongoDB\Driver\Manager::executeBulkWrite() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->insert(['_id' => 4, 'x' => 2]);
$bulk->delete(['x' => 1], ['limit' => 1]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched %d document(s)\n", $result->getMatchedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());
foreach ($result->getUpsertedIds() as $index => $id) {
printf('upsertedId[%d]: ', $index);
var_dump($id);
}
/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}
/* If a write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>`

The above example will output something similar to:

    Inserted 3 document(s)
    Matched  1 document(s)
    Updated  1 document(s)
    Upserted 2 document(s)
    Deleted  1 document(s)
    upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
      ["oid"]=>
      string(24) "54d3adc3ce7a792f4d703756"
    }
    upsertedId[4]: int(3)

### See Also

- MongoDB\Driver\BulkWrite
- MongoDB\Driver\WriteResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Server::executeBulkWrite() - Execute one or more write operations on this server

# MongoDB\Driver\Manager::executeBulkWriteCommand

(mongodb >=2.1.0)

MongoDB\Driver\Manager::executeBulkWriteCommand — Execute write operations using the bulkWrite command

### Description

final public MongoDB\Driver\Manager::executeBulkWriteCommand(MongoDB\Driver\BulkWriteCommand `$bulk`, ?array `$options` = `null`): MongoDB\Driver\BulkWriteCommandResult

Executes one or more write operations on the primary server using the » bulkWrite command introduced in MongoDB 8.0.

A MongoDB\Driver\BulkWriteCommand can be constructed with one or more write operations of varying types (e.g. inserts, updates, and deletes). Each write operation may target a different collection.

The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`bulk` (MongoDB\Driver\BulkWriteCommand)

  The write(s) to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

### Return Values

Returns MongoDB\Driver\BulkWriteCommandResult on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` does not contain any write operations.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` has already been executed. MongoDB\Driver\BulkWriteCommand objects may not be executed multiple times.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\BulkWriteCommandException on any write failure (e.g. command failure, write or write concern error)
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### Examples

Example #1 Mixed write operations

Mixed write operations (i.e. inserts, updates, and deletes) will be sent to the server using a single » bulkWrite command.

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
// Delete documents from both collections
$bulk->deleteMany('db.coll_one', []);
$bulk->deleteMany('db.coll_two', []);
// Insert documents into two collections
$bulk->insertOne('db.coll_one', ['_id' => 1]);
$bulk->insertOne('db.coll_two', ['_id' => 2]);
$bulk->insertOne('db.coll_two', ['_id' => 3]);
// Update a document in "coll_one"
$bulk->updateOne('db.coll_one', ['_id' => 1], ['$set' => ['x' => 1]]);
$result = $manager->executeBulkWriteCommand($bulk);
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
?>`

The above example will output:

    Inserted 3 document(s)
    Updated  1 document(s)

Example #2 Ordered write operations causing an error

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteMany('db.coll', []);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 2]);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 3]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
$result = $e->getPartialResult();
var_dump($e->getWriteErrors());
}
printf("Inserted %d document(s)\n", $result->getInsertedCount());
?>`

The above example will output something similar to:

    array(1) {
      [3]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(78) "E11000 duplicate key error collection: db.coll index: _id_ dup key: { _id: 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(3)
        ["info"]=>
        object(stdClass)#6 (0) {
        }
      }
    }
    Inserted 2 document(s)

### See Also

- MongoDB\Driver\BulkWriteCommand
- MongoDB\Driver\BulkWriteCommandResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Server::executeBulkWriteCommand() - Execute write operations on this server using the bulkWrite command

# MongoDB\Driver\Manager::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeCommand — Execute a database command

### Description

final public MongoDB\Driver\Manager::executeCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Selects a server according to the `"readPreference"` option and executes the command on that server.

This method applies no special logic to the command. The Default values for the `"readPreference"`, `"readConcern"`, and `"writeConcern"` options will be inferred from an active transaction (indicated by the `"session"` option). If there is no active transaction, a primary read preference will be used for server selection.

Default values will not be inferred from the connection URI. Users are therefore encouraged to use specific read and/or write command methods if possible.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\ReadPreference instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\ReadPreference object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

### Examples

Example #1 MongoDB\Driver\Manager::executeCommand() with a command returning a single result document

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);
try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
/* The ping command returns a single result document, so we need to access the
* first result in the cursor. */
$response = $cursor->toArray()[0];
var_dump($response);
?>`

The above example will output:

    array(1) {
      ["ok"]=>
      float(1)
    }

Example #2 MongoDB\Driver\Manager::executeCommand() with a command returning a cursor

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);
$command = new MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => [
['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
],
'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);
/* The aggregate command can optionally return its results in a cursor instead
* of a single result document. In this case, we can iterate on the cursor
* directly to access those results. */
foreach ($cursor as $document) {
var_dump($document);
}
?>`

The above example will output:

    object(stdClass)#6 (2) {
      ["_id"]=>
      string(3) "bar"
      ["sum"]=>
      int(10)
    }
    object(stdClass)#7 (2) {
      ["_id"]=>
      string(3) "foo"
      ["sum"]=>
      int(2)
    }

Example #3 Limiting execution time for a command

The execution time of a command may be limited by specifying a value for `"maxTimeMS"` in the MongoDB\Driver\Command document. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command([
'count' => 'collection',
'query' => ['x' => ['$gt' => 1]],
'maxTimeMS' => 1000,
]);
$cursor = $manager->executeCommand('db', $command);
var_dump($cursor->toArray()[0]);
?>`

If the command fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

### Notes

> Note: If a secondary `readPreference` is used, it is the caller's responsibility to ensure that the `command` can be executed on a secondary. No validation is done by the driver.

> Note: This method does not default to using the read preference from the MongoDB Connection URI. Applications in need of that behavior should consider using MongoDB\Driver\Manager::executeReadCommand().

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
- MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
- MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server

# MongoDB\Driver\Manager::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeQuery — Execute a database query

### Description

final public MongoDB\Driver\Manager::executeQuery(string `$namespace`, MongoDB\Driver\Query `$query`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Selects a server according to the `"readPreference"` option and executes the query on that server.

Default values for the `"readPreference"` option and Query's `"readConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`query` (MongoDB\Driver\Query)

  The query to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\ReadPreference instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\ReadPreference object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

### Examples

Example #1 MongoDB\Driver\Manager::executeQuery() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);
foreach ($cursor as $document) {
var_dump($document);
}
?>`

The above example will output:

    object(stdClass)#6 (1) {
      ["x"]=>
      int(3)
    }
    object(stdClass)#7 (1) {
      ["x"]=>
      int(2)
    }

Example #2 Limiting execution time for a query

The `"maxTimeMS"` MongoDB\Driver\Query option may be used to limit the execution time of a query. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$filter = ['x' => ['$gt' => 1]];
$options = [
'maxTimeMS' => 1000,
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);
foreach ($cursor as $document) {
var_dump($document);
}
?>`

If the query fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

### See Also

- MongoDB\Driver\Cursor
- MongoDB\Driver\Query
- MongoDB\Driver\ReadPreference
- MongoDB\Driver\Server::executeQuery() - Execute a database query on this server

# MongoDB\Driver\Manager::executeReadCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads

### Description

final public MongoDB\Driver\Manager::executeReadCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Selects a server according to the `"readPreference"` option and executes the command on that server.

This method will apply logic that is specific to commands that read (e.g. » distinct). Default values for the `"readPreference"` and `"readConcern"` options will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Manager::executeCommand() - Execute a database command
- MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
- MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
- MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server

# MongoDB\Driver\Manager::executeReadWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes

### Description

final public MongoDB\Driver\Manager::executeReadWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on the primary server.

This method will apply logic that is specific to commands that read and write (e.g. » aggregate). Default values for the `"readConcern"` and `"writeConcern"` options will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Manager::executeCommand() - Execute a database command
- MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
- MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
- MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server

# MongoDB\Driver\Manager::executeWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes

### Description

final public MongoDB\Driver\Manager::executeWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on the primary server.

This method will apply logic that is specific to commands that write (e.g. » drop). The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

> Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use MongoDB\Driver\Manager::executeBulkWrite() for those operations.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Manager::executeCommand() - Execute a database command
- MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
- MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
- MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server

# MongoDB\Driver\Manager::getEncryptedFieldsMap

(mongodb >=1.14.0)

MongoDB\Driver\Manager::getEncryptedFieldsMap — Return the encryptedFieldsMap auto encryption option for the Manager

### Description

final public MongoDB\Driver\Manager::getEncryptedFieldsMap(): array|object|null

Returns the `encryptedFieldsMap` auto encryption option for the Manager, if specified.

### Parameters

This function has no parameters.

### Return Values

The `encryptedFieldsMap` auto encryption option for the Manager, or `null` if it was not specified.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

# MongoDB\Driver\Manager::getReadConcern

(mongodb >=1.1.0)

MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager

### Description

final public MongoDB\Driver\Manager::getReadConcern(): MongoDB\Driver\ReadConcern

Returns the MongoDB\Driver\ReadConcern for the Manager, which is derived from its URI options. This is the default read concern for queries and commands executed on the Manager.

### Parameters

This function has no parameters.

### Return Values

The MongoDB\Driver\ReadConcern for the Manager.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Manager::getReadConcern() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadConcern());
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readConcernLevel=local');
var_dump($manager->getReadConcern());
?>`

The above example will output something similar to:

    object(MongoDB\Driver\ReadConcern)#2 (0) {
    }
    object(MongoDB\Driver\ReadConcern)#1 (1) {
      ["level"]=>
      string(5) "local"
    }

### See Also

- MongoDB\Driver\ReadConcern
- MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

# MongoDB\Driver\Manager::getReadPreference

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager

### Description

final public MongoDB\Driver\Manager::getReadPreference(): MongoDB\Driver\ReadPreference

Returns the MongoDB\Driver\ReadPreference for the Manager, which is derived from its URI options. This is the default read preference for queries and commands executed on the Manager.

### Parameters

This function has no parameters.

### Return Values

The MongoDB\Driver\ReadPreference for the Manager.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Manager::getReadPreference() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadPreference());
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=');
var_dump($manager->getReadPreference());
?>`

The above example will output something similar to:

    object(MongoDB\Driver\ReadPreference)#2 (1) {
      ["mode"]=>
      string(7) "primary"
    }
    object(MongoDB\Driver\ReadPreference)#1 (2) {
      ["mode"]=>
      string(18) "secondaryPreferred"
      ["tags"]=>
      array(3) {
        [0]=>
        object(stdClass)#3 (2) {
          ["dc"]=>
          string(2) "ny"
          ["rack"]=>
          string(1) "1"
        }
        [1]=>
        object(stdClass)#4 (1) {
          ["dc"]=>
          string(2) "ny"
        }
        [2]=>
        object(stdClass)#5 (0) {
        }
      }
    }

### See Also

- MongoDB\Driver\ReadPreference
- MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

# MongoDB\Driver\Manager::getServers

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected

### Description

final public MongoDB\Driver\Manager::getServers(): array

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

> Note: Since the driver connects to the database lazily, this method may return an empty array if called before executing an operation on the MongoDB\Driver\Manager.

### Parameters

This function has no parameters.

### Return Values

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Manager::getServers() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
/* The driver connects to the database server lazily, so Manager::getServers()
* may initially return an empty array. */
var_dump($manager->getServers());
$command = new MongoDB\Driver\Command(['ping' => 1]);
$manager->executeCommand('db', $command);
var_dump($manager->getServers());
?>`

The above example will output something similar to:

    array(0) {
    }
    array(1) {
      [0]=>
      object(MongoDB\Driver\Server)#3 (10) {
        ["host"]=>
        string(9) "localhost"
        ["port"]=>
        int(27017)
        ["type"]=>
        int(1)
        ["is_primary"]=>
        bool(false)
        ["is_secondary"]=>
        bool(false)
        ["is_arbiter"]=>
        bool(false)
        ["is_hidden"]=>
        bool(false)
        ["is_passive"]=>
        bool(false)
        ["last_hello_response"]=>
        array(8) {
          ["isWritablePrimary"]=>
          bool(true)
          ["maxBsonObjectSize"]=>
          int(16777216)
          ["maxMessageSizeBytes"]=>
          int(48000000)
          ["maxWriteBatchSize"]=>
          int(1000)
          ["localTime"]=>
          object(MongoDB\BSON\UTCDateTime)#4 (1) {
            ["milliseconds"]=>
            int(1447267964517)
          }
          ["maxWireVersion"]=>
          int(3)
          ["minWireVersion"]=>
          int(0)
          ["ok"]=>
          float(1)
        }
        ["round_trip_time"]=>
        int(554)
      }
    }

### See Also

- MongoDB\Driver\Server
- MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference

# MongoDB\Driver\Manager::getWriteConcern

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager

### Description

final public MongoDB\Driver\Manager::getWriteConcern(): MongoDB\Driver\WriteConcern

Returns the MongoDB\Driver\WriteConcern for the Manager, which is derived from its URI options. This is the default write concern for writes and commands executed on the Manager.

### Parameters

This function has no parameters.

### Return Values

The MongoDB\Driver\WriteConcern for the Manager.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Manager::getWriteConcern() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getWriteConcern());
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?w=majority&wtimeoutMS=2000');
var_dump($manager->getWriteConcern());
?>`

The above example will output something similar to:

    object(MongoDB\Driver\WriteConcern)#2 (0) {
    }
    object(MongoDB\Driver\WriteConcern)#1 (2) {
      ["w"]=>
      string(8) "majority"
      ["wtimeout"]=>
      int(2000)
    }

### See Also

- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

# MongoDB\Driver\Manager::removeSubscriber

(mongodb >=1.10.0)

MongoDB\Driver\Manager::removeSubscriber — Unregisters a monitoring event subscriber with this Manager

### Description

final public MongoDB\Driver\Manager::removeSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void

Unregisters a monitoring event subscriber with this Manager.

> Note: If `subscriber` is not already registered with this Manager, this function is a no-op.

### Parameters

`subscriber` (MongoDB\Driver\Monitoring\Subscriber)

  A monitoring event subscriber to unregister with this Manager.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
- MongoDB\Driver\Monitoring\Subscriber
- MongoDB\Driver\Monitoring\CommandSubscriber
- MongoDB\Driver\Monitoring\removeSubscriber() - Unregisters a monitoring event subscriber globally
- Application Performance Monitoring (APM)

# MongoDB\Driver\Manager::selectServer

(mongodb >=1.0.0)

MongoDB\Driver\Manager::selectServer — Select a server matching a read preference

### Description

final public MongoDB\Driver\Manager::selectServer(?MongoDB\Driver\ReadPreference `$readPreference` = `null`): MongoDB\Driver\Server

Selects a MongoDB\Driver\Server matching `readPreference`. If `readPreference` is `null` or omitted, the primary server will be selected by default. This may be used to preselect a server in order to perform version checking before executing an operation.

> Note: Unlike MongoDB\Driver\Manager::getServers(), this method will initialize database connections and perform server discovery if necessary. See the » Server Selection Specification for additional information.

### Parameters

`readPreference` (MongoDB\Driver\ReadPreference)

  The read preference to use for selecting a server. If `null` or omitted, the primary server will be selected by default.

### Return Values

Returns a MongoDB\Driver\Server matching the read preference.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException if a server matching the read preference could not be found.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | The `readPreference` is now optional. If `null` or omitted, the primary server will be selected by default.

### See Also

- MongoDB\Driver\Server
- MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
- » Server Selection Specification

# MongoDB\Driver\Manager::startSession

(mongodb >=1.4.0)

MongoDB\Driver\Manager::startSession — Start a new client session for use with this client

### Description

final public MongoDB\Driver\Manager::startSession(?array `$options` = `null`): MongoDB\Driver\Session

Creates a MongoDB\Driver\Session for the given options. The session may then be specified when executing commands, queries, and write operations.

> Note: A MongoDB\Driver\Session can only be used with the MongoDB\Driver\Manager from which it was created.

### Parameters

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  causalConsistency | bool | Configure causal consistency in a session. If `true`, each operation in the session will be causally ordered after the previous read or write operation. Set to `false` to disable causal consistency. See » Casual Consistency in the MongoDB manual for more information. | `true`
  defaultTransactionOptions | array | Default options to apply to newly created transactions. These options are used unless they are overridden when a transaction is started with different value for each option.
  options
  Option | Type | Description
  --- | --- | ---
  maxCommitTimeMS | integer | The maximum amount of time in milliseconds to allow a single `commitTransaction` command to run. If specified, `maxCommitTimeMS` must be a signed 32-bit integer greater than or equal to zero.
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.
  This option is available in MongoDB 4.0+. | `[]`
  snapshot | bool | Configure snapshot reads in a session. If `true`, a timestamp will be obtained from the first supported read operation in the session (i.e. `find`, `aggregate`, or unsharded `distinct`). Subsequent read operations within the session will then utilize a `"snapshot"` read concern level to read majority-committed data from that timestamp. Set to `false` to disable snapshot reads. Snapshot reads require MongoDB 5.0+ and cannot be used with causal consistency, transactions, or write operations. If `"snapshot"` is `true`, `"causalConsistency"` will default to `false`. See » Read Concern "snapshot" in the MongoDB manual for more information. | `false`

### Return Values

Returns a MongoDB\Driver\Session.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"causalConsistency"` and `"snapshot"` options are both `true`.
- Throws MongoDB\Driver\Exception\RuntimeException if the session could not be created (e.g. libmongoc does not support crypto).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | The `"snapshot"` option was added.
PECL mongodb 1.6.0 | The `"maxCommitTimeMS"` option was added to `"defaultTransactionOptions"`.
PECL mongodb 1.5.0 | The `"defaultTransactionOptions"` option was added.

### See Also

- MongoDB\Driver\Session
- » Casual Consistency in the MongoDB manual

## Table of Contents

- MongoDB\Driver\Manager::addSubscriber — Registers a monitoring event subscriber with this Manager
- MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
- MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object
- MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
- MongoDB\Driver\Manager::executeBulkWriteCommand — Execute write operations using the bulkWrite command
- MongoDB\Driver\Manager::executeCommand — Execute a database command
- MongoDB\Driver\Manager::executeQuery — Execute a database query
- MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads
- MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes
- MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes
- MongoDB\Driver\Manager::getEncryptedFieldsMap — Return the encryptedFieldsMap auto encryption option for the Manager
- MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
- MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
- MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
- MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
- MongoDB\Driver\Manager::removeSubscriber — Unregisters a monitoring event subscriber with this Manager
- MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
- MongoDB\Driver\Manager::startSession — Start a new client session for use with this client

# The MongoDB\Driver\Command class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide Command Helpers the MongoDB\Driver\Command object should be composed.

## Class synopsis

final class MongoDB\Driver\Command {
/* Methods */
final public __construct(array|object `$document`, ?array `$commandOptions` = `null`)
}

## Examples

Example #1 Composing MongoDB\Driver\Command to provide a helper to create collections

`<?php
class CreateCollection {
protected $cmd = array();
function __construct($collectionName) {
$this->cmd["create"] = (string) $collectionName;
}
function setCappedCollection($maxBytes, $maxDocuments = false) {
$this->cmd["capped"] = true;
$this->cmd["size"] = (int) $maxBytes;
if ($maxDocuments) {
$this->cmd["max"] = (int) $maxDocuments;
}
}
function usePowerOf2Sizes($bool) {
if ($bool) {
$this->cmd["flags"] = 1;
} else {
$this->cmd["flags"] = 0;
}
}
function setFlags($flags) {
$this->cmd["flags"] = (int) $flags;
}
function getCommand() {
return new MongoDB\Driver\Command($this->cmd);
}
function getCollectionName() {
return $this->cmd["create"];
}
}
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 * 1024);
try {
$command = $createCollection->getCommand();
$cursor = $manager->executeCommand("databaseName", $command);
$response = $cursor->toArray()[0];
var_dump($response);
$collstats = ["collstats" => $createCollection->getCollectionName()];
$cursor = $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
$response = $cursor->toArray()[0];
var_dump($response);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
?>`

The above example will output:

    object(MongoDB\Driver\Command)#3 (1) {
      ["command"]=>
      array(3) {
        ["create"]=>
        string(16) "cappedCollection"
        ["capped"]=>
        bool(true)
        ["size"]=>
        int(65536)
      }
    }
    array(1) {
      ["ok"]=>
      float(1)
    }
    array(16) {
      ["ns"]=>
      string(29) "databaseName.cappedCollection"
      ["count"]=>
      int(0)
      ["size"]=>
      int(0)
      ["numExtents"]=>
      int(1)
      ["storageSize"]=>
      int(65536)
      ["nindexes"]=>
      int(1)
      ["lastExtentSize"]=>
      float(65536)
      ["paddingFactor"]=>
      float(1)
      ["paddingFactorNote"]=>
      string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
      ["userFlags"]=>
      int(0)
      ["capped"]=>
      bool(true)
      ["max"]=>
      int(9223372036854775807)
      ["maxSize"]=>
      int(65536)
      ["totalIndexSize"]=>
      int(8176)
      ["indexSizes"]=>
      object(stdClass)#4 (1) {
        ["_id_"]=>
        int(8176)
      }
      ["ok"]=>
      float(1)
    }

# MongoDB\Driver\Command::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Command::__construct — Create a new Command

### Description

final public MongoDB\Driver\Command::__construct(array|object `$document`, ?array `$commandOptions` = `null`)

Constructs a new MongoDB\Driver\Command, which is an immutable value object that represents a database command. The command may then be executed with MongoDB\Driver\Manager::executeCommand().

The complete command document, which includes the command name and its options, should be expressed in the `document` parameter. The `commandOptions` parameter is only used to specify options related to the execution of the command and the resulting MongoDB\Driver\Cursor.

### Parameters

`document`

  The complete command document, which will be sent to the server.

`commandOptions`

  > Note: Do not use this parameter to specify options described in the command's reference in the MongoDB manual. This parameter should only be used for the options explicitly listed below.

  commandOptions
  Option | Type | Description
  --- | --- | ---
  maxAwaitTimeMS | int | Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available. This option should only be used in conjunction with commands that return a tailable cursor (e.g. » Change Streams).

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.4.0 | Added a second `commandOptions` argument, which supports the `"maxAwaitTimeMS"` option.

### Examples

Example #1 MongoDB\Driver\Command::__construct() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array("buildinfo" => 1));
try {
$cursor = $manager->executeCommand("admin", $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
var_dump($response);
?>`

The above example will output something similar to:

    array(13) {
      ["version"]=>
      string(14) "2.8.0-rc2-pre-"
      ["gitVersion"]=>
      string(62) "b743d7158f7642f4da6b7eac8320374b3b88dc2e modules: subscription"
      ["OpenSSLVersion"]=>
      string(25) "OpenSSL 1.0.1f 6 Jan 2014"
      ["sysInfo"]=>
      string(104) "Linux infant 3.16.0-24-generic #32-Ubuntu SMP Tue Oct 28 13:07:32 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49"
      ["loaderFlags"]=>
      string(91) "-fPIC -pthread -Wl,-z,now -rdynamic -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,-E"
      ["compilerFlags"]=>
      string(301) "-Wnon-virtual-dtor -Woverloaded-virtual -std=c++11 -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -pipe -Werror -O3 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -fno-builtin-memcmp -std=c99"
      ["allocator"]=>
      string(8) "tcmalloc"
      ["versionArray"]=>
      array(4) {
        [0]=>
        int(2)
        [1]=>
        int(8)
        [2]=>
        int(0)
        [3]=>
        int(-8)
      }
      ["javascriptEngine"]=>
      string(2) "V8"
      ["bits"]=>
      int(64)
      ["debug"]=>
      bool(false)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["ok"]=>
      float(1)
    }

Example #2 MongoDB\Driver\Command::__construct() example

Commands can accept options as well, as part of the normal structure that you create to send to the server. For example, the `maxTimeMS` option can be passed with most commands to restrict the amount of time a specific command can run for on the server.

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(
array(
"distinct" => "beer",
"key" => "beer_name",
"maxTimeMS" => 10,
)
);
try {
$cursor = $manager->executeCommand("beerdb", $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
var_dump($response);
?>`

The above example will output something similar to:

operation exceeded time limit

### See Also

- MongoDB\Driver\Manager::executeCommand() - Execute a database command
- MongoDB\Driver\Cursor

## Table of Contents

- MongoDB\Driver\Command::__construct — Create a new Command

# The MongoDB\Driver\Query class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\Query class is a value object that represents a database query.

## Class synopsis

final class MongoDB\Driver\Query {
/* Methods */
final public __construct(array|object `$filter`, ?array `$queryOptions` = `null`)
}

# MongoDB\Driver\Query::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Query::__construct — Create a new Query

### Description

final public MongoDB\Driver\Query::__construct(array|object `$filter`, ?array `$queryOptions` = `null`)

Constructs a new MongoDB\Driver\Query, which is an immutable value object that represents a database query. The query may then be executed with MongoDB\Driver\Manager::executeQuery().

### Parameters

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`queryOptions`

  queryOptions
  Option | Type | Description
  --- | --- | ---
  allowDiskUse | bool | Allows MongoDB to use temporary disk files to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.
  allowPartialResults | bool | For queries against a sharded collection, returns partial results from the mongos if some shards are unavailable instead of throwing an error. Falls back to the deprecated `"partial"` option if not specified.
  awaitData | bool | Use in conjunction with the `"tailable"` option to block a getMore operation on the cursor temporarily if at the end of data rather than returning no data. After a timeout period, the query returns as normal.
  batchSize | int | The number of documents to return in the first batch. Defaults to 101. A batch size of 0 means that the cursor will be established, but no documents will be returned in the first batch. In versions of MongoDB before 3.2, where queries use the legacy wire protocol OP_QUERY, a batch size of 1 will close the cursor irrespective of the number of matched documents.
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  comment | mixed | An arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs. The comment can be any valid BSON type for MongoDB 4.4+. Earlier server versions only support string values. Falls back to the deprecated `"$comment"` modifier if not specified.
  exhaust | bool | Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection. This option is not supported by the find command in MongoDB 3.2+ and will force the driver to use the legacy wire protocol version (i.e. OP_QUERY).
  explain | bool | If `true`, the returned MongoDB\Driver\Cursor will contain a single document that describes the process and indexes used to return the query. Falls back to the deprecated `"$explain"` modifier if not specified. This option is not supported by the find command in MongoDB 3.2+ and will only be respected when using the legacy wire protocol version (i.e. OP_QUERY). The » explain command should be used on MongoDB 3.0+.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index. Falls back to the deprecated `"hint"` option if not specified.
  let | array|object | Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. `$$var`). This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.
  limit | int | The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.
  max | array|object | The exclusive upper bound for a specific index. Falls back to the deprecated `"$max"` modifier if not specified.
  maxAwaitTimeMS | int | Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available. This option should only be used in conjunction with the `"tailable"` and `"awaitData"` options.
  maxTimeMS | int | The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point. Falls back to the deprecated `"$maxTimeMS"` modifier if not specified.
  min | array|object | The inclusive lower bound for a specific index. Falls back to the deprecated `"$min"` modifier if not specified.
  noCursorTimeout | bool | Prevents the server from timing out idle cursors after an inactivity period (10 minutes).
  projection | array|object | The » projection specification to determine which fields to include in the returned documents. If you are using the ODM functionality to deserialise documents as their original PHP class, make sure that you include the __pclass field in the projection. This is required for the deserialization to work and without it, the extension will return (by default) a stdClass object instead.
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. By default, the read concern from the MongoDB Connection URI will be used. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  returnKey | bool | If `true`, returns only the index keys in the resulting documents. Default value is `false`. If `true` and the find command does not use an index, the returned documents will be empty. Falls back to the deprecated `"$returnKey"` modifier if not specified.
  showRecordId | bool | Determines whether to return the record identifier for each document. If `true`, adds a top-level `"$recordId"` field to the returned documents. Falls back to the deprecated `"$showDiskLoc"` modifier if not specified.
  singleBatch | bool | Determines whether to close the cursor after the first batch. Defaults to `false`.
  skip | int | Number of documents to skip. Defaults to 0.
  sort | array|object | The sort specification for the ordering of the results. Falls back to the deprecated `"$orderby"` modifier if not specified.
  tailable | bool | Returns a tailable cursor for a capped collection.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `"partial"` option was removed. Use the `"allowPartialResults"` option instead. The `"maxScan"` option was removed. Support for this option was removed in MongoDB 4.2. The `"modifiers"` option was removed. This option was used for legacy query modifiers, which are all deprecated. The `"oplogReplay"` option was removed. It is ignored in MongoDB 4.4 and newer. The `"snapshot"` option was removed. Support for this option was removed in MongoDB 4.0. A negative value for the `"limit"` option no longer implies `true` for the `"singleBatch"` option. To only receive a single batch of results, combine a positive `"limit"` value with the `"singleBatch"` option.
PECL mongodb 1.14.0 | Added the `"let"` option. The `"comment"` option now accepts any type.
PECL mongodb 1.8.0 | Added the `"allowDiskUse"` option. The `"oplogReplay"` option is deprecated.
PECL mongodb 1.5.0 | The `"maxScan"` and `"snapshot"` options are deprecated.
PECL mongodb 1.3.0 | Added the `"maxAwaitTimeMS"` option.
PECL mongodb 1.2.0 | Added the `"allowPartialResults"`, `"collation"`, `"comment"`, `"hint"`, `"max"`, `"maxScan"`, `"maxTimeMS"`, `"min"`, `"returnKey"`, `"showRecordId"`, and `"snapshot"` options. Renamed the `"partial"` option to `"allowPartialResults"`. For backwards compatibility, `"partial"` will still be read if `"allowPartialResults"` is not specified. Removed the legacy `"secondaryOk"` option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the `secondaryOk` bit as needed in accordance with the » Server Selection Specification.
PECL mongodb 1.1.0 | Added the `"readConcern"` option.

### Examples

Example #1 MongoDB\Driver\Query::__construct() example

`<?php
/* Select only documents authord by "bjori" with at least 100 views */
$filter = [
'author' => 'bjori',
'views' => [
'$gte' => 100,
],
];
$options = [
/* Only return the following fields in the matching documents */
'projection' => [
'title' => 1,
'article' => 1,
],
/* Return the documents in descending order of views */
'sort' => [
'views' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, ['readPreference' => $readPreference]);
foreach($cursor as $document) {
var_dump($document);
}
?>`

### See Also

- MongoDB\Driver\Manager::executeQuery() - Execute a database query
- MongoDB\Driver\Cursor

## Table of Contents

- MongoDB\Driver\Query::__construct — Create a new Query

# The MongoDB\Driver\BulkWrite class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\BulkWrite collects one or more write operations that should be sent to the server. After adding any number of insert, update, and delete operations, the collection may be executed via MongoDB\Driver\Manager::executeBulkWrite().

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

## Class synopsis

final class MongoDB\Driver\BulkWrite implements Countable {
/* Methods */
public __construct(?array `$options` = `null`)
public count(): int
public delete(array|object `$filter`, ?array `$deleteOptions` = `null`): void
public insert(array|object `$document`): mixed
public update(array|object `$filter`, array|object `$newObj`, ?array `$updateOptions` = `null`): void
}

## Examples

Example #1 Mixed write operations are grouped by type

Mixed write operations (i.e. inserts, updates, and deletes) will be assembled into typed write commands to be sent sequentially to the server.

`<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);
?>`

Will result in four write commands (i.e. roundtrips) being executed. Since the operations are ordered, the third insertion cannot be sent until the preceding update is executed.

Example #2 Ordered write operations causing an error

`<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3, 'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4, 'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();
// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}
// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("Other error: %s\n", $e->getMessage());
exit;
}
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
?>`

The above example will output:

    Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
    Inserted 4 document(s)
    Updated  2 document(s)

If the write concern could not be fullfilled, the example above would output something like:

    waiting for replication timed out (64): array (
      'wtimeout' => true,
    )
    Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000)
    Inserted 4 document(s)
    Updated  2 document(s)

If we execute the example above, but allow for unordered writes:

`<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */
?>`

The above example will output:

    Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
    Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000)
    Inserted 5 document(s)
    Updated  2 document(s)

## See Also

- MongoDB\Driver\Manager::executeBulkWrite()
- MongoDB\Driver\WriteResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\WriteConcernError
- MongoDB\Driver\WriteError

# MongoDB\Driver\BulkWrite::__construct

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite

### Description

public MongoDB\Driver\BulkWrite::__construct(?array `$options` = `null`)

Constructs a new MongoDB\Driver\BulkWrite, which is a mutable object to which one or more write operations may be added. The write(s) may then be executed with MongoDB\Driver\Manager::executeBulkWrite().

### Parameters

`options` (array)

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  bypassDocumentValidation | bool | If `true`, allows insert and update operations to circumvent document level validation. This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation. | `false`
  comment | mixed | An arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs. This option is available in MongoDB 4.4+ and will result in an exception at execution time if specified for an older server version.
  let | array|object | Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. `$$var`). This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.
  ordered | bool | Ordered operations (`true`) are executed serially on the MongoDB server, while unordered operations (`false`) are sent to the server in an arbitrary order and may be executed in parallel. | `true`

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.14.0 | Added the `"comment"` and `"let"` options.
PECL mongodb 1.1.0 | Added the `"bypassDocumentValidation"` option.

### Examples

Example #1 MongoDB\Driver\BulkWrite::__construct() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(
['x' => 2],
['$set' => ['x' => 1]],
['limit' => 1, 'upsert' => false]
);
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->update(
['_id' => 3],
['$set' => ['x' => 3]],
['limit' => 1, 'upsert' => true]
);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(1);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();
// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}
// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("Other error: %s\n", $e->getMessage());
exit;
}
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());
?>`

The above example will output:

    Inserted 2 document(s)
    Updated  1 document(s)
    Upserted 1 document(s)
    Deleted  1 document(s)

### See Also

- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
- MongoDB\Driver\WriteResult

# MongoDB\Driver\BulkWrite::count

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk

### Description

public MongoDB\Driver\BulkWrite::count(): int

Returns the number of write operations added to the MongoDB\Driver\BulkWrite object.

### Parameters

This function has no parameters.

### Return Values

Returns number of write operations added to the MongoDB\Driver\BulkWrite object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.2.0 | Returns the number of write operations added to the MongoDB\Driver\BulkWrite object. Earlier versions returned the expected number of client-to-server roundtrips required to execute all write operations.

### Examples

Example #1 MongoDB\Driver\BulkWrite::count() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->delete(['x' => 1]);
var_dump(count($bulk));
?>`

The above example will output:

    int(4)

# MongoDB\Driver\BulkWrite::delete

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk

### Description

public MongoDB\Driver\BulkWrite::delete(array|object `$filter`, ?array `$deleteOptions` = `null`): void

Adds a delete operation to the MongoDB\Driver\BulkWrite.

### Parameters

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`deleteOptions`

  deleteOptions
  Option | Type | Description | Default
  --- | --- | --- | ---
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index. This option is available in MongoDB 4.4+ and will result in an exception at execution time if specified for an older server version.
  limit | bool | Delete all matching documents (`false`), or only the first matching document (`true`) | `false`

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.8.0 | Added the `"hint"` option.
PECL mongodb 1.2.0 | Added the `"collation"` option.

### Examples

Example #1 MongoDB\Driver\BulkWrite::delete() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->delete(['x' => 2], ['limit' => 0]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);
?>`

### See Also

- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
- MongoDB\Driver\WriteResult

# MongoDB\Driver\BulkWrite::insert

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk

### Description

public MongoDB\Driver\BulkWrite::insert(array|object `$document`): mixed

Adds an insert operation to the MongoDB\Driver\BulkWrite.

### Parameters

`document` (array|object)

  A document to insert.

### Return Values

Returns the `_id` of the inserted document. If the `document` did not have an `_id`, the MongoDB\BSON\ObjectId generated for the insert will be returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.3.0 | The `_id` of the inserted document is always returned. Previously, the method only returned a value if a MongoDB\BSON\ObjectId was generated.

### Examples

Example #1 MongoDB\Driver\BulkWrite::insert() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite;
$doc1 = ['x' => 1];
$doc2 = ['_id' => 'custom-id', 'x' => 2];
$doc3 = ['_id' => new MongoDB\BSON\ObjectId('0123456789abcdef01234567'), 'x' => 3];
$id1 = $bulk->insert($doc1);
$id2 = $bulk->insert($doc2);
$id3 = $bulk->insert($doc3);
var_dump($id1, $id2, $id3);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);
?>`

The above example will output something similar to:

    object(MongoDB\BSON\ObjectId)#3 (1) {
      ["oid"]=>
      string(24) "67f58058d1a0aa2fd80d55d0"
    }
    string(9) "custom-id"
    object(MongoDB\BSON\ObjectId)#4 (1) {
      ["oid"]=>
      string(24) "0123456789abcdef01234567"
    }

### See Also

- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
- MongoDB\Driver\WriteResult
- MongoDB\BSON\ObjectId
- MongoDB\BSON\Persistable

# MongoDB\Driver\BulkWrite::update

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk

### Description

public MongoDB\Driver\BulkWrite::update(array|object `$filter`, array|object `$newObj`, ?array `$updateOptions` = `null`): void

Adds an update operation to the MongoDB\Driver\BulkWrite.

### Parameters

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`newObj` (array|object)

  A document containing either update operators (e.g. `$set`), a replacement document (i.e. only `field:value` expressions), or an » aggregation pipeline.

`updateOptions`

  updateOptions
  Option | Type | Description | Default
  --- | --- | --- | ---
  arrayFilters | array | An array of filter documents that determines which array elements to modify for an update operation on an array field. See » Specify arrayFilters for Array Update Operations in the MongoDB manual for more information. This option is available in MongoDB 3.6+ and will result in an exception at execution time if specified for an older server version.
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index. This option is available in MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version.
  multi | bool | Update only the first matching document if `false`, or all matching documents `true`. This option cannot be `true` if `newObj` is a replacement document. | `false`
  sort | array|object | Specify which document the operation updates if the query matches multiple documents. The first document matched by the sort order will be updated. This option cannot be used if `"multi"` is `true`. This option is available in MongoDB 8.0+ and will result in an exception at execution time if specified for an older server version.
  upsert | bool | If `filter` does not match an existing document, insert a single document. The document will be created from `newObj` if it is a replacement document (i.e. no update operators); otherwise, the operators in `newObj` will be applied to `filter` to create the new document. | `false`

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.21.0 | Added the `"sort"` option.
PECL mongodb 1.7.0 | Added the `"hint"` option.
PECL mongodb 1.6.0 | The `newObj` parameter now accepts an aggregation pipeline. This feature requires MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version.
PECL mongodb 1.5.0 | Using the `"arrayFilters"` option will result in an exception at execution time if unsupported by the server. Previously, no exception would be thrown and the option may have been ignored.
PECL mongodb 1.4.0 | Added the `"arrayFilters"` option.
PECL mongodb 1.2.0 | Added the `"collation"` option.

### Examples

Example #1 MongoDB\Driver\BulkWrite::update() example

`<?php
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['x' => 2],
['$set' => ['y' => 3]],
['multi' => false, 'upsert' => false]
);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);
?>`

### See Also

- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
- MongoDB\Driver\WriteResult

## Table of Contents

- MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
- MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
- MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
- MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
- MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk

# The MongoDB\Driver\BulkWriteCommand class

(mongodb >=2.1.0)

## Introduction

MongoDB\Driver\BulkWriteCommand collects one or more write operations that should be sent to the server using the » bulkWrite command introduced in MongoDB 8.0. After adding any number of insert, update, and delete operations, the command may be executed via MongoDB\Driver\Manager::executeBulkWriteCommand().

Unlike MongoDB\Driver\BulkWrite, where all write operations must target the same collection, each write operation within MongoDB\Driver\BulkWriteCommand may target a different collection.

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

## Class synopsis

final class MongoDB\Driver\BulkWriteCommand implements Countable {
/* Methods */
public __construct(?array `$options` = `null`)
public count(): int
public deleteMany(string `$namespace`, array|object `$filter`, ?array `$options` = `null`): void
public deleteOne(string `$namespace`, array|object `$filter`, ?array `$options` = `null`): void
public insertOne(string `$namespace`, array|object `$document`): mixed
public replaceOne(
string `$namespace`,
array|object `$filter`,
array|object `$replacement`,
?array `$options` = `null`
): void
public updateMany(
string `$namespace`,
array|object `$filter`,
array|object `$update`,
?array `$options` = `null`
): void
public updateOne(
string `$namespace`,
array|object `$filter`,
array|object `$update`,
?array `$options` = `null`
): void
}

## Examples

Example #1 Mixed write operations

Mixed write operations (i.e. inserts, updates, and deletes) will be sent to the server using a single » bulkWrite command.

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
// Delete documents from both collections
$bulk->deleteMany('db.coll_one', []);
$bulk->deleteMany('db.coll_two', []);
// Insert documents into two collections
$bulk->insertOne('db.coll_one', ['_id' => 1]);
$bulk->insertOne('db.coll_two', ['_id' => 2]);
$bulk->insertOne('db.coll_two', ['_id' => 3]);
// Update a document in "coll_one"
$bulk->updateOne('db.coll_one', ['_id' => 1], ['$set' => ['x' => 1]]);
$result = $manager->executeBulkWriteCommand($bulk);
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
?>`

The above example will output:

    Inserted 3 document(s)
    Updated  1 document(s)

Example #2 Ordered write operations causing an error

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteMany('db.coll', []);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 2]);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 3]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
$result = $e->getPartialResult();
var_dump($e->getWriteErrors());
}
printf("Inserted %d document(s)\n", $result->getInsertedCount());
?>`

The above example will output something similar to:

    array(1) {
      [3]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(78) "E11000 duplicate key error collection: db.coll index: _id_ dup key: { _id: 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(3)
        ["info"]=>
        object(stdClass)#6 (0) {
        }
      }
    }
    Inserted 2 document(s)

## See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand()
- MongoDB\Driver\BulkWriteCommandResult
- MongoDB\Driver\Exception\BulkWriteCommandException
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\WriteConcernError
- MongoDB\Driver\WriteError

# MongoDB\Driver\BulkWriteCommand::__construct

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::__construct — Create a new BulkWriteCommand

### Description

public MongoDB\Driver\BulkWriteCommand::__construct(?array `$options` = `null`)

Constructs a new MongoDB\Driver\BulkWriteCommand, which may be used to perform many insert, update, and delete operations on multiple collections in a single request using the » bulkWrite command introduced in MongoDB 8.0. This differs from MongoDB\Driver\BulkWrite, which is supported by all server versions but limited to a single collection.

After all write operations have been added, this object may be executed with MongoDB\Driver\Manager::executeBulkWriteCommand().

### Parameters

`options` (array)

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  bypassDocumentValidation | bool | If `true`, allows insert and update operations to circumvent document level validation. | `false`
  comment | mixed | An arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.
  let | array|object | Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. `$$var`). This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.
  ordered | bool | Whether the operations in this bulk write should be executed in the order in which they were specified. If `false`, writes will continue to be executed if an individual write fails. If `true`, writes will stop executing if an individual write fails. | `true`
  verboseResults | bool | Whether detailed results for each successful operation should be included in the returned MongoDB\Driver\BulkWriteCommandResult. | `false`

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::__construct() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
// Delete documents from both collections
$bulk->deleteMany('db.coll_one', []);
$bulk->deleteMany('db.coll_two', []);
// Insert documents into two collections
$bulk->insertOne('db.coll_one', ['_id' => 1]);
$bulk->insertOne('db.coll_two', ['_id' => 2]);
$bulk->insertOne('db.coll_two', ['_id' => 3]);
// Update a document in "coll_one"
$bulk->updateOne('db.coll_one', ['_id' => 1], ['$set' => ['x' => 1]]);
$result = $manager->executeBulkWriteCommand($bulk);
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
?>`

The above example will output:

    Inserted 3 document(s)
    Updated  1 document(s)

### See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

# MongoDB\Driver\BulkWriteCommand::count

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::count — Count number of write operations in the BulkWriteCommand

### Description

public MongoDB\Driver\BulkWriteCommand::count(): int

Returns the number of write operations added to the MongoDB\Driver\BulkWriteCommand object.

### Parameters

This function has no parameters.

### Return Values

Returns number of write operations added to the MongoDB\Driver\BulkWriteCommand object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::count() example

`<?php
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['_id' => 1, 'x' => 1]);
$bulk->insertOne('db.coll', ['_id' => 2, 'x' => 2]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['x' => 1]]);
$bulk->deleteMany('db.coll', ['x' => 1]);
var_dump(count($bulk));
?>`

The above example will output:

    int(4)

# MongoDB\Driver\BulkWriteCommand::deleteMany

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::deleteMany — Add a deleteMany operation

### Description

public MongoDB\Driver\BulkWriteCommand::deleteMany(string `$namespace`, array|object `$filter`, ?array `$options` = `null`): void

Add a deleteMany operation to the MongoDB\Driver\BulkWriteCommand. All documents matching `filter` in the collection identified by `namespace` will be deleted.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::deleteMany() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteMany('db.coll', ['x' => ['$gt' => 1]]);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

### See Also

- MongoDB\Driver\BulkWriteCommand::deleteOne() - Add a deleteOne operation
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

# MongoDB\Driver\BulkWriteCommand::deleteOne

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::deleteOne — Add a deleteOne operation

### Description

public MongoDB\Driver\BulkWriteCommand::deleteOne(string `$namespace`, array|object `$filter`, ?array `$options` = `null`): void

Add a deleteOne operation to the MongoDB\Driver\BulkWriteCommand. The first document matching `filter` in the collection identified by `namespace` will be deleted.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::deleteOne() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteOne('db.coll', ['x' => 1]);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

### See Also

- MongoDB\Driver\BulkWriteCommand::deleteMany() - Add a deleteMany operation
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

# MongoDB\Driver\BulkWriteCommand::insertOne

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::insertOne — Add an insertOne operation

### Description

public MongoDB\Driver\BulkWriteCommand::insertOne(string `$namespace`, array|object `$document`): mixed

Add an insertOne operation to the MongoDB\Driver\BulkWriteCommand. The document will be inserted into the collection identified by `namespace`.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`document` (array|object)

  A document to insert.

### Return Values

Returns the `_id` of the inserted document. If the `document` did not have an `_id`, the MongoDB\BSON\ObjectId generated for the insert will be returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::insertOne() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$doc1 = ['x' => 1];
$doc2 = ['_id' => 'custom-id', 'x' => 2];
$doc3 = ['_id' => new MongoDB\BSON\ObjectId('0123456789abcdef01234567'), 'x' => 3];
$id1 = $bulk->insertOne('db.coll', $doc1);
$id2 = $bulk->insertOne('db.coll', $doc2);
$id3 = $bulk->insertOne('db.coll', $doc3);
var_dump($id1, $id2, $id3);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

The above example will output something similar to:

    object(MongoDB\BSON\ObjectId)#3 (1) {
      ["oid"]=>
      string(24) "67f58058d1a0aa2fd80d55d0"
    }
    string(9) "custom-id"
    object(MongoDB\BSON\ObjectId)#4 (1) {
      ["oid"]=>
      string(24) "0123456789abcdef01234567"
    }

### See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult
- MongoDB\BSON\ObjectId

# MongoDB\Driver\BulkWriteCommand::replaceOne

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::replaceOne — Add a replaceOne operation

### Description

public MongoDB\Driver\BulkWriteCommand::replaceOne(
string `$namespace`,
array|object `$filter`,
array|object `$replacement`,
?array `$options` = `null`
): void

Add a replaceOne operation to the MongoDB\Driver\BulkWriteCommand. The first document matching `filter` in the collection identified by `namespace` will be replaced.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`replacement` (array|object)

  A replacement document.

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.
  sort | array|object | Specify which document the operation replaces if the query matches multiple documents. The first document matched by the sort order will be replaced.
  upsert | bool | If `filter` does not match an existing document, insert a single document. The document will be created from `replacement`. | `false`

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::replaceOne() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->replaceOne('db.coll', ['x' => 1], ['x' => 1, 'y' = 2]);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

### See Also

- MongoDB\Driver\BulkWriteCommand::updateOne() - Add an updateOne operation
- MongoDB\Driver\BulkWriteCommand::updateMany() - Add an updateMany operation
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

# MongoDB\Driver\BulkWriteCommand::updateMany

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::updateMany — Add an updateMany operation

### Description

public MongoDB\Driver\BulkWriteCommand::updateMany(
string `$namespace`,
array|object `$filter`,
array|object `$update`,
?array `$options` = `null`
): void

Add an updateMany operation to the MongoDB\Driver\BulkWriteCommand. All documents matching `filter` in the collection identified by `namespace` will be updated.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`update` (array|object)

  A document containing either update operators (e.g. `$set`) or an » aggregation pipeline.

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  arrayFilters | array | An array of filter documents that determines which array elements to modify for an update operation on an array field. See » Specify arrayFilters for Array Update Operations in the MongoDB manual for more information.
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.
  upsert | bool | If `filter` does not match an existing document, insert a single document. The document will be created by applying operators in `update` to any field values in `filter`. | `false`

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::updateMany() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->updateMany('db.coll', ['x' => ['$gt' => 1]], ['$set' => ['y' => 2]]);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

### See Also

- MongoDB\Driver\BulkWriteCommand::replaceOne() - Add a replaceOne operation
- MongoDB\Driver\BulkWriteCommand::updateMany()
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

# MongoDB\Driver\BulkWriteCommand::updateOne

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommand::updateOne — Add an updateOne operation

### Description

public MongoDB\Driver\BulkWriteCommand::updateOne(
string `$namespace`,
array|object `$filter`,
array|object `$update`,
?array `$options` = `null`
): void

Add an updateOne operation to the MongoDB\Driver\BulkWriteCommand. The first document matching `filter` in the collection identified by `namespace` will be updated.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`update` (array|object)

  A document containing either update operators (e.g. `$set`) or an » aggregation pipeline.

`options`

  options
  Option | Type | Description | Default
  --- | --- | --- | ---
  arrayFilters | array | An array of filter documents that determines which array elements to modify for an update operation on an array field. See » Specify arrayFilters for Array Update Operations in the MongoDB manual for more information.
  collation | array|object | » Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `"locale"` field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document. If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons. This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
  hint | string|array|object | Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.
  sort | array|object | Specify which document the operation updates if the query matches multiple documents. The first document matched by the sort order will be updated.
  upsert | bool | If `filter` does not match an existing document, insert a single document. The document will be created by applying operators in `update` to any field values in `filter`. | `false`

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommand::updateOne() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 2]]);
$result = $manager->executeBulkWriteCommand($bulk);
?>`

### See Also

- MongoDB\Driver\BulkWriteCommand::replaceOne() - Add a replaceOne operation
- MongoDB\Driver\BulkWriteCommand::updateMany() - Add an updateMany operation
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\BulkWriteCommandResult

## Table of Contents

- MongoDB\Driver\BulkWriteCommand::__construct — Create a new BulkWriteCommand
- MongoDB\Driver\BulkWriteCommand::count — Count number of write operations in the BulkWriteCommand
- MongoDB\Driver\BulkWriteCommand::deleteMany — Add a deleteMany operation
- MongoDB\Driver\BulkWriteCommand::deleteOne — Add a deleteOne operation
- MongoDB\Driver\BulkWriteCommand::insertOne — Add an insertOne operation
- MongoDB\Driver\BulkWriteCommand::replaceOne — Add a replaceOne operation
- MongoDB\Driver\BulkWriteCommand::updateMany — Add an updateMany operation
- MongoDB\Driver\BulkWriteCommand::updateOne — Add an updateOne operation

# The MongoDB\Driver\Session class

(mongodb >=1.4.0)

## Introduction

The MongoDB\Driver\Session class represents a client session and is returned by MongoDB\Driver\Manager::startSession(). Commands, queries, and write operations may then be associated the session.

## Class synopsis

final class MongoDB\Driver\Session {
/* Constants */
const string TRANSACTION_NONE = none;
const string TRANSACTION_STARTING = starting;
const string TRANSACTION_IN_PROGRESS = in_progress;
const string TRANSACTION_COMMITTED = committed;
const string TRANSACTION_ABORTED = aborted;
/* Methods */
final public abortTransaction(): void
final public advanceClusterTime(array|object `$clusterTime`): void
final public advanceOperationTime(MongoDB\BSON\TimestampInterface `$operationTime`): void
final public commitTransaction(): void
final private __construct()
final public endSession(): void
final public getClusterTime(): ?object
final public getLogicalSessionId(): object
final public getOperationTime(): ?MongoDB\BSON\Timestamp
final public getServer(): ?MongoDB\Driver\Server
final public getTransactionOptions(): ?array
final public getTransactionState(): string
final public isDirty(): bool
final public isInTransaction(): bool
final public startTransaction(?array `$options` = `null`): void
}

## Predefined Constants

`MongoDB\Driver\Session::TRANSACTION_NONE`

  There is no transaction in progress.

`MongoDB\Driver\Session::TRANSACTION_STARTING`

  A transaction has been started, but no operation has been sent to the server.

`MongoDB\Driver\Session::TRANSACTION_IN_PROGRESS`

  A transaction is in progress.

`MongoDB\Driver\Session::TRANSACTION_COMMITTED`

  The transaction was committed.

`MongoDB\Driver\Session::TRANSACTION_ABORTED`

  The transaction was aborted.

# MongoDB\Driver\Session::abortTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::abortTransaction — Aborts a transaction

### Description

final public MongoDB\Driver\Session::abortTransaction(): void

Terminates the multi-document transaction and rolls back any data changes made by the operations within the transaction. That is, the transaction ends without saving any of the changes made by the operations in the transaction.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be aborted (e.g. a transaction was not started).

### See Also

- MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
- MongoDB\Driver\Session::commitTransaction() - Commits a transaction
- MongoDB\Driver\Session::startTransaction() - Starts a transaction

# MongoDB\Driver\Session::advanceClusterTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::advanceClusterTime — Advances the cluster time for this session

### Description

final public MongoDB\Driver\Session::advanceClusterTime(array|object `$clusterTime`): void

Advances the cluster time for this session. If the cluster time is less than or equal to the session's current cluster time, this function is a no-op.

By using this method in conjunction with MongoDB\Driver\Session::advanceOperationTime() to copy the cluster and operation times from another session, you can ensure that operations in this session are causally consistent with the last operation in the other session.

### Parameters

`clusterTime`

  The cluster time is a document containing a logical timestamp and server signature. Typically, this value will be obtained by calling MongoDB\Driver\Session::getClusterTime() on another session object.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::advanceOperationTime() - Advances the operation time for this session
- MongoDB\Driver\Session::getClusterTime() - Returns the cluster time for this session

# MongoDB\Driver\Session::advanceOperationTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::advanceOperationTime — Advances the operation time for this session

### Description

final public MongoDB\Driver\Session::advanceOperationTime(MongoDB\BSON\TimestampInterface `$operationTime`): void

Advances the operation time for this session. If the operation time is less than or equal to the session's current operation time, this function is a no-op.

By using this method in conjunction with MongoDB\Driver\Session::advanceClusterTime() to copy the operation and cluster times from another session, you can ensure that operations in this session are causally consistent with the last operation in the other session.

### Parameters

`operationTime`

  The operation time is a logical timestamp. Typically, this value will be obtained by calling MongoDB\Driver\Session::getOperationTime() on another session object.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::advanceClusterTime() - Advances the cluster time for this session
- MongoDB\Driver\Session::getClusterTime() - Returns the cluster time for this session

# MongoDB\Driver\Session::commitTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::commitTransaction — Commits a transaction

### Description

final public MongoDB\Driver\Session::commitTransaction(): void

Saves the changes made by the operations in the multi-document transaction and ends the transaction. Until the commit, none of the data changes made from within the transaction are visible outside the transaction.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\CommandException if the server could not commit the transaction (e.g. due to conflicts, network issues). In case the exception's MongoDB\Driver\Exception\CommandException::getResultDocument() has a `"errorLabels"` element, and this array contains a `"TransientTransactionError"` or `"UnknownTransactionCommitResult"` value, it is safe to re-try the whole transaction. In newer versions of the extension, MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() should be used to test for this situation instead.
- Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be commited (e.g. a transaction was not started).

### See Also

- MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
- MongoDB\Driver\Session::abortTransaction() - Aborts a transaction
- MongoDB\Driver\Session::startTransaction() - Starts a transaction
- MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() - Returns whether an error label is associated with an exception

# MongoDB\Driver\Session::__construct

(mongodb >=1.4.0)

MongoDB\Driver\Session::__construct — Create a new Session (not used)

### Description

final private MongoDB\Driver\Session::__construct()

MongoDB\Driver\Session objects are returned by MongoDB\Driver\Manager::startSession() and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client

# MongoDB\Driver\Session::endSession

(mongodb >=1.5.0)

MongoDB\Driver\Session::endSession — Terminates a session

### Description

final public MongoDB\Driver\Session::endSession(): void

This method closes an existing session. If a transaction was associated with this session, the transaction will be aborted. After calling this method, applications should not invoke other methods on the session.

> Note: Sessions are also closed during garbage collection. It should not be necessary to call this method under normal circumstances.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
- MongoDB\Driver\Session::abortTransaction() - Aborts a transaction
- MongoDB\Driver\Session::commitTransaction() - Commits a transaction
- MongoDB\Driver\Session::startTransaction() - Starts a transaction

# MongoDB\Driver\Session::getClusterTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::getClusterTime — Returns the cluster time for this session

### Description

final public MongoDB\Driver\Session::getClusterTime(): ?object

Returns the cluster time for this session. If the session has not been used for any operation and MongoDB\Driver\Session::advanceClusterTime() has not been called, the cluster time will be `null`.

### Parameters

This function has no parameters.

### Return Values

Returns the cluster time for this session, or `null` if the session has no cluster time.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::advanceClusterTime() - Advances the cluster time for this session

# MongoDB\Driver\Session::getLogicalSessionId

(mongodb >=1.4.0)

MongoDB\Driver\Session::getLogicalSessionId — Returns the logical session ID for this session

### Description

final public MongoDB\Driver\Session::getLogicalSessionId(): object

Returns the logical session ID for this session, which may be used to identify this session's operations on the server.

### Parameters

This function has no parameters.

### Return Values

Returns the logical session ID for this session.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Session::getOperationTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::getOperationTime — Returns the operation time for this session

### Description

final public MongoDB\Driver\Session::getOperationTime(): ?MongoDB\BSON\Timestamp

Returns the operation time for this session. If the session has not been used for any operation and MongoDB\Driver\Session::advanceOperationTime() has not been called, the operation time will be `null`

### Parameters

This function has no parameters.

### Return Values

Returns the operation time for this session, or `null` if the session has no operation time.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::advanceOperationTime() - Advances the operation time for this session

# MongoDB\Driver\Session::getServer

(mongodb >=1.6.0)

MongoDB\Driver\Session::getServer — Returns the server to which this session is pinned

### Description

final public MongoDB\Driver\Session::getServer(): ?MongoDB\Driver\Server

Returns the MongoDB\Driver\Server to which this session is pinned. If the session is not pinned to a server, `null` will be returned.

Session pinning is primarily used for sharded transactions, as all commands within a sharded transaction must be sent to the same mongos instance. This method is intended to be used by libraries built atop the extension to allow use of a pinned server instead of invoking server selection.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server to which this session is pinned, or `null` if the session is not pinned to any server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Session::getTransactionOptions

(mongodb >=1.7.0)

MongoDB\Driver\Session::getTransactionOptions — Returns options for the currently running transaction

### Description

final public MongoDB\Driver\Session::getTransactionOptions(): ?array

Returns options for the currently running transaction.

### Parameters

This function has no parameters.

### Return Values

Returns a array containing current transaction options, or `null` if no transaction is running.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::getTransactionState() - Returns the current transaction state for this session

# MongoDB\Driver\Session::getTransactionState

(mongodb >=1.7.0)

MongoDB\Driver\Session::getTransactionState — Returns the current transaction state for this session

### Description

final public MongoDB\Driver\Session::getTransactionState(): string

Returns the transaction state for this session.

### Parameters

This function has no parameters.

### Return Values

Returns the current transaction state for this session.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::isInTransaction() - Returns whether a multi-document transaction is in progress
- MongoDB\Driver\Session::getTransactionOptions() - Returns options for the currently running transaction

# MongoDB\Driver\Session::isDirty

(mongodb >=1.13.0)

MongoDB\Driver\Session::isDirty — Returns whether the session has been marked as dirty

### Description

final public MongoDB\Driver\Session::isDirty(): bool

Returns whether the session has been marked as dirty (i.e. it has been used with a command that encountered a network error).

### Parameters

This function has no parameters.

### Return Values

Returns whether the session has been marked as dirty.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Session::isInTransaction

(mongodb >=1.6.0)

MongoDB\Driver\Session::isInTransaction — Returns whether a multi-document transaction is in progress

### Description

final public MongoDB\Driver\Session::isInTransaction(): bool

Returns whether a multi-document transaction is currently in progress for this session. A transaction is considered "in progress" if it has been started but has not been committed or aborted.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if a transaction is currently in progress for this session, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Session::getTransactionState() - Returns the current transaction state for this session

# MongoDB\Driver\Session::startTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::startTransaction — Starts a transaction

### Description

final public MongoDB\Driver\Session::startTransaction(?array `$options` = `null`): void

Starts a multi-document transaction associated with the session. At any given time, you can have at most one open transaction for a session. After starting a transaction, the session object must be passed to each operation via the `"session"` option (e.g. MongoDB\Driver\Manager::executeBulkWrite()) in order to associate that operation with the transaction.

Transactions can be committed through MongoDB\Driver\Session::commitTransaction(), and aborted with MongoDB\Driver\Session::abortTransaction(). Transactions are also automatically aborted when the session is closed from garbage collection or by explicitly calling MongoDB\Driver\Session::endSession().

### Parameters

`options`

  Options can be passed as argument to this method. Each element in this options array overrides the corresponding option from the `"defaultTransactionOptions"` option, if set when starting the session with MongoDB\Driver\Manager::startSession().

  options
  Option | Type | Description
  --- | --- | ---
  maxCommitTimeMS | integer | The maximum amount of time in milliseconds to allow a single `commitTransaction` command to run. If specified, `maxCommitTimeMS` must be a signed 32-bit integer greater than or equal to zero.
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\CommandException if the transaction could not be started because of a server-side problem (e.g. a lock could not be obtained).
- Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be started (e.g. a transaction was already started).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.6.0 | The `"maxCommitTimeMS"` option was added.

### See Also

- MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
- MongoDB\Driver\Session::commitTransaction() - Commits a transaction
- MongoDB\Driver\Session::abortTransaction() - Aborts a transaction

## Table of Contents

- MongoDB\Driver\Session::abortTransaction — Aborts a transaction
- MongoDB\Driver\Session::advanceClusterTime — Advances the cluster time for this session
- MongoDB\Driver\Session::advanceOperationTime — Advances the operation time for this session
- MongoDB\Driver\Session::commitTransaction — Commits a transaction
- MongoDB\Driver\Session::__construct — Create a new Session (not used)
- MongoDB\Driver\Session::endSession — Terminates a session
- MongoDB\Driver\Session::getClusterTime — Returns the cluster time for this session
- MongoDB\Driver\Session::getLogicalSessionId — Returns the logical session ID for this session
- MongoDB\Driver\Session::getOperationTime — Returns the operation time for this session
- MongoDB\Driver\Session::getServer — Returns the server to which this session is pinned
- MongoDB\Driver\Session::getTransactionOptions — Returns options for the currently running transaction
- MongoDB\Driver\Session::getTransactionState — Returns the current transaction state for this session
- MongoDB\Driver\Session::isDirty — Returns whether the session has been marked as dirty
- MongoDB\Driver\Session::isInTransaction — Returns whether a multi-document transaction is in progress
- MongoDB\Driver\Session::startTransaction — Starts a transaction

# The MongoDB\Driver\ClientEncryption class

(mongodb >=1.7.0)

## Introduction

The MongoDB\Driver\ClientEncryption class handles creation of data keys for client-side encryption, as well as manually encrypting and decrypting values.

## Class synopsis

final class MongoDB\Driver\ClientEncryption {
/* Constants */
const string AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC = AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic;
const string AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM = AEAD_AES_256_CBC_HMAC_SHA_512-Random;
const string ALGORITHM_INDEXED = Indexed;
const string ALGORITHM_UNINDEXED = Unindexed;
const string ALGORITHM_RANGE = Range;
const string QUERY_TYPE_EQUALITY = equality;
const string QUERY_TYPE_RANGE = range;
/* Methods */
final public addKeyAltName(MongoDB\BSON\Binary `$keyId`, string `$keyAltName`): ?object
final public __construct(array `$options`)
final public createDataKey(string `$kmsProvider`, ?array `$options` = `null`): MongoDB\BSON\Binary
final public decrypt(MongoDB\BSON\Binary `$value`): mixed
final public deleteKey(MongoDB\BSON\Binary `$keyId`): object
final public encrypt(mixed `$value`, ?array `$options` = `null`): MongoDB\BSON\Binary
final public encryptExpression(array|object `$expr`, ?array `$options` = `null`): object
final public getKey(MongoDB\BSON\Binary `$keyId`): ?object
final public getKeyByAltName(string `$keyAltName`): ?object
final public getKeys(): MongoDB\Driver\Cursor
final public removeKeyAltName(MongoDB\BSON\Binary `$keyId`, string `$keyAltName`): ?object
final public rewrapManyDataKey(array|object `$filter`, ?array `$options` = `null`): object
}

## Predefined Constants

`MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC`

  Specifies an algorithm for » deterministic encryption, which is suitable for querying.

`MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM`

  Specifies an algorithm for » randomized encryption

`MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED`

  Specifies an algorithm for an indexed, encrypted payload, which can be used with queryable encryption.

  To insert or query with an indexed, encrypted payload, the MongoDB\Driver\Manager must be configured with the `"autoEncryption"` driver option. The `"bypassQueryAnalysis"` auto encryption option may be `true`. The `"bypassAutoEncryption"` auto encryption option must be `false`.

`MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED`

  Specifies an algorithm for an unindexed, encrypted payload.

`MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`

  Specifies an algorithm for a range encrypted payload, which can be used with queryable encryption.

  To query with a range encrypted payload, the MongoDB\Driver\Manager must be configured with the `"autoEncryption"` driver option. The `"bypassQueryAnalysis"` auto encryption option may be `true`. The `"bypassAutoEncryption"` auto encryption option must be `false`.

  > Note:

  > The extension does not yet support range queries for Decimal128 BSON field types.

`MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY`

  Specifies an equality query type, which is used in conjunction with `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED`.

`MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE`

  Specifies a range query type, which is used in conjunction with `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`.

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Removed `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW` and `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW`.
PECL mongodb 1.20.0 | Added `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE` and `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE`. Deprecated `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW` and `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW`.
PECL mongodb 1.16.0 | Added `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW` and `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW`.
PECL mongodb 1.14.0 | Added `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED`, `MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED`, and `MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY`.

## See Also

- MongoDB\Driver\Manager::createClientEncryption()

# MongoDB\Driver\ClientEncryption::addKeyAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::addKeyAltName — Adds an alternate name to a key document

### Description

final public MongoDB\Driver\ClientEncryption::addKeyAltName(MongoDB\BSON\Binary `$keyId`, string `$keyAltName`): ?object

Adds `keyAltName` to the set of alternate names for the key document with the given UUID `keyId`.

### Parameters

`keyId`

  A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

`keyAltName`

  Alternate name to add to the key document.

### Return Values

Returns the previous version of the key document, or `null` if no document matched.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### See Also

- MongoDB\Driver\ClientEncryption::getKeyByAltName() - Gets a key document by an alternate name
- MongoDB\Driver\ClientEncryption::removeKeyAltName() - Removes an alternate name from a key document

# MongoDB\Driver\ClientEncryption::__construct

(mongodb >=1.14.0)

MongoDB\Driver\ClientEncryption::__construct — Create a new ClientEncryption object

### Description

final public MongoDB\Driver\ClientEncryption::__construct(array `$options`)

Constructs a new MongoDB\Driver\ClientEncryption object with the specified options.

### Parameters

`options`

  options
  Option | Type | Description
  --- | --- | ---
  keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries. This option is required (unlike with MongoDB\Driver\Manager::createClientEncryption()).
  keyVaultNamespace | string | A fully qualified namespace (e.g. `"databaseName.collectionName"`) denoting the collection that contains all data keys used for encryption and decryption. This option is required.
  kmsProviders | array | A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include `"aws"`, `"azure"`, `"gcp"`, `"kmip"`, and `"local"` and at least one must be specified. If an empty document is specified for `"aws"`, `"azure"`, or `"gcp"`, the driver will attempt to configure the provider using » Automatic Credentials. The format for `"aws"` is as follows:
      aws: {
          accessKeyId: <string>,
          secretAccessKey: <string>,
          sessionToken: <optional string>
      }
  The format for `"azure"` is as follows:
      azure: {
          tenantId: <string>,
          clientId: <string>,
          clientSecret: <string>,
          identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
      }
  The format for `"gcp"` is as follows:
      gcp: {
          email: <string>,
          privateKey: <base64 string>|<MongoDB\BSON\Binary>,
          endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
      }
  The format for `"kmip"` is as follows:
      kmip: {
          endpoint: <string>
      }
  The format for `"local"` is as follows:
      local: {
          // 96-byte master key used to encrypt/decrypt data keys
          key: <base64 string>|<MongoDB\BSON\Binary>
      }
  tlsOptions | array | A document containing the TLS configuration for one or more KMS providers. Supported providers include `"aws"`, `"azure"`, `"gcp"`, and `"kmip"`. All providers support the following options:
      <provider>: {
          tlsCaFile: <optional string>,
          tlsCertificateKeyFile: <optional string>,
          tlsCertificateKeyFilePassword: <optional string>,
          tlsDisableOCSPEndpointCheck: <optional bool>
      }

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support

### Changelog

Version | Description
--- | ---
PECL mongodb 1.16.0 | The AWS KMS provider for client-side encryption now accepts a `"sessionToken"` option, which can be used to authenticate with temporary AWS credentials. Added `"tlsDisableOCSPEndpointCheck"` to the `"tlsOptions"` option. If an empty document is specified for the `"azure"` or `"gcp"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.
PECL mongodb 1.15.0 | If an empty document is specified for the `"aws"` KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

### See Also

- MongoDB\Driver\Manager::createClientEncryption() - Create a new ClientEncryption object
- » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual

# MongoDB\Driver\ClientEncryption::createDataKey

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::createDataKey — Creates a key document

### Description

final public MongoDB\Driver\ClientEncryption::createDataKey(string `$kmsProvider`, ?array `$options` = `null`): MongoDB\BSON\Binary

Creates a new key document and inserts it into the key vault collection.

### Parameters

`kmsProvider`

  The KMS provider (e.g. `"local"`, `"aws"`) that will be used to encrypt the new data key.

`options`

  Data key options
  Option | Type | Description
  --- | --- | ---
  masterKey | array | The masterKey document identifies a KMS-specific key used to encrypt the new data key. This option is required unless `kmsProvider` is `"local"`.
  `"aws"` provider options
  Option | Type | Description
  --- | --- | ---
  region | string | Required.
  key | string | Required. The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
  endpoint | string | Optional. An alternate host identifier to send KMS requests to. May include port number.
  `"azure"` provider options
  Option | Type | Description
  --- | --- | ---
  keyVaultEndpoint | string | Required. Host with optional port (e.g. "example.vault.azure.net").
  keyName | string | Required.
  keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
  `"gcp"` provider options
  Option | Type | Description
  --- | --- | ---
  projectId | string | Required.
  location | string | Required.
  keyRing | string | Required.
  keyName | string | Required.
  keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
  endpoint | string | Optional. Host with optional port. Defaults to "cloudkms.googleapis.com".
  `"kmip"` provider options
  Option | Type | Description
  --- | --- | ---
  keyId | string | Optional. Unique identifier to a 96-byte KMIP secret data managed object. If unspecified, the driver creates a random 96-byte KMIP secret data managed object.
  endpoint | string | Optional. Host with optional port.
  delegated | bool | Optional. If true, this key should be decrypted by the KMIP server.
  keyAltNames | array | An optional list of string alternate names used to reference a key. If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by `_id`.
  keyMaterial | MongoDB\BSON\Binary | An optional 96-byte value to use as custom key material for the data key being created. If keyMaterial is given, the custom key material is used for encrypting and decrypting data. Otherwise, the key material for the new data key is generated from a cryptographically secure random device.

### Return Values

Returns the identifier of the new key as a MongoDB\BSON\Binary object with subtype 4 (UUID).

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.20.0 | Added `"delegated"` to the KMIP provider masterKey options.
PECL mongodb 1.15.0 | Added the `"keyMaterial"` option.
PECL mongodb 1.10.0 | Azure and GCP are now supported as KMS providers for client-side encryption.

# MongoDB\Driver\ClientEncryption::decrypt

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value

### Description

final public MongoDB\Driver\ClientEncryption::decrypt(MongoDB\BSON\Binary `$value`): mixed

Decrypts the value.

### Parameters

`value`

  A MongoDB\BSON\Binary instance with subtype 6 containing the encrypted value.

### Return Values

Returns the decrypted value as it was passed to MongoDB\Driver\ClientEncryption::encrypt().

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while decrypting the value

### See Also

- MongoDB\Driver\ClientEncryption::encrypt() - Encrypt a value

# MongoDB\Driver\ClientEncryption::deleteKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::deleteKey — Deletes a key document

### Description

final public MongoDB\Driver\ClientEncryption::deleteKey(MongoDB\BSON\Binary `$keyId`): object

Removes the key document with the given UUID `keyId` from the key vault collection.

### Parameters

`keyId`

  A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

### Return Values

Returns the result of the internal `deleteOne` operation on the key vault collection.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

# MongoDB\Driver\ClientEncryption::encrypt

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value

### Description

final public MongoDB\Driver\ClientEncryption::encrypt(mixed `$value`, ?array `$options` = `null`): MongoDB\BSON\Binary

Encrypts the value.

### Parameters

`value`

  The value to be encrypted. Any value that can be inserted into MongoDB can be encrypted using this method.

`options`

  Encryption options
  Option | Type | Description
  --- | --- | ---
  algorithm | string | The encryption algorithm to be used. This option is required. Specify one of the following ClientEncryption constants: `MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC` `MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM` `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` `MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED` `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`
  contentionFactor | int | The contention factor for evaluating queries with indexed, encrypted payloads. This option only applies and may only be specified when `algorithm` is `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` or `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`.
  keyAltName | string | Identifies a key vault collection document by `keyAltName`. This option is mutually exclusive with `keyId` and exactly one is required.
  keyId | MongoDB\BSON\Binary | Identifies a data key by `_id`. The value is a UUID (binary subtype 4). This option is mutually exclusive with `keyAltName` and exactly one is required.
  queryType | string | The query type for evaluating queries with indexed, encrypted payloads. Specify one of the following ClientEncryption constants: `MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY` `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE` This option only applies and may only be specified when `algorithm` is `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` or `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`.
  rangeOpts | array | Index options for a queryable encryption field supporting "range" queries. The options below must match the values set in the `encryptedFields` of the target collection. For double and decimal128 BSON field types, `min`, `max`, and `precision` must all be set, or all be unset.
  Range index options
  Option | Type | Description
  --- | --- | ---
  min | mixed | Required if `precision` is set. The minimum BSON value of the range.
  max | mixed | Required if `precision` is set. The maximum BSON value of the range.
  sparsity | int | Optional. Positive 64-bit integer.
  precision | int | Optional. Positive 32-bit integer specifying precision to use for explicit encryption. May only be set for double or decimal128 BSON field types.
  trimFactor | int | Optional. Positive 32-bit integer.

### Return Values

Returns the encrypted value as MongoDB\BSON\Binary object with subtype 6.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while encrypting the value

### Changelog

Version | Description
--- | ---
PECL mongodb 1.20.0 | Added the `"trimFactor"` range option. The `"sparsity"` range option is now optional.
PECL mongodb 1.16.0 | Added the `"rangeOpts"` option.
PECL mongodb 1.14.0 | Added the `"contentionFactor"` and `"queryType"` options.

### See Also

- MongoDB\Driver\ClientEncryption::decrypt() - Decrypt a value
- MongoDB\Driver\ClientEncryption::encryptExpression() - Encrypts a match or aggregate expression

# MongoDB\Driver\ClientEncryption::encryptExpression

(mongodb >=1.16.0)

MongoDB\Driver\ClientEncryption::encryptExpression — Encrypts a match or aggregate expression

### Description

final public MongoDB\Driver\ClientEncryption::encryptExpression(array|object `$expr`, ?array `$options` = `null`): object

Encrypts a match or aggregate expression to query a range index.

To query with a range encrypted payload, the MongoDB\Driver\Manager must be configured with the `"autoEncryption"` driver option. The `"bypassQueryAnalysis"` auto encryption option may be `true`. The `"bypassAutoEncryption"` auto encryption option must be `false`.

> Note:

> The extension does not yet support range queries for Decimal128 BSON field types.

### Parameters

`expr`

  The match or aggregate expression to be encrypted. Expressions must use at least one of the `$gt`, `$gte`, `$lt`, or `$lte` operators. A top-level `$and` operator is required, even if only a single comparison operator is used.

  An example of a supported match expression (applies to queries and the `$match` aggregation stage) is as follows:

      [
          '$and' => [
              [ '<field>' => [ '$gt'  => '<value1>' ] ],
              [ '<field>' => [ '$lte' => '<value2>' ] ],
          ],
      ]

  An example of a supported aggregate expression is as follows:

      [
          '$and' => [
              [ '$gte' => [ '<fieldPath>', '<value1>' ] ],
              [ '$lt'  => [ '<fieldPath>', '<value2>' ] ],
          ],
      ]

`options`

  Encryption options
  Option | Type | Description
  --- | --- | ---
  algorithm | string | The encryption algorithm to be used. This option is required. Specify one of the following ClientEncryption constants: `MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC` `MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM` `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` `MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED` `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`
  contentionFactor | int | The contention factor for evaluating queries with indexed, encrypted payloads. This option only applies and may only be specified when `algorithm` is `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` or `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`.
  keyAltName | string | Identifies a key vault collection document by `keyAltName`. This option is mutually exclusive with `keyId` and exactly one is required.
  keyId | MongoDB\BSON\Binary | Identifies a data key by `_id`. The value is a UUID (binary subtype 4). This option is mutually exclusive with `keyAltName` and exactly one is required.
  queryType | string | The query type for evaluating queries with indexed, encrypted payloads. Specify one of the following ClientEncryption constants: `MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY` `MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE` This option only applies and may only be specified when `algorithm` is `MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED` or `MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE`.
  rangeOpts | array | Index options for a queryable encryption field supporting "range" queries. The options below must match the values set in the `encryptedFields` of the target collection. For double and decimal128 BSON field types, `min`, `max`, and `precision` must all be set, or all be unset.
  Range index options
  Option | Type | Description
  --- | --- | ---
  min | mixed | Required if `precision` is set. The minimum BSON value of the range.
  max | mixed | Required if `precision` is set. The maximum BSON value of the range.
  sparsity | int | Optional. Positive 64-bit integer.
  precision | int | Optional. Positive 32-bit integer specifying precision to use for explicit encryption. May only be set for double or decimal128 BSON field types.
  trimFactor | int | Optional. Positive 32-bit integer.

### Return Values

Returns the encrypted expression as an object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while encrypting the expression

### Changelog

Version | Description
--- | ---
PECL mongodb 1.20.0 | Added the `"trimFactor"` range option. The `"sparsity"` range option is now optional.

### See Also

- MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager
- MongoDB\Driver\ClientEncryption::encrypt() - Encrypt a value

# MongoDB\Driver\ClientEncryption::getKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKey — Gets a key document

### Description

final public MongoDB\Driver\ClientEncryption::getKey(MongoDB\BSON\Binary `$keyId`): ?object

Finds a single key document in the key vault collection with the given UUID `keyId`.

### Parameters

`keyId`

  A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

### Return Values

Returns the key document, or `null` if no document matched.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

# MongoDB\Driver\ClientEncryption::getKeyByAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKeyByAltName — Gets a key document by an alternate name

### Description

final public MongoDB\Driver\ClientEncryption::getKeyByAltName(string `$keyAltName`): ?object

Finds a single key document in the key vault collection with the given alternate name `keyAltName`.

### Parameters

`keyAltName`

  Alternate name for the key document.

### Return Values

Returns the key document, or `null` if no document matched.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### See Also

- MongoDB\Driver\ClientEncryption::addKeyAltName() - Adds an alternate name to a key document
- MongoDB\Driver\ClientEncryption::removeKeyAltName() - Removes an alternate name from a key document

# MongoDB\Driver\ClientEncryption::getKeys

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKeys — Gets all key documents

### Description

final public MongoDB\Driver\ClientEncryption::getKeys(): MongoDB\Driver\Cursor

Finds all key documents in the key vault collection.

### Parameters

This function has no parameters.

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

# MongoDB\Driver\ClientEncryption::removeKeyAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::removeKeyAltName — Removes an alternate name from a key document

### Description

final public MongoDB\Driver\ClientEncryption::removeKeyAltName(MongoDB\BSON\Binary `$keyId`, string `$keyAltName`): ?object

Removes `keyAltName` from the set of alternate names for the key document with the given UUID `keyId`.

### Parameters

`keyId`

  A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

`keyAltName`

  Alternate name to remove from the key document.

### Return Values

Returns the previous version of the key document, or `null` if no document matched.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### See Also

- MongoDB\Driver\ClientEncryption::addKeyAltName() - Adds an alternate name to a key document
- MongoDB\Driver\ClientEncryption::getKeyByAltName() - Gets a key document by an alternate name

# MongoDB\Driver\ClientEncryption::rewrapManyDataKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::rewrapManyDataKey — Rewraps data keys

### Description

final public MongoDB\Driver\ClientEncryption::rewrapManyDataKey(array|object `$filter`, ?array `$options` = `null`): object

Rewraps (i.e. decrypts and re-encrypts) zero or more data keys in the key vault collection that match the given `filter`.

If the `"provider"` option is not specified, matching data keys will be rewrapped with their current KMS provider. Otherwise, matching data keys will be re-encrypted according to the specified `"provider"` and `"masterKey"` options.

### Parameters

`filter` (array|object)

  The » query predicate. An empty predicate will match all documents in the collection.

  > Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

`options`

  RewrapManyDataKey options
  Option | Type | Description
  --- | --- | ---
  provider | string | The KMS provider (e.g. `"local"`, `"aws"`) that will be used to re-encrypt the matched data keys. If a KMS provider is not specified, matched data keys will be re-encrypted with their current KMS provider.
  masterKey | array | The masterKey identifies a KMS-specific key used to encrypt the new data key. This option should not be specified without the `"provider"` option. This option is required if `"provider"` is specified and not `"local"`.
  `"aws"` provider options
  Option | Type | Description
  --- | --- | ---
  region | string | Required.
  key | string | Required. The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
  endpoint | string | Optional. An alternate host identifier to send KMS requests to. May include port number.
  `"azure"` provider options
  Option | Type | Description
  --- | --- | ---
  keyVaultEndpoint | string | Required. Host with optional port (e.g. "example.vault.azure.net").
  keyName | string | Required.
  keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
  `"gcp"` provider options
  Option | Type | Description
  --- | --- | ---
  projectId | string | Required.
  location | string | Required.
  keyRing | string | Required.
  keyName | string | Required.
  keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
  endpoint | string | Optional. Host with optional port. Defaults to "cloudkms.googleapis.com".
  `"kmip"` provider options
  Option | Type | Description
  --- | --- | ---
  keyId | string | Optional. Unique identifier to a 96-byte KMIP secret data managed object. If unspecified, the driver creates a random 96-byte KMIP secret data managed object.
  endpoint | string | Optional. Host with optional port.
  delegated | bool | Optional. If true, this key should be decrypted by the KMIP server.

### Return Values

Returns an object, which will have an optional `bulkWriteResult` property containing the result of the internal `bulkWrite` operation as an object. If no data keys matched the filter or the write was unacknowledged, the `bulkWriteResult` property will be `null`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while decrypting or re-encrypting a data key.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.20.0 | Added `"delegated"` to the KMIP provider masterKey options.

## Table of Contents

- MongoDB\Driver\ClientEncryption::addKeyAltName — Adds an alternate name to a key document
- MongoDB\Driver\ClientEncryption::__construct — Create a new ClientEncryption object
- MongoDB\Driver\ClientEncryption::createDataKey — Creates a key document
- MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value
- MongoDB\Driver\ClientEncryption::deleteKey — Deletes a key document
- MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value
- MongoDB\Driver\ClientEncryption::encryptExpression — Encrypts a match or aggregate expression
- MongoDB\Driver\ClientEncryption::getKey — Gets a key document
- MongoDB\Driver\ClientEncryption::getKeyByAltName — Gets a key document by an alternate name
- MongoDB\Driver\ClientEncryption::getKeys — Gets all key documents
- MongoDB\Driver\ClientEncryption::removeKeyAltName — Removes an alternate name from a key document
- MongoDB\Driver\ClientEncryption::rewrapManyDataKey — Rewraps data keys

# The MongoDB\Driver\ServerApi class

(mongodb >=1.10.0)

## Introduction

## Class synopsis

final class MongoDB\Driver\ServerApi implements MongoDB\BSON\Serializable, Serializable {
/* Constants */
const string MongoDB\Driver\ServerAPI::V1 = "1";
/* Methods */
final public bsonSerialize(): stdClass
final public __construct(string `$version`, ?bool `$strict` = `null`, ?bool `$deprecationErrors` = `null`)
}

## Predefined Constants

`MongoDB\Driver\ServerApi::V1`

  Server API version 1.

## Examples

Example #1 Declare an API version on a manager

`<?php
use MongoDB\Driver\Manager;
use MongoDB\Driver\ServerApi;
$v1 = new ServerApi(ServerApi::v1);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);
$command = new MongoDB\Driver\Command(['buildInfo' => 1]);
try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
/* The buildInfo command returns a single result document, so we need to access
* the first result in the cursor. */
$buildInfo = $cursor->toArray()[0];
echo $buildInfo->version, "\n";
?>`

The above example will output:

    4.9.0-alpha7-49-gb968ca0

Example #2 Declare a strict API version on a manager

The following example sets the `strict` flag, which tells the server to reject any command that is not part of the declared API version. This results in an error when running the buildInfo command.

`<?php
use MongoDB\Driver\Manager;
use MongoDB\Driver\ServerApi;
$v1 = new ServerApi(ServerApi::v1, true);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);
$command = new MongoDB\Driver\Command(['buildInfo' => 1]);
try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
/* The buildInfo command returns a single result document, so we need to access
* the first result in the cursor. */
$buildInfo = $cursor->toArray()[0];
echo $buildInfo->version, "\n";
?>`

The above example will output:

    Provided apiStrict:true, but the command buildInfo is not in API Version 1

# MongoDB\Driver\ServerApi::bsonSerialize

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::bsonSerialize — Returns an object for BSON serialization

### Description

final public MongoDB\Driver\ServerApi::bsonSerialize(): stdClass

### Parameters

This function has no parameters.

### Return Values

Returns an object for serializing the ServerApi as BSON.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON

# MongoDB\Driver\ServerApi::__construct

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::__construct — Create a new ServerApi instance

### Description

final public MongoDB\Driver\ServerApi::__construct(string `$version`, ?bool `$strict` = `null`, ?bool `$deprecationErrors` = `null`)

Creates a new MongoDB\Driver\ServerApi instance used to declare an API version when creating a MongoDB\Driver\Manager.

### Parameters

`version`

  A server API version.

  Supported API versions are provided as constants in MongoDB\Driver\ServerApi. The only supported API version is `MongoDB\Driver\ServerApi::V1`.

`strict`

  If the `strict` parameter is set to `true`, the server will yield an error for any command that is not part of the specified API version. If no value is provided, the server default value (`false`) is used.

`deprecationErrors`

  If the `deprecationErrors` parameter is set to `true`, the server will yield an error when using a command that is deprecated in the specified API version. If no value is provided, the server default value (`false`) is used.

## Table of Contents

- MongoDB\Driver\ServerApi::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\ServerApi::__construct — Create a new ServerApi instance

# The MongoDB\Driver\WriteConcern class

(mongodb >=1.0.0)

## Introduction

MongoDB\Driver\WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone `mongod` or to replica sets or to sharded clusters. In sharded clusters, `mongos` instances will pass the write concern on to the shards.

## Class synopsis

final class MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable, Serializable {
/* Constants */
const string MAJORITY = "majority";
/* Methods */
final public bsonSerialize(): stdClass
final public __construct(string|int `$w`, ?int `$wtimeout` = `null`, ?bool `$journal` = `null`)
final public getJournal(): ?bool
final public getW(): string|int|null
final public getWtimeout(): int
final public isDefault(): bool
}

## Predefined Constants

`MongoDB\Driver\WriteConcern::MAJORITY`

  Majority of all the members in the set; arbiters, non-voting members, passive members, hidden members and delayed members are all included in the definition of majority write concern.

## Changelog

Version | Description
--- | ---
PECL mongodb 1.7.0 | Implements Serializable.
PECL mongodb 1.2.0 | Implements MongoDB\BSON\Serializable.

# MongoDB\Driver\WriteConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization

### Description

final public MongoDB\Driver\WriteConcern::bsonSerialize(): stdClass

### Parameters

This function has no parameters.

### Return Values

Returns an object for serializing the WriteConcern as BSON.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcern::bsonSerialize() with majority write concern

`<?php
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($wc)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (1) {
      ["w"]=>
      string(8) "majority"
    }

    { "w" : "majority" }

Example #2 MongoDB\Driver\WriteConcern::bsonSerialize() with wtimeout and journal

`<?php
$wc = new MongoDB\Driver\WriteConcern(2, 1000, true);
var_dump($wc->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($wc)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (3) {
      ["w"]=>
      int(2)
      ["j"]=>
      bool(true)
      ["wtimeout"]=>
      int(1000)
    }

    { "w" : 2, "j" : true, "wtimeout" : 1000 }

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
- » Write Concern reference

# MongoDB\Driver\WriteConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern

### Description

final public MongoDB\Driver\WriteConcern::__construct(string|int `$w`, ?int `$wtimeout` = `null`, ?bool `$journal` = `null`)

Constructs a new MongoDB\Driver\WriteConcern, which is an immutable value object.

### Parameters

`w`

  Write concern
  Value | Description
  --- | ---
  1 | Requests acknowledgement that the write operation has propagated to the standalone `mongod` or the primary in a replica set. This is the default write concern for MongoDB.
  0 | Requests no acknowledgment of the write operation. However, this may return information about socket exceptions and networking errors to the application.
  <integer greater than 1> | Numbers greater than 1 are valid only for replica sets to request acknowledgement from specified number of members, including the primary.
  `MongoDB\Driver\WriteConcern::MAJORITY` | Requests acknowledgment that write operations have propagated to the majority of voting nodes, including the primary, and have been written to the on-disk journal for these nodes. Prior to MongoDB 3.0, this refers to the majority of replica set members (not just voting nodes).
  string | A string value is interpereted as a tag set. Requests acknowledgement that the write operations have propagated to a replica set member with the specified tag.

`wtimeout`

  How long to wait (in milliseconds) for secondaries before failing.

  `wtimeout` causes write operations to return with an error (WriteConcernError) after the specified limit, even if the required write concern will eventually succeed. When these write operations return, MongoDB does not undo successful data modifications performed before the write concern exceeded the `wtimeout` time limit.

  If specified, `wtimeout` must be a signed 64-bit integer greater than or equal to zero.

  Write concern timeout
  Value | Description
  --- | ---
  0 | Block indefinitely. This is the default.
  <integer greater than 0> | Milliseconds to wait until returning.

`journal`

  Wait until mongod has applied the write to the journal.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `w` is invalid or `wtimeout` is either negative or greater than the bounds of a signed 32-bit integer.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.7.0 | The `wTimeout` parameter now accepts 64-bit values.

### Examples

Example #1 MongoDB\Driver\WriteConcern::__construct() example

`<?php
/* Request write acknowledgement from the majority of the replica set nodes */
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 500);
/* Request write acknowledgement from a node configured with the "MultipleDC" tag */
$wc = new MongoDB\Driver\WriteConcern("MultipleDC", 500);
?>`

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcern::getJournal

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option

### Description

final public MongoDB\Driver\WriteConcern::getJournal(): ?bool

### Parameters

This function has no parameters.

### Return Values

Returns the WriteConcern's "journal" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcern::getJournal() example

`<?php
$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getJournal());
$wc = new MongoDB\Driver\WriteConcern(1, 0, true);
var_dump($wc->getJournal());
$wc = new MongoDB\Driver\WriteConcern(1, 0, false);
var_dump($wc->getJournal());
?>`

The above example will output:

    NULL
    bool(true)
    bool(false)

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcern::getW

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option

### Description

final public MongoDB\Driver\WriteConcern::getW(): string|int|null

### Parameters

This function has no parameters.

### Return Values

Returns the WriteConcern's "w" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcern::getW() example

`<?php
$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getW());
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->getW());
?>`

The above example will output:

    int(1)
    string(8) "majority"

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcern::getWtimeout

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option

### Description

final public MongoDB\Driver\WriteConcern::getWtimeout(): int

### Parameters

This function has no parameters.

### Return Values

Returns the WriteConcern's "wtimeout" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.7.0 | On 32-bit systems, this method will always truncate the `wTimeout` value if it exceeds the 32-bit range. In that case, a warning will be emitted.

### Examples

Example #1 MongoDB\Driver\WriteConcern::getWtimeout() example

`<?php
$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getWtimeout());
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 3000);
var_dump($wc->getWtimeout());
?>`

The above example will output:

    int(0)
    int(3000)

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcern::isDefault

(mongodb >=1.3.0)

MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern

### Description

final public MongoDB\Driver\WriteConcern::isDefault(): bool

Returns whether this is the default write concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getWriteConcern() to determine whether the Manager has been constructed without any write concern options.

The driver will not include a default write concern in its write operations (e.g. MongoDB\Driver\Manager::executeBulkWrite()) in order to allow the server to apply its own default, which may have been » modified. Libraries that access the Manager's write concern to include it in their own write commands should use this method to ensure that default write concerns are left unset.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this is the default write concern and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcern::isDefault() example

`<?php
$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->isDefault());
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?w=majority');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());
?>`

The above example will output:

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

### See Also

- MongoDB\Driver\Manager::getWriteConcern() - Return the WriteConcern for the Manager
- » Modify Default Write Concern in the MongoDB manual
- » Write Concern reference

## Table of Contents

- MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern
- MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
- MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
- MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
- MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern

# The MongoDB\Driver\ReadPreference class

(mongodb >=1.0.0)

## Introduction

## Class synopsis

final class MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable, Serializable {
/* Constants */
const string PRIMARY = primary;
const string PRIMARY_PREFERRED = primaryPreferred;
const string SECONDARY = secondary;
const string SECONDARY_PREFERRED = secondaryPreferred;
const string NEAREST = nearest;
const int NO_MAX_STALENESS = -1;
const int SMALLEST_MAX_STALENESS_SECONDS = 90;
/* Methods */
final public bsonSerialize(): stdClass
final public __construct(string `$mode`, ?array `$tagSets` = `null`, ?array `$options` = `null`)
final public getHedge(): ?object
final public getMaxStalenessSeconds(): int
final public getMode(): int
final public getModeString(): string
final public getTagSets(): array
}

## Predefined Constants

`MongoDB\Driver\ReadPreference::PRIMARY`

  All operations read from the current replica set primary. This is the default read preference for MongoDB.

`MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED`

  In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

`MongoDB\Driver\ReadPreference::SECONDARY`

  All operations read from the secondary members of the replica set.

`MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED`

  In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

`MongoDB\Driver\ReadPreference::NEAREST`

  Operations read from member of the replica set with the least network latency, irrespective of the member's type.

`MongoDB\Driver\ReadPreference::NO_MAX_STALENESS`

  The default value for the `"maxStalenessSeconds"` option is to specify no limit on maximum staleness, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

`MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS`

  The minimum value for the `"maxStalenessSeconds"` option is 90 seconds. The driver estimates secondaries' staleness by periodically checking the latest write date of each replica set member. Since these checks are infrequent, the staleness estimate is coarse. Thus, the driver cannot enforce a max staleness value of less than 90 seconds.

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Removed the `MongoDB\Driver\ReadPreference::RP_PRIMARY`, `MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED`, `MongoDB\Driver\ReadPreference::RP_SECONDARY`, `MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED`, and `MongoDB\Driver\ReadPreference::RP_NEAREST` constants. The getMode() method was also removed.
PECL mongodb 1.20.0 | Deprecated the `MongoDB\Driver\ReadPreference::RP_PRIMARY`, `MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED`, `MongoDB\Driver\ReadPreference::RP_SECONDARY`, `MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED`, and `MongoDB\Driver\ReadPreference::RP_NEAREST` constants.
PECL mongodb 1.7.0 | Added the `MongoDB\Driver\ReadPreference::PRIMARY`, `MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED`, `MongoDB\Driver\ReadPreference::SECONDARY`, `MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED`, and `MongoDB\Driver\ReadPreference::NEAREST` constants. Implements Serializable.
PECL mongodb 1.2.0 | Added the `MongoDB\Driver\ReadPreference::NO_MAX_STALENESS` and `MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS` constants. Implements MongoDB\BSON\Serializable.

# MongoDB\Driver\ReadPreference::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization

### Description

final public MongoDB\Driver\ReadPreference::bsonSerialize(): stdClass

### Parameters

This function has no parameters.

### Return Values

Returns an object for serializing the ReadPreference as BSON.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadPreference::bsonSerialize() with primary read preference

`<?php
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
var_dump($rp->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($rp)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (1) {
      ["mode"]=>
      string(7) "primary"
    }

    { "mode" : "primary" }

Example #2 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and tag sets

`<?php
$rp = new MongoDB\Driver\ReadPreference(
MongoDB\Driver\ReadPreference::SECONDARY,
[
['dc' => 'ny'],
['dc' => 'sf', 'use' => 'reporting'],
[]
]
);
var_dump($rp->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($rp)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (2) {
      ["mode"]=>
      string(9) "secondary"
      ["tags"]=>
      array(3) {
        [0]=>
        object(stdClass)#1 (1) {
          ["dc"]=>
          string(2) "ny"
        }
        [1]=>
        object(stdClass)#5 (2) {
          ["dc"]=>
          string(2) "sf"
          ["use"]=>
          string(9) "reporting"
        }
        [2]=>
        object(stdClass)#4 (0) {
        }
      }
    }

    { "mode" : "secondary", "tags" : [ { "dc" : "ny" }, { "dc" : "sf", "use" : "reporting" }, {  } ] }

Example #3 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and max staleness

`<?php
$rp = new MongoDB\Driver\ReadPreference(
MongoDB\Driver\ReadPreference::SECONDARY,
null,
['maxStalenessSeconds' => 120]
);
var_dump($rp->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($rp)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (2) {
      ["mode"]=>
      string(9) "secondary"
      ["maxStalenessSeconds"]=>
      int(120)
    }

    { "mode" : "secondary", "maxStalenessSeconds" : 120 }

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
- » Read Preference reference

# MongoDB\Driver\ReadPreference::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference

### Description

final public MongoDB\Driver\ReadPreference::__construct(string `$mode`, ?array `$tagSets` = `null`, ?array `$options` = `null`)

Constructs a new MongoDB\Driver\ReadPreference, which is an immutable value object.

### Parameters

`mode`

  Read preference mode
  Value | Description
  --- | ---
  `"primary"` | All operations read from the current replica set primary. This is the default read preference for MongoDB.
  `"primaryPreferred"` | In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.
  `"secondary"` | All operations read from the secondary members of the replica set.
  `"secondaryPreferred"` | In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.
  `"nearest"` | Operations read from member of the replica set with the least network latency, irrespective of the member's type.

`tagSets`

  Tag sets allow you to target read operations to specific members of a replica set. This parameter should be an array of associative arrays, each of which contain zero or more key/value pairs. When selecting a server for a read operation, the driver attempt to select a node having all tags in a set (i.e. the associative array of key/value pairs). If selection fails, the driver will attempt subsequent sets. An empty tag set (`array()`) will match any node and may be used as a fallback.

  Tags are not compatible with the `"primary"` mode and, in general, only apply when selecting a secondary member of a set for a read operation. However, the `"nearest"` mode, when combined with a tag set, selects the matching member with the lowest network latency. This member may be a primary or secondary.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  hedge | object|array | Specifies whether to use » hedged reads, which are supported by MongoDB 4.4+ for sharded queries. Server hedged reads are available for all non-primary read preferences and are enabled by default when using the `"nearest"` mode. This option allows explicitly enabling server hedged reads for non-primary read preferences by specifying `['enabled' => true]`, or explicitly disabling server hedged reads for the `"nearest"` read preference by specifying `['enabled' => false]`.
  maxStalenessSeconds | int | Specifies a maximum replication lag, or "staleness", for reads from secondaries. When a secondary's estimated staleness exceeds this value, the driver stops using it for read operations. If specified, the max staleness must be a signed 32-bit integer greater than or equal to `MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS`. Defaults to `MongoDB\Driver\ReadPreference::NO_MAX_STALENESS`, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation. This option is not compatible with the `"primary"` mode. Specifying a max staleness also requires all MongoDB instances in the deployment to be using MongoDB 3.4+. An exception will be thrown at execution time if any MongoDB instances in the deployment are of an older server version.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `mode` is invalid.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `tagSets` is provided for a primary read preference or is malformed (i.e. not an array of zero or more documents).
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"maxStalenessSeconds"` option is provided for a primary read preference or is out of range.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Passing an int for the `mode` argument is no longer supported.
PECL mongodb 1.20.0 | Passing an int for the `mode` argument is DEPRECATED.
PECL mongodb 1.8.0 | Added the `"hedge"` option.
PECL mongodb 1.3.0 | The `mode` argument now accepts a string value, which is consistent with the `"readPreference"` URI option for MongoDB\Driver\Manager::__construct().
PECL mongodb 1.2.0 | Added a third `options` argument, which supports the `"maxStalenessSeconds"` option.

### Examples

Example #1 MongoDB\Driver\ReadPreference::__construct() example

`<?php
/* Prefer a secondary node but fall back to a primary. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED));
/* Prefer a node in the New York data center with lowest latency. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::NEAREST, [['dc' => 'ny']]));
/* Require a secondary node whose replication lag is within two minutes of the primary */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY, null, ['maxStalenessSeconds' => 120]));
/* Explicitly enable server hedged reads */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY, null, ['hedge' => ['enabled' => true]]));
?>`

The above example will output:

    object(MongoDB\Driver\ReadPreference)#1 (1) {
      ["mode"]=>
      string(18) "secondaryPreferred"
    }
    object(MongoDB\Driver\ReadPreference)#1 (2) {
      ["mode"]=>
      string(7) "nearest"
      ["tags"]=>
      array(1) {
        [0]=>
        object(stdClass)#2 (1) {
          ["dc"]=>
          string(2) "ny"
        }
      }
    }
    object(MongoDB\Driver\ReadPreference)#1 (2) {
      ["mode"]=>
      string(9) "secondary"
      ["maxStalenessSeconds"]=>
      int(120)
    }
    object(MongoDB\Driver\ReadPreference)#1 (2) {
      ["mode"]=>
      string(9) "secondary"
      ["hedge"]=>
      object(stdClass)#1 (1) {
        ["enabled"]=>
        bool(true)
      }
    }

### See Also

- » Read Preference reference

# MongoDB\Driver\ReadPreference::getHedge

(mongodb >=1.8.0)

MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option

### Description

final public MongoDB\Driver\ReadPreference::getHedge(): ?object

### Parameters

This function has no parameters.

### Return Values

Returns the ReadPreference's "hedge" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- » Read Preference reference

# MongoDB\Driver\ReadPreference::getMaxStalenessSeconds

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option

### Description

final public MongoDB\Driver\ReadPreference::getMaxStalenessSeconds(): int

### Parameters

This function has no parameters.

### Return Values

Returns the ReadPreference's "maxStalenessSeconds" option. If no max staleness has been specified, `MongoDB\Driver\ReadPreference::NO_MAX_STALENESS` will be returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadPreference::getMaxStalenessSeconds() example

`<?php
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY);
var_dump($rp->getMaxStalenessSeconds());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY, null, [
'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::NO_MAX_STALENESS,
]);
var_dump($rp->getMaxStalenessSeconds());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY, null, [
'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS,
]);
var_dump($rp->getMaxStalenessSeconds());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY, null, [
'maxStalenessSeconds' => 1000,
]);
var_dump($rp->getMaxStalenessSeconds());
?>`

The above example will output:

    int(-1)
    int(-1)
    int(90)
    int(1000)

### See Also

- » Read Preference reference

# MongoDB\Driver\ReadPreference::getMode

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\Driver\ReadPreference::getModeString() instead.

### Description

final public MongoDB\Driver\ReadPreference::getMode(): int

### Parameters

This function has no parameters.

### Return Values

Returns the ReadPreference's "mode" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method was removed.

### Examples

Example #1 MongoDB\Driver\ReadPreference::getMode() example

`<?php
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
var_dump($rp->getMode());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED);
var_dump($rp->getMode());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY);
var_dump($rp->getMode());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED);
var_dump($rp->getMode());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::NEAREST);
var_dump($rp->getMode());
?>`

The above example will output:

    int(1)
    int(5)
    int(2)
    int(6)
    int(10)

### See Also

- MongoDB\Driver\ReadPreference::getModeString() - Returns the ReadPreference's "mode" option
- » Read Preference reference

# MongoDB\Driver\ReadPreference::getModeString

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option

### Description

final public MongoDB\Driver\ReadPreference::getModeString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the ReadPreference's "mode" option as a string.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadPreference::getModeString() example

`<?php
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
var_dump($rp->getModeString());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED);
var_dump($rp->getModeString());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY);
var_dump($rp->getModeString());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED);
var_dump($rp->getModeString());
$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::NEAREST);
var_dump($rp->getModeString());
?>`

The above example will output:

    string(7) "primary"
    string(16) "primaryPreferred"
    string(9) "secondary"
    string(18) "secondaryPreferred"
    string(7) "nearest"

### See Also

- MongoDB\Driver\ReadPreference::getMode() - Returns the ReadPreference's "mode" option
- » Read Preference reference

# MongoDB\Driver\ReadPreference::getTagSets

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option

### Description

final public MongoDB\Driver\ReadPreference::getTagSets(): array

### Parameters

This function has no parameters.

### Return Values

Returns the ReadPreference's "tagSets" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadPreference::getTagSets() example

`<?php
$mode = MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED;
/* Null and an empty array both denote no tag set preference. */
$rp = new MongoDB\Driver\ReadPreference($mode, null);
var_dump($rp->getTagSets());
$rp = new MongoDB\Driver\ReadPreference($mode, []);
var_dump($rp->getTagSets());
/* Prefer a node in New York, but fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [['dc' => 'ny']]);
var_dump($rp->getTagSets());
/* Prefer a node in the New York, followed by a node in San Francisco that is
labeled for reporting usage, and finally fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [
['dc' => 'ny'],
['dc' => 'sf', 'use' => 'reporting'],
[],
]);
var_dump($rp->getTagSets());
?>`

The above example will output:

    array(0) {
    }
    array(0) {
    }
    array(2) {
      [0]=>
      array(1) {
        ["dc"]=>
        string(2) "ny"
      }
      [1]=>
      array(0) {
      }
    }
    array(3) {
      [0]=>
      array(1) {
        ["dc"]=>
        string(2) "ny"
      }
      [1]=>
      array(2) {
        ["dc"]=>
        string(2) "sf"
        ["use"]=>
        string(9) "reporting"
      }
      [2]=>
      array(0) {
      }
    }

### See Also

- » Read Preference reference

## Table of Contents

- MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
- MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option
- MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
- MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
- MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option
- MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option

# The MongoDB\Driver\ReadConcern class

(mongodb >=1.1.0)

## Introduction

MongoDB\Driver\ReadConcern controls the level of isolation for read operations for replica sets and replica set shards. This option requires MongoDB 3.2 or later.

## Class synopsis

final class MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable, Serializable {
/* Constants */
const string AVAILABLE = "available";
const string LINEARIZABLE = "linearizable";
const string LOCAL = "local";
const string MAJORITY = "majority";
const string SNAPSHOT = "snapshot";
/* Methods */
final public bsonSerialize(): stdClass
final public __construct(?string `$level` = `null`)
final public getLevel(): ?string
final public isDefault(): bool
}

## Predefined Constants

`MongoDB\Driver\ReadConcern::AVAILABLE`

  Default for reads against secondaries when `afterClusterTime`and `level` are unspecified.

  The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

  For unsharded collections (including collections in a standalone deployment or a replica set deployment), `"local"` and `"available"` read concerns behave identically.

  For a sharded cluster, `"available"` read concern provides greater tolerance for partitions since it does not wait to ensure consistency guarantees. However, a query with `"available"` read concern may return orphan documents if the shard is undergoing chunk migrations since the `"available"` read concern, unlike `"local"` read concern, does not contact the shard's primary nor the config servers for updated metadata.

`MongoDB\Driver\ReadConcern::LINEARIZABLE`

  The query returns data that reflects all successful writes issued with a write concern of `"majority"` and acknowledged prior to the start of the read operation. For replica sets that run with `writeConcernMajorityJournalDefault` set to `true`, linearizable read concern returns data that will never be rolled back.

  With `writeConcernMajorityJournalDefault` set to `false`, MongoDB will not wait for `w: "majority"` writes to be durable before acknowledging the writes. As such, `"majority"` write operations could possibly roll back in the event of a loss of a replica set member.

  You can specify linearizable read concern for read operations on the primary only.

  Linearizable read concern guarantees only apply if read operations specify a query filter that uniquely identifies a single document.

  Tip

  Always use `maxTimeMS` with linearizable read concern in case a majority of data bearing members are unavailable. `maxTimeMS` ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.

  Linearizable read concern requires MongoDB 3.4.

`MongoDB\Driver\ReadConcern::LOCAL`

  Default for reads against primary if `level` is unspecified and for reads against secondaries if `level` is unspecified but `afterClusterTime` is specified.

  The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

`MongoDB\Driver\ReadConcern::MAJORITY`

  The query returns the instance's most recent data acknowledged as having been written to a majority of members in the replica set.

  To use read concern level of `"majority"`, replica sets must use WiredTiger storage engine and election protocol version 1.

`MongoDB\Driver\ReadConcern::SNAPSHOT`

  Read concern `"snapshot"` is available for multi-document transactions, and starting in MongoDB 5.0, certain read operations outside of multi-document transactions.

  If the transaction is not part of a causally consistent session, upon transaction commit with write concern `"majority"`, the transaction operations are guaranteed to have read from a snapshot of majority-committed data.

  If the transaction is part of a causally consistent session, upon transaction commit with write concern `"majority"`, the transaction operations are guaranteed to have read from a snapshot of majority-committed data that provides causal consistency with the operation immediately preceding the transaction start.

  Outside of multi-document transactions, read concern `"snapshot"` is available on primaries and secondaries for the following read operations: `find`, `aggregate`, and `distinct` (on unsharded collections). All other read commands prohibit `"snapshot"`.

## Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | Added the `MongoDB\Driver\ReadConcern::SNAPSHOT` constant.
PECL mongodb 1.7.0 | Implements Serializable.
PECL mongodb 1.4.0 | Added the `MongoDB\Driver\ReadConcern::AVAILABLE` constant.
PECL mongodb 1.2.0 | Added the `MongoDB\Driver\ReadConcern::LINEARIZABLE` constant. Implements MongoDB\BSON\Serializable.

## See Also

- » Read Concern reference

# MongoDB\Driver\ReadConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization

### Description

final public MongoDB\Driver\ReadConcern::bsonSerialize(): stdClass

### Parameters

This function has no parameters.

### Return Values

Returns an object for serializing the ReadConcern as BSON.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadConcern::bsonSerialize() with empty read concern

`<?php
$rc = new MongoDB\Driver\ReadConcern;
var_dump($rc->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($rc)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (0) {
    }

    { }

Example #2 MongoDB\Driver\ReadConcern::bsonSerialize() with local read concern

`<?php
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->bsonSerialize());
echo "\n", MongoDB\BSON\Document::fromPHP($rc)->toRelaxedExtendedJSON();
?>`

The above example will output something similar to:

    object(stdClass)#2 (1) {
      ["level"]=>
      string(5) "local"
    }

    { "level" : "local" }

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
- » Read Concern reference

# MongoDB\Driver\ReadConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern

### Description

final public MongoDB\Driver\ReadConcern::__construct(?string `$level` = `null`)

Constructs a new MongoDB\Driver\ReadConcern, which is an immutable value object.

### Parameters

`level`

  The » read concern level. You may use, but are not limited to, one of the class constants.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadConcern::__construct() example

`<?php
/* Unspecified read isolation level (uses the server's default behavior) */
$rc = new MongoDB\Driver\ReadConcern();
/* Request read isolation from a single replica set node */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
/* Request read isolation from a majority of the replica set nodes */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
?>`

### See Also

- » Read Concern reference

# MongoDB\Driver\ReadConcern::getLevel

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option

### Description

final public MongoDB\Driver\ReadConcern::getLevel(): ?string

### Parameters

This function has no parameters.

### Return Values

Returns the ReadConcern's "level" option.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadConcern::getLevel() example

`<?php
$rc = new MongoDB\Driver\ReadConcern();
var_dump($rc->getLevel());
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->getLevel());
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->getLevel());
?>`

The above example will output:

    NULL
    string(5) "local"
    string(8) "majority"

### See Also

- » Read Concern reference

# MongoDB\Driver\ReadConcern::isDefault

(mongodb >=1.3.0)

MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern

### Description

final public MongoDB\Driver\ReadConcern::isDefault(): bool

Returns whether this is the default read concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getReadConcern() to determine whether the Manager has been constructed without any read concern options.

The driver will not include a default read concern in its read operations (e.g. MongoDB\Driver\Manager::executeQuery()) in order order to allow the server to apply its own default. Libraries that access the Manager's read concern to include it in their own read commands should use this method to ensure that default read concerns are left unset.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this is the default read concern and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\ReadConcern::isDefault() example

`<?php
$rc = new MongoDB\Driver\ReadConcern(null);
var_dump($rc->isDefault());
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->isDefault());
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?readConcernLevel=majority');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());
?>`

The above example will output:

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

### See Also

- MongoDB\Driver\Manager::getReadConcern() - Return the ReadConcern for the Manager
- » Read Concern reference

## Table of Contents

- MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern
- MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
- MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern

# The MongoDB\Driver\Cursor class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand() or MongoDB\Driver\Manager::executeQuery(), respectively.

## Class synopsis

final class MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface {
/* Methods */
final private __construct()
public current(): array|object|null
final public getId(): MongoDB\BSON\Int64
final public getServer(): MongoDB\Driver\Server
final public isDead(): bool
public key(): int
public next(): void
public rewind(): void
final public setTypeMap(array `$typemap`): void
final public toArray(): array
public valid(): bool
}

## Changelog

Version | Description
--- | ---
PECL mongodb 1.9.0 | Implements Iterator.
PECL mongodb 1.6.0 | Implements MongoDB\Driver\CursorInterface, which extends Traversable.

## Examples

Example #1 Reading a result set

MongoDB\Driver\Manager::executeCommand() and MongoDB\Driver\Manager::executeQuery() both return their result(s) as a MongoDB\Driver\Cursor object. This object can be used to iterate over the result set of the command or query.

Because MongoDB\Driver\Cursor implements the Traversable interface, you can simply iterate over the result set with `foreach`.

`<?php
$manager = new MongoDB\Driver\Manager();
/* Insert some documents so that our query returns information */
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['name' => 'Ceres', 'size' => 946, 'distance' => 2.766]);
$bulkWrite->insert(['name' => 'Vesta', 'size' => 525, 'distance' => 2.362]);
$manager->executeBulkWrite("test.asteroids", $bulkWrite);
/* Query for all the items in the collection */
$query = new MongoDB\Driver\Query( [] );
/* Query the "asteroids" collection of the "test" database */
$cursor = $manager->executeQuery("test.asteroids", $query);
/* $cursor now contains an object that wraps around the result set. Use
* foreach() to iterate over all the result */
foreach($cursor as $document) {
print_r($document);
}
?>`

The above example will output something similar to:

    stdClass Object
    (
        [_id] => MongoDB\BSON\ObjectId Object
            (
                [oid] => 5a4cff2f122d3321565d8cc2
            )

        [name] => Ceres
        [size] => 946
        [distance] => 2.766
    )
    stdClass Object
    (
        [_id] => MongoDB\BSON\ObjectId Object
            (
                [oid] => 5a4cff2f122d3321565d8cc3
            )

        [name] => Vesta
        [size] => 525
        [distance] => 2.362
    }

Example #2 Reading a result set for a tailable cursor

» Tailable cursors are a special type of MongoDB cursor that allows the client to read some results and then wait until more documents become available. These cursors are primarily used with » Capped Collections and » Change Streams.

While normal cursors can be iterated once with `foreach`, that approach will not work with tailable cursors. When `foreach` is used with a tailable cursor, the loop will stop upon reaching the end of the initial result set. Attempting to continue iteration on the cursor with a second `foreach` would throw an exception, since PHP attempts to rewind the cursor. Similar to result objects in other database drivers, cursors in MongoDB only support forward iteration, which means they cannot be rewound.

In order to continuously read from a tailable cursor, the Cursor object must be wrapped with an IteratorIterator. This allows the application to directly control the cursor's iteration, avoid inadvertently rewinding the cursor, and decide when to wait for new results or stop iteration entirely.

In order to demonstrate a tailable cursor in action, two scripts will be used: a "producer" and a "consumer". The producer script will create a new capped collection using the » create command and proceed to insert a new document into that collection each second.

`<?php
$manager = new MongoDB\Driver\Manager;
$manager->executeCommand('test', new MongoDB\Driver\Command([
'create' => 'asteroids',
'capped' => true,
'size' => 1048576,
]));
while (true) {
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['createdAt' => new MongoDB\BSON\UTCDateTime]);
$manager->executeBulkWrite('test.asteroids', $bulkWrite);
sleep(1);
}
?>`

With the producer script still running, a second consumer script may be executed to read the inserted documents using a tailable cursor, indicated by the `tailable` and `awaitData` options to MongoDB\Driver\Query::__construct().

`<?php
$manager = new MongoDB\Driver\Manager;
$query = new MongoDB\Driver\Query([], [
'tailable' => true,
'awaitData' => true,
]);
$cursor = $manager->executeQuery('test.asteroids', $query);
$iterator = new IteratorIterator($cursor);
$iterator->rewind();
while (true) {
if ($iterator->valid()) {
$document = $iterator->current();
printf("Consumed document created at: %s\n", $document->createdAt);
}
$iterator->next();
}
?>`

The consumer script will start by quickly printing all available documents in the capped collection (as if `foreach` had been used); however, it will not terminate upon reaching the end of the initial result set. Since the cursor is tailable, calling IteratorIterator::next() will block and wait for additional results. IteratorIterator::valid() is also used to check if there is actually data available to read at each step.

> Note: This example uses the `awaitData` query option to instruct the server to block for a short period (e.g. one second) at the end of the result set before returning a response to the driver. This is used to prevent the driver from aggressively polling the server when there are no results available. The `maxAwaitTimeMS` option may be used in conjunction with `tailable` and `awaitData` to specify the amount of time that the server should block when it reaches the end of the result set.

## Errors/Exceptions

When iterating over the cursor object, BSON data is converted into PHP variables. This iteration can cause the following Exceptions:

- Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

# MongoDB\Driver\Cursor::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)

### Description

final private MongoDB\Driver\Cursor::__construct()

MongoDB\Driver\Cursor objects are returned as the result of an executed command or query and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\Driver\Manager::executeCommand() - Execute a database command
- MongoDB\Driver\Manager::executeQuery() - Execute a database query
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
- MongoDB\Driver\Server::executeQuery() - Execute a database query on this server

# MongoDB\Driver\Cursor::current

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::current — Returns the current element

### Description

public MongoDB\Driver\Cursor::current(): array|object|null

### Parameters

This function has no parameters.

### Return Values

Returns the current result document as an array or object, depending on the cursor's type map. If iteration has not started or the current position is not valid, `null` will be returned.

### See Also

- Iterator::current() - Return the current element

# MongoDB\Driver\Cursor::getId

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getId — Returns the ID for this cursor

### Description

final public MongoDB\Driver\Cursor::getId(): MongoDB\BSON\Int64

Returns the ID for this cursor, which uniquely identifies the cursor on the server.

### Parameters

This function has no parameters.

### Return Values

Returns the ID for this cursor. The ID will be returned as a MongoDB\BSON\Int64 object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The return type was changed to MongoDB\BSON\Int64. The `asInt64` parameter was removed.
PECL mongodb 1.20.0 | Deprecated returning a MongoDB\Driver\CursorId. Added the `asInt64` argument to ease migration for future versions. If `asInt64` is `true`, the ID will be returned as a MongoDB\BSON\Int64.

### Examples

Example #1 MongoDB\Driver\Cursor::getId() example

`<?php
/* In this example, we insert several documents into the collection and specify
* a smaller batchSize to ensure that the first batch contains only a subset of
* our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);
$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getId(true));
?>`

The above example will output something similar to:

    object(MongoDB\BSON\Int64)#5 (1) {
      ["integer"]=>
      string(11) "94810124093"
    }

### See Also

- MongoDB\BSON\Int64

# MongoDB\Driver\Cursor::getServer

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor

### Description

final public MongoDB\Driver\Cursor::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server associated with this cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Cursor::getServer() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);
$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getServer());
?>`

The above example will output something similar to:

    object(MongoDB\Driver\Server)#5 (10) {
      ["host"]=>
      string(9) "localhost"
      ["port"]=>
      int(27017)
      ["type"]=>
      int(1)
      ["is_primary"]=>
      bool(false)
      ["is_secondary"]=>
      bool(false)
      ["is_arbiter"]=>
      bool(false)
      ["is_hidden"]=>
      bool(false)
      ["is_passive"]=>
      bool(false)
      ["last_hello_response"]=>
      array(8) {
        ["isWritablePrimary"]=>
        bool(true)
        ["maxBsonObjectSize"]=>
        int(16777216)
        ["maxMessageSizeBytes"]=>
        int(48000000)
        ["maxWriteBatchSize"]=>
        int(1000)
        ["localTime"]=>
        object(MongoDB\BSON\UTCDateTime)#6 (1) {
          ["milliseconds"]=>
          int(1446505367907)
        }
        ["maxWireVersion"]=>
        int(3)
        ["minWireVersion"]=>
        int(0)
        ["ok"]=>
        float(1)
      }
      ["round_trip_time"]=>
      int(584)
    }

### See Also

- MongoDB\Driver\Server

# MongoDB\Driver\Cursor::isDead

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results

### Description

final public MongoDB\Driver\Cursor::isDead(): bool

Checks whether there are definitely no additional results available on the cursor. This method is similar to the » cursor.isExhausted() method in the MongoDB shell and is primarily useful when iterating » tailable cursors.

A cursor has no additional results and is considered "dead" when one of the following is true:

- The current batch has been fully iterated and the cursor ID is zero (i.e. a » getMore cannot be issued).
- An error was encountered while iterating the cursor.
- The cursor reached its configured limit.

By design, it is not possible to always determine whether a cursor has additional results. The cases where a cursor may have more data available is as follows:

- There are additional documents in the current batch, which are buffered on the client side. Iterating will fetch a document from the local buffer.
- There are no additional documents in the current batch (i.e. local buffer), but the cursor ID is non-zero. Iterating will request more documents from the server via a » getMore operation, which may or may not return additional results and/or indicate that the cursor has been closed on the server by returning zero for its ID.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if there are definitely no additional results available on the cursor, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Cursor::isDead() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);
$cursor = $manager->executeQuery('db.collection', $query);
$iterator = new IteratorIterator($cursor);
$iterator->rewind();
var_dump($cursor->isDead());
$iterator->next();
var_dump($cursor->isDead());
$iterator->next();
var_dump($cursor->isDead());
$iterator->next();
var_dump($cursor->isDead());
?>`

The above example will output:

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

### See Also

- » Tailable Cursors in the MongoDB manual
- » cursor.isExhausted() in the MongoDB manual

# MongoDB\Driver\Cursor::key

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor

### Description

public MongoDB\Driver\Cursor::key(): int

### Parameters

This function has no parameters.

### Return Values

The current result's numeric index within the cursor.

### See Also

- Iterator::key() - Return the key of the current element

# MongoDB\Driver\Cursor::next

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::next — Advances the cursor to the next result

### Description

public MongoDB\Driver\Cursor::next(): void

### Parameters

This function has no parameters.

### Return Values

Moves the current position to the next element in the cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.

### See Also

- Iterator::next() - Move forward to next element

# MongoDB\Driver\Cursor::rewind

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result

### Description

public MongoDB\Driver\Cursor::rewind(): void

If the cursor has advanced beyond its first position, it can no longer be rewound.

### Parameters

This function has no parameters.

### Return Values

`null`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\LogicException if this method is called after the cursor has advanced beyond its first position.

### See Also

- Iterator::rewind() - Rewind the Iterator to the first element

# MongoDB\Driver\Cursor::setTypeMap

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization

### Description

final public MongoDB\Driver\Cursor::setTypeMap(array `$typemap`): void

Sets the type map configuration to use when unserializing the BSON results into PHP values.

### Parameters

`typeMap` (array)

  Type map configuration.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

When iterating over the cursor, the following exceptions can also be thrown due to an incorrect type map configuration:

- Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

### Examples

Example #1 MongoDB\Driver\Cursor::setTypeMap() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$id = $bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);
$query = new MongoDB\Driver\Query(['_id' => $id]);
$cursor = $manager->executeQuery('db.collection', $query);
$cursor->setTypeMap(['root' => 'array']);
foreach ($cursor as $document) {
var_dump($document);
}
?>`

The above example will output something similar to:

    array(2) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#6 (1) {
        ["oid"]=>
        string(24) "56424fb76118fd3267180741"
      }
      ["x"]=>
      int(1)
    }

### See Also

- Persisting Data

# MongoDB\Driver\Cursor::toArray

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor

### Description

final public MongoDB\Driver\Cursor::toArray(): array

Iterates the cursor and returns its results in an array. MongoDB\Driver\Cursor::setTypeMap() may be used to control how documents are unserialized into PHP values.

### Parameters

This function has no parameters.

### Return Values

Returns an array containing all results for this cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Cursor::toArray() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);
$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->toArray());
?>`

The above example will output something similar to:

    array(3) {
      [0]=>
      object(stdClass)#6 (2) {
        ["_id"]=>
        object(MongoDB\BSON\ObjectId)#5 (1) {
          ["oid"]=>
          string(24) "564259a96118fd40b41bcf61"
        }
        ["x"]=>
        int(1)
      }
      [1]=>
      object(stdClass)#8 (2) {
        ["_id"]=>
        object(MongoDB\BSON\ObjectId)#7 (1) {
          ["oid"]=>
          string(24) "564259a96118fd40b41bcf62"
        }
        ["x"]=>
        int(2)
      }
      [2]=>
      object(stdClass)#10 (2) {
        ["_id"]=>
        object(MongoDB\BSON\ObjectId)#9 (1) {
          ["oid"]=>
          string(24) "564259a96118fd40b41bcf63"
        }
        ["x"]=>
        int(3)
      }
    }

### See Also

- MongoDB\Driver\Cursor::setTypeMap() - Sets a type map to use for BSON unserialization

# MongoDB\Driver\Cursor::valid

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid

### Description

public MongoDB\Driver\Cursor::valid(): bool

### Parameters

This function has no parameters.

### Return Values

`true` if the current cursor position is valid, `false` otherwise.

### See Also

- Iterator::valid() - Checks if current position is valid

## Table of Contents

- MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
- MongoDB\Driver\Cursor::current — Returns the current element
- MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
- MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
- MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results
- MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor
- MongoDB\Driver\Cursor::next — Advances the cursor to the next result
- MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result
- MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
- MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
- MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid

# The MongoDB\Driver\CursorId class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\CursorID class is a value object that represents a cursor ID. Instances of this class are returned by MongoDB\Driver\Cursor::getId().

Warning

This class has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications have to update their usage of MongoDB\Driver\Cursor::getId() to return MongoDB\BSON\Int64 instead.

## Class synopsis

final class MongoDB\Driver\CursorId implements Serializable, Stringable {
/* Methods */
final private __construct()
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class was removed.
PECL mongodb 1.20.0 | This class has been deprecated and will be removed in version 2.0.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.7.0 | Implements Serializable.

# MongoDB\Driver\CursorId::__construct

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)

### Description

final private MongoDB\Driver\CursorId::__construct()

MongoDB\Driver\CursorId objects are returned from MongoDB\Driver\Cursor::getId() and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor

# MongoDB\Driver\CursorId::__toString

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__toString — String representation of the cursor ID

### Description

final public MongoDB\Driver\CursorId::__toString(): string

Returns the string representation of the cursor ID.

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of the cursor ID.

### Examples

Example #1 MongoDB\Driver\CursorId::__toString() example

`<?php
/* In this example, we insert several documents into the collection and specify
* a smaller batchSize to ensure that the first batch contains only a subset of
* our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);
$cursor = $manager->executeQuery('db.collection', $query);
var_dump((string) $cursor->getId());
?>`

The above example will output something similar to:

    string(11) "98061641158"

### See Also

- MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor

## Table of Contents

- MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
- MongoDB\Driver\CursorId::__toString — String representation of the cursor ID

# The MongoDB\Driver\CursorInterface interface

(mongodb >=1.6.0)

## Introduction

This interface is implemented by MongoDB\Driver\Cursor to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\Driver\CursorInterface implements Iterator {
/* Methods */
abstract public getId(): MongoDB\BSON\Int64
abstract public getServer(): MongoDB\Driver\Server
abstract public isDead(): bool
abstract public setTypeMap(array `$typemap`): void
abstract public toArray(): array
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This interface now extends Iterator. Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\Driver\CursorInterface::getId

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::getId — Returns the ID for this cursor

### Description

abstract public MongoDB\Driver\CursorInterface::getId(): MongoDB\BSON\Int64

Returns the ID for this cursor, which uniquely identifies the cursor on the server.

### Parameters

This function has no parameters.

### Return Values

Returns the ID for this cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.20.0 | Added MongoDB\BSON\Int64 to the tentative return type for this method. MongoDB\Driver\CursorId will be removed from the return type in version 2.0.

### See Also

- MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor
- MongoDB\Driver\CursorId
- MongoDB\BSON\Int64

# MongoDB\Driver\CursorInterface::getServer

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::getServer — Returns the server associated with this cursor

### Description

abstract public MongoDB\Driver\CursorInterface::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server associated with this cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Cursor::getServer() - Returns the server associated with this cursor
- MongoDB\Driver\Server

# MongoDB\Driver\CursorInterface::isDead

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::isDead — Checks if the cursor may have additional results

### Description

abstract public MongoDB\Driver\CursorInterface::isDead(): bool

Checks whether the cursor may have additional results available to read. A cursor is initially "alive" but may become "dead" for any of the following reasons:

- Advancing a non-tailable cursor did not return a document
- The cursor encountered an error
- The cursor read its last batch to completion
- The cursor reached its configured limit

This is primarily useful with tailable cursors.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if additional results are not available, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Cursor::isDead() - Checks if the cursor is exhausted or may have additional results

# MongoDB\Driver\CursorInterface::setTypeMap

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::setTypeMap — Sets a type map to use for BSON unserialization

### Description

abstract public MongoDB\Driver\CursorInterface::setTypeMap(array `$typemap`): void

Sets the type map configuration to use when unserializing the BSON results into PHP values.

### Parameters

`typeMap` (array)

  Type map configuration.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Cursor::setTypeMap() - Sets a type map to use for BSON unserialization
- Persisting Data

# MongoDB\Driver\CursorInterface::toArray

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::toArray — Returns an array containing all results for this cursor

### Description

abstract public MongoDB\Driver\CursorInterface::toArray(): array

Iterates the cursor and returns its results in an array. MongoDB\Driver\CursorInterface::setTypeMap() may be used to control how documents are unserialized into PHP values.

### Parameters

This function has no parameters.

### Return Values

Returns an array containing all results for this cursor.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Cursor::toArray() - Returns an array containing all results for this cursor
- MongoDB\Driver\CursorInterface::setTypeMap() - Sets a type map to use for BSON unserialization

## Table of Contents

- MongoDB\Driver\CursorInterface::getId — Returns the ID for this cursor
- MongoDB\Driver\CursorInterface::getServer — Returns the server associated with this cursor
- MongoDB\Driver\CursorInterface::isDead — Checks if the cursor may have additional results
- MongoDB\Driver\CursorInterface::setTypeMap — Sets a type map to use for BSON unserialization
- MongoDB\Driver\CursorInterface::toArray — Returns an array containing all results for this cursor

# The MongoDB\Driver\Server class

(mongodb >=1.0.0)

## Introduction

## Class synopsis

final class MongoDB\Driver\Server {
/* Constants */
const int TYPE_UNKNOWN = 0;
const int TYPE_STANDALONE = 1;
const int TYPE_MONGOS = 2;
const int TYPE_POSSIBLE_PRIMARY = 3;
const int TYPE_RS_PRIMARY = 4;
const int TYPE_RS_SECONDARY = 5;
const int TYPE_RS_ARBITER = 6;
const int TYPE_RS_OTHER = 7;
const int TYPE_RS_GHOST = 8;
const int TYPE_LOAD_BALANCER = 9;
/* Methods */
final private __construct()
final public executeBulkWrite(string `$namespace`, MongoDB\Driver\BulkWrite `$bulk`, ?array `$options` = `null`): MongoDB\Driver\WriteResult
final public executeBulkWriteCommand(MongoDB\Driver\BulkWriteCommand `$bulk`, ?array `$options` = `null`): MongoDB\Driver\BulkWriteCommandResult
final public executeCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeQuery(string `$namespace`, MongoDB\Driver\Query `$query`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeReadCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeReadWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public executeWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor
final public getHost(): string
final public getInfo(): array
final public getLatency(): ?integer
final public getPort(): int
final public getServerDescription(): MongoDB\Driver\ServerDescription
final public getTags(): array
final public getType(): int
final public isArbiter(): bool
final public isHidden(): bool
final public isPassive(): bool
final public isPrimary(): bool
final public isSecondary(): bool
}

## Predefined Constants

`MongoDB\Driver\Server::TYPE_UNKNOWN`

  Unknown server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_STANDALONE`

  Standalone server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_MONGOS`

  Mongos server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY`

  Replica set possible primary server type, returned by MongoDB\Driver\Server::getType().

  A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

`MongoDB\Driver\Server::TYPE_RS_PRIMARY`

  Replica set primary server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_RS_SECONDARY`

  Replica set secondary server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_RS_ARBITER`

  Replica set arbiter server type, returned by MongoDB\Driver\Server::getType().

`MongoDB\Driver\Server::TYPE_RS_OTHER`

  Replica set other server type, returned by MongoDB\Driver\Server::getType().

  Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

`MongoDB\Driver\Server::TYPE_RS_GHOST`

  Replica set ghost server type, returned by MongoDB\Driver\Server::getType().

  Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

`MongoDB\Driver\Server::TYPE_LOAD_BALANCER`

  Load balancer server type, returned by MongoDB\Driver\Server::getType().

## Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | Added the `MongoDB\Driver\Server::TYPE_LOAD_BALANCER` constant.

# MongoDB\Driver\Server::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Server::__construct — Create a new Server (not used)

### Description

final private MongoDB\Driver\Server::__construct()

MongoDB\Driver\Server objects are created internally by MongoDB\Driver\Manager when a database connection is established and may be returned by MongoDB\Driver\Manager::getServers() and MongoDB\Driver\Manager::selectServer().

### Parameters

This function has no parameters.

### See Also

- MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
- MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference

# MongoDB\Driver\Server::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server

### Description

final public MongoDB\Driver\Server::executeBulkWrite(string `$namespace`, MongoDB\Driver\BulkWrite `$bulk`, ?array `$options` = `null`): MongoDB\Driver\WriteResult

Executes one or more write operations on this server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`bulk` (MongoDB\Driver\BulkWrite)

  The write(s) to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

### Return Values

Returns MongoDB\Driver\WriteResult on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` does not contain any write operations.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\WriteConcern instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\WriteConcern object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is now thrown if `bulk` does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

### Notes

> Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

### See Also

- MongoDB\Driver\BulkWrite
- MongoDB\Driver\WriteResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations

# MongoDB\Driver\Server::executeBulkWriteCommand

(mongodb >=2.1.0)

MongoDB\Driver\Server::executeBulkWriteCommand — Execute write operations on this server using the bulkWrite command

### Description

final public MongoDB\Driver\Server::executeBulkWriteCommand(MongoDB\Driver\BulkWriteCommand `$bulk`, ?array `$options` = `null`): MongoDB\Driver\BulkWriteCommandResult

Executes one or more write operations on this server using the » bulkWrite command introduced in MongoDB 8.0.

A MongoDB\Driver\BulkWriteCommand can be constructed with one or more write operations of varying types (e.g. inserts, updates, and deletes). Each write operation may target a different collection.

The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`bulk` (MongoDB\Driver\BulkWriteCommand)

  The write(s) to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

### Return Values

Returns MongoDB\Driver\BulkWriteCommandResult on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` does not contain any write operations.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `bulk` has already been executed. MongoDB\Driver\BulkWriteCommand objects may not be executed multiple times.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\BulkWriteCommandException on any write failure (e.g. command failure, write or write concern error)
- Throws MongoDB\Driver\Exception\RuntimeException on other errors.

### See Also

- MongoDB\Driver\BulkWriteCommand
- MongoDB\Driver\BulkWriteCommandResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command

# MongoDB\Driver\Server::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeCommand — Execute a database command on this server

### Description

final public MongoDB\Driver\Server::executeCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on this server.

This method applies no special logic to the command. The Default values for the `"readPreference"`, `"readConcern"`, and `"writeConcern"` options will be inferred from an active transaction (indicated by the `"session"` option). If there is no active transaction, a primary read preference will be used for server selection.

Default values will not be inferred from the connection URI. Users are therefore encouraged to use specific read and/or write command methods if possible.

> Note: The `"readPreference"` option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\ReadPreference instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\ReadPreference object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

### Notes

> Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
- MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
- MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
- MongoDB\Driver\Manager::executeCommand() - Execute a database command

# MongoDB\Driver\Server::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeQuery — Execute a database query on this server

### Description

final public MongoDB\Driver\Server::executeQuery(string `$namespace`, MongoDB\Driver\Query `$query`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the query on this server.

Default values for the `"readPreference"` option and Query's `"readConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

> Note: The `"readPreference"` option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

### Parameters

`namespace` (string)

  A fully qualified namespace (e.g. `"databaseName.collectionName"`).

`query` (MongoDB\Driver\Query)

  The query to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `options` parameter no longer accepts a MongoDB\Driver\ReadPreference instance.
PECL mongodb 1.21.0 | Passing a MongoDB\Driver\ReadPreference object as `options` is deprecated and will be removed in 2.0.
PECL mongodb 1.4.0 | The third parameter is now an `options` array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

### See Also

- MongoDB\Driver\Cursor
- MongoDB\Driver\Query
- MongoDB\Driver\ReadPreference
- MongoDB\Driver\Manager::executeQuery() - Execute a database query

# MongoDB\Driver\Server::executeReadCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server

### Description

final public MongoDB\Driver\Server::executeReadCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on this server, irrespective of the `"readPreference"` option.

This method will apply logic that is specific to commands that read (e.g. » distinct). Default values for the `"readPreference"` and `"readConcern"` options will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

> Note: The `"readPreference"` option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation.
  session | MongoDB\Driver\Session | A session to associate with the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
- MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
- MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
- MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads

# MongoDB\Driver\Server::executeReadWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server

### Description

final public MongoDB\Driver\Server::executeReadWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that read and write (e.g. » aggregate). Default values for the `"readConcern"` and `"writeConcern"` options will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  readConcern | MongoDB\Driver\ReadConcern | A read concern to apply to the operation. This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.

### Notes

> Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
- MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
- MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
- MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes

# MongoDB\Driver\Server::executeWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server

### Description

final public MongoDB\Driver\Server::executeWriteCommand(string `$db`, MongoDB\Driver\Command `$command`, ?array `$options` = `null`): MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that write (e.g. » drop). The default value for the `"writeConcern"` option will be inferred from an active transaction (indicated by the `"session"` option), followed by the connection URI.

> Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use MongoDB\Driver\Server::executeBulkWrite() for those operations.

### Parameters

`db` (string)

  The name of the database on which to execute the command.

`command` (MongoDB\Driver\Command)

  The command to execute.

`options`

  options
  Option | Type | Description
  --- | --- | ---
  session | MongoDB\Driver\Session | A session to associate with the operation.
  writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation.

  Warning

  If you are using a `"session"` which has a transaction in progress, you cannot specify a `"readConcern"` or `"writeConcern"` option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

### Return Values

Returns MongoDB\Driver\Cursor on success.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used with an associated transaction in combination with a `"readConcern"` or `"writeConcern"` option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the `"session"` option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

### Changelog

Version | Description
--- | ---
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the `"session"` option is used in combination with an unacknowledged write concern.

### Notes

> Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

### See Also

- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
- MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
- MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
- MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes

# MongoDB\Driver\Server::getHost

(mongodb >=1.0.0)

MongoDB\Driver\Server::getHost — Returns the hostname of this server

### Description

final public MongoDB\Driver\Server::getHost(): string

Returns the hostname of this server.

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Server::getHost() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");
$server = $manager->selectServer();
var_dump($server->getHost());
?>`

The above example will output:

    string(9) "localhost"

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
- MongoDB\Driver\ServerDescription::getHost() - Returns the hostname of this server

# MongoDB\Driver\Server::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\Server::getInfo — Returns an array of information describing this server

### Description

final public MongoDB\Driver\Server::getInfo(): array

Returns an array of information describing the server. This array is derived from the most recent » hello command response obtained through » server monitoring.

> Note:

> When the driver is connected to a load balancer, this method will return the backing server's » hello command response from the initial connection handshake. This is in contrast to other methods (e.g. MongoDB\Driver\Server::getType()), which will return information about the load balancer itself.

### Parameters

This function has no parameters.

### Return Values

Returns an array of information describing this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Server::getInfo() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/');
$rp = new MongoDB\Driver\ReadPreference('primary');
$server = $manager->selectServer($rp);
var_dump($server->getInfo());
?>`

The above example will output something similar to:

    array(23) {
      ["helloOk"]=>
      bool(true)
      ["topologyVersion"]=>
      array(2) {
        ["processId"]=>
        object(MongoDB\BSON\ObjectId)#4 (1) {
          ["oid"]=>
          string(24) "617b6d696a3a89d2f77e6df0"
        }
        ["counter"]=>
        int(6)
      }
      ["hosts"]=>
      array(1) {
        [0]=>
        string(15) "localhost:27017"
      }
      ["setName"]=>
      string(3) "rs0"
      ["setVersion"]=>
      int(1)
      ["ismaster"]=>
      bool(true)
      ["secondary"]=>
      bool(false)
      ["primary"]=>
      string(15) "localhost:27017"
      ["me"]=>
      string(15) "localhost:27017"
      ["electionId"]=>
      object(MongoDB\BSON\ObjectId)#5 (1) {
        ["oid"]=>
        string(24) "7fffffff0000000000000001"
      }
      ["lastWrite"]=>
      array(4) {
        ["opTime"]=>
        array(2) {
          ["ts"]=>
          object(MongoDB\BSON\Timestamp)#6 (2) {
            ["increment"]=>
            string(1) "1"
            ["timestamp"]=>
            string(10) "1635478989"
          }
          ["t"]=>
          int(1)
        }
        ["lastWriteDate"]=>
        object(MongoDB\BSON\UTCDateTime)#7 (1) {
          ["milliseconds"]=>
          string(13) "1635478989000"
        }
        ["majorityOpTime"]=>
        array(2) {
          ["ts"]=>
          object(MongoDB\BSON\Timestamp)#8 (2) {
            ["increment"]=>
            string(1) "1"
            ["timestamp"]=>
            string(10) "1635478989"
          }
          ["t"]=>
          int(1)
        }
        ["majorityWriteDate"]=>
        object(MongoDB\BSON\UTCDateTime)#9 (1) {
          ["milliseconds"]=>
          string(13) "1635478989000"
        }
      }
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(100000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#10 (1) {
        ["milliseconds"]=>
        string(13) "1635478992136"
      }
      ["logicalSessionTimeoutMinutes"]=>
      int(30)
      ["connectionId"]=>
      int(3)
      ["minWireVersion"]=>
      int(0)
      ["maxWireVersion"]=>
      int(13)
      ["readOnly"]=>
      bool(false)
      ["ok"]=>
      float(1)
      ["$clusterTime"]=>
      array(2) {
        ["clusterTime"]=>
        object(MongoDB\BSON\Timestamp)#11 (2) {
          ["increment"]=>
          string(1) "1"
          ["timestamp"]=>
          string(10) "1635478989"
        }
        ["signature"]=>
        array(2) {
          ["hash"]=>
          object(MongoDB\BSON\Binary)#12 (2) {
            ["data"]=>
            string(20) ""
            ["type"]=>
            int(0)
          }
          ["keyId"]=>
          int(0)
        }
      }
      ["operationTime"]=>
      object(MongoDB\BSON\Timestamp)#13 (2) {
        ["increment"]=>
        string(1) "1"
        ["timestamp"]=>
        string(10) "1635478989"
      }
    }

### Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | When the driver is connected to a load balancer, this method returns the backing server's `hello` command response from the initial connection handshake.

### See Also

- MongoDB\Driver\ServerDescription::getHelloResponse() - Returns the server's most recent "hello" response
- » hello command in the MongoDB manual
- » Server Discovery and Monitoring Specification

# MongoDB\Driver\Server::getLatency

(mongodb >=1.0.0)

MongoDB\Driver\Server::getLatency — Returns the latency of this server in milliseconds

### Description

final public MongoDB\Driver\Server::getLatency(): ?integer

Returns the latency of this server in milliseconds. This is the client's measured » round trip time of a `hello` command.

### Parameters

This function has no parameters.

### Return Values

Returns the latency of this server in milliseconds, or `null` if no latency has been measured (e.g. client is connected to a load balancer).

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.11.0 | This method will return `null` if no latency has been measured. In earlier versions, an integer was always returned and an unset value might be reported as `-1`.

### Examples

Example #1 MongoDB\Driver\Server::getLatency() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");
$server = $manager->selectServer();
var_dump($server->getLatency());
?>`

The above example will output something similar to:

    int(592)

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
- MongoDB\Driver\ServerDescription::getRoundTripTime() - Returns the server's round trip time in milliseconds
- » Server Discovery and Monitoring Specification

# MongoDB\Driver\Server::getPort

(mongodb >=1.0.0)

MongoDB\Driver\Server::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Server::getPort(): int

Returns the port on which this server is listening.

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\Server::getPort() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");
$server = $manager->selectServer();
var_dump($server->getPort());
?>`

The above example will output:

    int(27017)

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
- MongoDB\Driver\ServerDescription::getPort() - Returns the port on which this server is listening

# MongoDB\Driver\Server::getServerDescription

(mongodb >=1.13.0)

MongoDB\Driver\Server::getServerDescription — Returns a ServerDescription for this server

### Description

final public MongoDB\Driver\Server::getServerDescription(): MongoDB\Driver\ServerDescription

Returns a MongoDB\Driver\ServerDescription for this server. This is an immutable value object that will describe the server at the time this method is called.

### Parameters

This function has no parameters.

### Return Values

Returns a MongoDB\Driver\ServerDescription for this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Server::getTags

(mongodb >=1.0.0)

MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set

### Description

final public MongoDB\Driver\Server::getTags(): array

Returns an array of » tags used to describe this server in a replica set. The array will contain zero or more string key and value pairs.

### Parameters

This function has no parameters.

### Return Values

Returns an array of tags used to describe this server in a replica set.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

# MongoDB\Driver\Server::getType

(mongodb >=1.0.0)

MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server

### Description

final public MongoDB\Driver\Server::getType(): int

Returns an int denoting the type of this server. The value will correlate with a MongoDB\Driver\Server constant.

### Parameters

This function has no parameters.

### Return Values

Returns an int denoting the type of this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
- MongoDB\Driver\ServerDescription::getType() - Returns a string denoting the type of this server

# MongoDB\Driver\Server::isArbiter

(mongodb >=1.0.0)

MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set

### Description

final public MongoDB\Driver\Server::isArbiter(): bool

Returns whether this server is an » arbiter member of a replica set.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this server is an arbiter member of a replica set, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

# MongoDB\Driver\Server::isHidden

(mongodb >=1.0.0)

MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set

### Description

final public MongoDB\Driver\Server::isHidden(): bool

Returns whether this server is a » hidden member of a replica set.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this server is a hidden member of a replica set, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

# MongoDB\Driver\Server::isPassive

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set

### Description

final public MongoDB\Driver\Server::isPassive(): bool

Returns whether this server is a » passive member of a replica set (i.e. its priority is `0`).

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this server is a passive member of a replica set, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

# MongoDB\Driver\Server::isPrimary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set

### Description

final public MongoDB\Driver\Server::isPrimary(): bool

Returns whether this server is a » primary member of a replica set.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this server is a primary member of a replica set, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

# MongoDB\Driver\Server::isSecondary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set

### Description

final public MongoDB\Driver\Server::isSecondary(): bool

Returns whether this server is a » secondary member of a replica set.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if this server is a secondary member of a replica set, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

## Table of Contents

- MongoDB\Driver\Server::__construct — Create a new Server (not used)
- MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
- MongoDB\Driver\Server::executeBulkWriteCommand — Execute write operations on this server using the bulkWrite command
- MongoDB\Driver\Server::executeCommand — Execute a database command on this server
- MongoDB\Driver\Server::executeQuery — Execute a database query on this server
- MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server
- MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server
- MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server
- MongoDB\Driver\Server::getHost — Returns the hostname of this server
- MongoDB\Driver\Server::getInfo — Returns an array of information describing this server
- MongoDB\Driver\Server::getLatency — Returns the latency of this server in milliseconds
- MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Server::getServerDescription — Returns a ServerDescription for this server
- MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
- MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
- MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
- MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
- MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
- MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
- MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set

# The MongoDB\Driver\ServerDescription class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\ServerDescription class is a value object that represents a server to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Server::getServerDescription() and MongoDB\Driver\Monitoring\ServerChangedEvent methods.

## Class synopsis

final class MongoDB\Driver\ServerDescription {
/* Constants */
const string TYPE_UNKNOWN = "Unknown";
const string TYPE_STANDALONE = "Standalone";
const string TYPE_MONGOS = "Mongos";
const string TYPE_POSSIBLE_PRIMARY = "PossiblePrimary";
const string TYPE_RS_PRIMARY = "RSPrimary";
const string TYPE_RS_SECONDARY = "RSSecondary";
const string TYPE_RS_ARBITER = "RSArbiter";
const string TYPE_RS_OTHER = "RSOther";
const string TYPE_RS_GHOST = "RSGhost";
const string TYPE_LOAD_BALANCER = "LoadBalancer";
/* Methods */
final public getHelloResponse(): array
final public getHost(): string
final public getLastUpdateTime(): int
final public getPort(): int
final public getRoundTripTime(): ?int
final public getType(): string
}

## Predefined Constants

`MongoDB\Driver\ServerDescription::TYPE_UNKNOWN`

  Unknown server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_STANDALONE`

  Standalone server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_MONGOS`

  Mongos server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_POSSIBLE_PRIMARY`

  Replica set possible primary server type, returned by MongoDB\Driver\ServerDescription::getType().

  A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

`MongoDB\Driver\ServerDescription::TYPE_RS_PRIMARY`

  Replica set primary server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_RS_SECONDARY`

  Replica set secondary server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_RS_ARBITER`

  Replica set arbiter server type, returned by MongoDB\Driver\ServerDescription::getType().

`MongoDB\Driver\ServerDescription::TYPE_RS_OTHER`

  Replica set other server type, returned by MongoDB\Driver\ServerDescription::getType().

  Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

`MongoDB\Driver\ServerDescription::TYPE_RS_GHOST`

  Replica set ghost server type, returned by MongoDB\Driver\ServerDescription::getType().

  Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

`MongoDB\Driver\ServerDescription::TYPE_LOAD_BALANCER`

  Load balancer server type, returned by MongoDB\Driver\ServerDescription::getType().

# MongoDB\Driver\ServerDescription::getHelloResponse

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getHelloResponse — Returns the server's most recent "hello" response

### Description

final public MongoDB\Driver\ServerDescription::getHelloResponse(): array

Returns an array of information describing the server. This array is derived from the most recent (at the time the MongoDB\Driver\ServerDescription was constructed) » hello command response obtained through » server monitoring.

> Note:

> When the driver is connected to a load balancer, this method will return an empty array since load balancers are not monitored. This is in contrast to MongoDB\Driver\Server::getInfo(), which would return the backing server's » hello command response from the initial connection handshake.

### Parameters

This function has no parameters.

### Return Values

Returns an array of information describing this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
- » hello command in the MongoDB manual
- » Server Discovery and Monitoring Specification

# MongoDB\Driver\ServerDescription::getHost

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getHost — Returns the hostname of this server

### Description

final public MongoDB\Driver\ServerDescription::getHost(): string

Returns the hostname of this server.

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getHost() - Returns the hostname of this server

# MongoDB\Driver\ServerDescription::getLastUpdateTime

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getLastUpdateTime — Returns the server's last update time in microseconds

### Description

final public MongoDB\Driver\ServerDescription::getLastUpdateTime(): int

Returns the server's last update time in microseconds.

> Note: The returned value is a monotonic timestamp, which starts at an arbitrary point. As such, it is only suitable to compare with other return values from MongoDB\Driver\ServerDescription::getLastUpdateTime().

### Parameters

This function has no parameters.

### Return Values

Returns the server's last update time in microseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\ServerDescription::getPort

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\ServerDescription::getPort(): int

Returns the port on which this server is listening.

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getPort() - Returns the port on which this server is listening

# MongoDB\Driver\ServerDescription::getRoundTripTime

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getRoundTripTime — Returns the server's round trip time in milliseconds

### Description

final public MongoDB\Driver\ServerDescription::getRoundTripTime(): ?int

Returns the server's round trip time in milliseconds. This is the client's measurement of the duration of a » hello command.

### Parameters

This function has no parameters.

### Return Values

Returns the server's round trip time in milliseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getLatency() - Returns the latency of this server in milliseconds

# MongoDB\Driver\ServerDescription::getType

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getType — Returns a string denoting the type of this server

### Description

final public MongoDB\Driver\ServerDescription::getType(): string

Returns a string denoting the type of this server. The value will correlate with a MongoDB\Driver\ServerDescription constant.

### Parameters

This function has no parameters.

### Return Values

Returns a string denoting the type of this server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Server::getType() - Returns an integer denoting the type of this server

## Table of Contents

- MongoDB\Driver\ServerDescription::getHelloResponse — Returns the server's most recent "hello" response
- MongoDB\Driver\ServerDescription::getHost — Returns the hostname of this server
- MongoDB\Driver\ServerDescription::getLastUpdateTime — Returns the server's last update time in microseconds
- MongoDB\Driver\ServerDescription::getPort — Returns the port on which this server is listening
- MongoDB\Driver\ServerDescription::getRoundTripTime — Returns the server's round trip time in milliseconds
- MongoDB\Driver\ServerDescription::getType — Returns a string denoting the type of this server

# The MongoDB\Driver\TopologyDescription class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\TopologyDescription class is a value object that represents a topology to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Monitoring\TopologyChangedEvent methods.

## Class synopsis

final class MongoDB\Driver\TopologyDescription {
/* Constants */
const string TYPE_UNKNOWN = "Unknown";
const string TYPE_SINGLE = "Single";
const string TYPE_SHARDED = "Sharded";
const string TYPE_REPLICA_SET_NO_PRIMARY = "ReplicaSetNoPrimary";
const string TYPE_REPLICA_SET_WITH_PRIMARY = "ReplicaSetWithPrimary";
const string TYPE_LOAD_BALANCED = "LoadBalanced";
/* Methods */
final public getServers(): array
final public getType(): string
final public hasReadableServer(?MongoDB\Driver\ReadPreference `$readPreference` = `null`): bool
final public hasWritableServer(): bool
}

## Predefined Constants

`MongoDB\Driver\TopologyDescription::TYPE_UNKNOWN`

  Unknown topology type, returned by MongoDB\Driver\TopologyDescription::getType().

`MongoDB\Driver\TopologyDescription::TYPE_SINGLE`

  Single server (i.e. direct connection), returned by MongoDB\Driver\TopologyDescription::getType().

`MongoDB\Driver\TopologyDescription::TYPE_SHARDED`

  Sharded cluster, returned by MongoDB\Driver\TopologyDescription::getType().

`MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_NO_PRIMARY`

  Replica set with no primary server, returned by MongoDB\Driver\TopologyDescription::getType().

`MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_WITH_PRIMARY`

  Replica set with a primary server, returned by MongoDB\Driver\TopologyDescription::getType().

`MongoDB\Driver\TopologyDescription::TYPE_LOAD_BALANCED`

  Load balanced topology, returned by MongoDB\Driver\TopologyDescription::getType().

# MongoDB\Driver\TopologyDescription::getServers

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::getServers — Returns the servers in the topology

### Description

final public MongoDB\Driver\TopologyDescription::getServers(): array

Returns an array of MongoDB\Driver\ServerDescription objects corresponding to the known servers in the topology.

### Parameters

This function has no parameters.

### Return Values

Returns an array of MongoDB\Driver\ServerDescription objects corresponding to the known servers in the topology.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\TopologyDescription::getType

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::getType — Returns a string denoting the type of this topology

### Description

final public MongoDB\Driver\TopologyDescription::getType(): string

Returns a string denoting the type of this topology. The value will correlate with a MongoDB\Driver\TopologyDescription constant.

### Parameters

This function has no parameters.

### Return Values

Returns a string denoting the type of this topology.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\TopologyDescription::hasReadableServer

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::hasReadableServer — Returns whether the topology has a readable server

### Description

final public MongoDB\Driver\TopologyDescription::hasReadableServer(?MongoDB\Driver\ReadPreference `$readPreference` = `null`): bool

Returns whether the topology has a readable server or, if `readPreference` is specified, a server matching the specified read preference.

### Parameters

This function has no parameters.

### Return Values

Returns whether the topology has a readable server or, if `readPreference` is specified, a server matching the specified read preference.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\TopologyDescription::hasWritableServer

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::hasWritableServer — Returns whether the topology has a writable server

### Description

final public MongoDB\Driver\TopologyDescription::hasWritableServer(): bool

Returns whether the topology has a writable server.

### Parameters

This function has no parameters.

### Return Values

Returns whether the topology has a writable server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\TopologyDescription::getServers — Returns the servers in the topology
- MongoDB\Driver\TopologyDescription::getType — Returns a string denoting the type of this topology
- MongoDB\Driver\TopologyDescription::hasReadableServer — Returns whether the topology has a readable server
- MongoDB\Driver\TopologyDescription::hasWritableServer — Returns whether the topology has a writable server

# The MongoDB\Driver\WriteConcernError class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\WriteConcernError class encapsulates information about a write concern error and may be returned by MongoDB\Driver\WriteResult::getWriteConcernError().

## Class synopsis

final class MongoDB\Driver\WriteConcernError {
/* Methods */
final public getCode(): int
final public getInfo(): ?object
final public getMessage(): string
}

# MongoDB\Driver\WriteConcernError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code

### Description

final public MongoDB\Driver\WriteConcernError::getCode(): int

### Parameters

This function has no parameters.

### Return Values

Returns the WriteConcernError's error code.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcernError::getCode() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);
try {
$manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getCode());
}
?>`

The above example will output something similar to:

    int(64)

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcernError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError

### Description

final public MongoDB\Driver\WriteConcernError::getInfo(): ?object

### Parameters

This function has no parameters.

### Return Values

Returns the metadata document for the WriteConcernError, or `null` if no metadata is available.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcernError::getInfo() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);
try {
$manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getInfo());
}
?>`

The above example will output something similar to:

    object(stdClass)#1 (1) {
      ["wtimeout"]=>
      bool(true)
    }

### See Also

- » Write Concern reference

# MongoDB\Driver\WriteConcernError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message

### Description

final public MongoDB\Driver\WriteConcernError::getMessage(): string

### Parameters

This function has no parameters.

### Return Values

Returns the WriteConcernError's error message.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteConcernError::getMessage() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);
try {
$manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getMessage());
}
?>`

The above example will output something similar to:

    string(33) "waiting for replication timed out"

### See Also

- » Write Concern reference

## Table of Contents

- MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
- MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError
- MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message

# The MongoDB\Driver\WriteError class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\WriteError class encapsulates information about a write error and may be returned as an array element from MongoDB\Driver\WriteResult::getWriteErrors().

## Class synopsis

final class MongoDB\Driver\WriteError {
/* Methods */
final public getCode(): int
final public getIndex(): int
final public getInfo(): ?object
final public getMessage(): string
}

# MongoDB\Driver\WriteError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code

### Description

final public MongoDB\Driver\WriteError::getCode(): int

### Parameters

This function has no parameters.

### Return Values

Returns the WriteError's error code.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteError::getCode() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getCode());
}
?>`

The above example will output something similar to:

    int(11000)

# MongoDB\Driver\WriteError::getIndex

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError

### Description

final public MongoDB\Driver\WriteError::getIndex(): int

### Parameters

This function has no parameters.

### Return Values

Returns the index of the write operation (from MongoDB\Driver\BulkWrite) corresponding to this WriteError.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteError::getIndex() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getIndex());
}
?>`

The above example will output something similar to:

    int(1)

### See Also

- MongoDB\Driver\BulkWrite

# MongoDB\Driver\WriteError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError

### Description

final public MongoDB\Driver\WriteError::getInfo(): ?object

### Parameters

This function has no parameters.

### Return Values

Returns the metadata document for the WriteError, or `null` if no metadata is available.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\WriteError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message

### Description

final public MongoDB\Driver\WriteError::getMessage(): string

### Parameters

This function has no parameters.

### Return Values

Returns the WriteError's error message.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteError::getMessage() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getMessage());
}
?>`

The above example will output something similar to:

    string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"

## Table of Contents

- MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
- MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
- MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError
- MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message

# The MongoDB\Driver\WriteResult class

(mongodb >=1.0.0)

## Introduction

The MongoDB\Driver\WriteResult class encapsulates information about an executed MongoDB\Driver\BulkWrite and may be returned by MongoDB\Driver\Manager::executeBulkWrite().

## Class synopsis

final class MongoDB\Driver\WriteResult {
/* Methods */
final public getDeletedCount(): int
final public getInsertedCount(): int
final public getMatchedCount(): int
final public getModifiedCount(): int
final public getServer(): MongoDB\Driver\Server
final public getUpsertedCount(): int
final public getUpsertedIds(): array
final public getWriteConcernError(): ?MongoDB\Driver\WriteConcernError
final public getWriteErrors(): array
final public isAcknowledged(): bool
}

# MongoDB\Driver\WriteResult::getDeletedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted

### Description

final public MongoDB\Driver\WriteResult::getDeletedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the number of documents deleted.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method now throws an exception when called for an unacknowledged write instead of returning `null`.

### Examples

Example #1 MongoDB\Driver\WriteResult::getDeletedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getDeletedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getInsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)

### Description

final public MongoDB\Driver\WriteResult::getInsertedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the number of documents inserted (excluding upserts).

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method now throws an exception when called for an unacknowledged write instead of returning `null`.

### Examples

Example #1 MongoDB\Driver\WriteResult::getInsertedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getInsertedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getMatchedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update

### Description

final public MongoDB\Driver\WriteResult::getMatchedCount(): int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the matched count may be greater than the value returned by MongoDB\Driver\WriteResult::getModifiedCount().

### Parameters

This function has no parameters.

### Return Values

Returns the number of documents selected for update.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method now throws an exception when called for an unacknowledged write instead of returning `null`.

### Examples

Example #1 MongoDB\Driver\WriteResult::getMatchedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getMatchedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\WriteResult::getModifiedCount() - Returns the number of existing documents updated
- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getModifiedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated

### Description

final public MongoDB\Driver\WriteResult::getModifiedCount(): int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the modified count may be less than the value returned by MongoDB\Driver\WriteResult::getMatchedCount().

### Parameters

This function has no parameters.

### Return Values

Returns the number of existing documents updated.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method now throws an exception when called for an unacknowledged write instead of returning `null`.

### Examples

Example #1 MongoDB\Driver\WriteResult::getModifiedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getModifiedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\WriteResult::getMatchedCount() - Returns the number of documents selected for update
- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getServer

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result

### Description

final public MongoDB\Driver\WriteResult::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this write result. This is the server that executed the MongoDB\Driver\BulkWrite.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server associated with this write result.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteResult::getServer() example

`<?php
$manager = new MongoDB\Driver\Manager;
$server = $manager->selectServer();
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$result = $server->executeBulkWrite('db.collection', $bulk);
var_dump($result->getServer() == $server);
?>`

The above example will output:

    bool(true)

### See Also

- MongoDB\Driver\Server

# MongoDB\Driver\WriteResult::getUpsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert

### Description

final public MongoDB\Driver\WriteResult::getUpsertedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the number of documents inserted by an upsert.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method now throws an exception when called for an unacknowledged write instead of returning `null`.

### Examples

Example #1 MongoDB\Driver\WriteResult::getUpsertedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getUpsertedCount());
?>`

The above example will output:

    int(2)

### See Also

- MongoDB\Driver\WriteResult::getUpsertedIds() - Returns an array of identifiers for upserted documents
- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getUpsertedIds

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents

### Description

final public MongoDB\Driver\WriteResult::getUpsertedIds(): array

### Parameters

This function has no parameters.

### Return Values

Returns an array of identifiers (i.e. `"_id"` field values) for upserted documents. The array keys will correspond to the index of the write operation (from MongoDB\Driver\BulkWrite) responsible for the upsert.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteResult::getUpsertedIds() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->getUpsertedIds());
?>`

The above example will output something similar to:

    array(2) {
      [2]=>
      object(MongoDB\BSON\ObjectId)#4 (1) {
        ["oid"]=>
        string(24) "580e62a224f2302f191b880b"
      }
      [3]=>
      object(MongoDB\BSON\ObjectId)#5 (1) {
        ["oid"]=>
        string(24) "580e62a224f2302f191b880c"
      }
    }

### See Also

- MongoDB\Driver\WriteResult::getUpsertedCount() - Returns the number of documents inserted by an upsert
- MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\WriteResult::getWriteConcernError

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred

### Description

final public MongoDB\Driver\WriteResult::getWriteConcernError(): ?MongoDB\Driver\WriteConcernError

### Parameters

This function has no parameters.

### Return Values

Returns a MongoDB\Driver\WriteConcernError if a write concern error was encountered during the write operation, and `null` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteResult::getWriteConcernError() example

`<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);
try {
$manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError());
}
?>`

The above example will output something similar to:

    object(MongoDB\Driver\WriteConcernError)#6 (3) {
      ["message"]=>
      string(33) "waiting for replication timed out"
      ["code"]=>
      int(64)
      ["info"]=>
      object(stdClass)#7 (1) {
        ["wtimeout"]=>
        bool(true)
      }
    }

### See Also

- MongoDB\Driver\WriteConcern
- » Write Concern reference

# MongoDB\Driver\WriteResult::getWriteErrors

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred

### Description

final public MongoDB\Driver\WriteResult::getWriteErrors(): array

### Parameters

This function has no parameters.

### Return Values

Returns an array of MongoDB\Driver\WriteError objects for any write errors encountered during the write operation. The array will be empty if no write errors occurred.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteResult::getWriteErrors() with a single error

`<?php
$manager = new MongoDB\Driver\Manager;
/* By default, bulk write operations are executed serially in order and
* execution will stop after the first error.
*/
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(2)
        ["info"]=>
        NULL
      }
    }

Example #2 MongoDB\Driver\WriteResult::getWriteErrors() with multiple errors

`<?php
$manager = new MongoDB\Driver\Manager;
/* The "ordered" option may be used to allow bulk write operations to continue
* executing after the first error is encountered.
*/
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}
?>`

The above example will output something similar to:

    array(2) {
      [0]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(2)
        ["info"]=>
        NULL
      }
      [1]=>
      object(MongoDB\Driver\WriteError)#6 (4) {
        ["message"]=>
        string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 4 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(5)
        ["info"]=>
        NULL
      }
    }

### See Also

- MongoDB\Driver\WriteError

# MongoDB\Driver\WriteResult::isAcknowledged

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

### Description

final public MongoDB\Driver\WriteResult::isAcknowledged(): bool

If the write is acknowledged, other count fields will be available on the MongoDB\Driver\WriteResult object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the write was acknowledged, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\WriteResult::isAcknowledged() with acknowledged write concern

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result->isAcknowledged());
?>`

The above example will output:

    bool(true)

Example #2 MongoDB\Driver\WriteResult::isAcknowledged() with unacknowledged write concern

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(0);
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
var_dump($result->isAcknowledged());
?>`

The above example will output:

    bool(false)

### See Also

- MongoDB\Driver\WriteConcern
- » Write Concern reference

## Table of Contents

- MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
- MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
- MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
- MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
- MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
- MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
- MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
- MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
- MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
- MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

# The MongoDB\Driver\BulkWriteCommandResult class

(mongodb >=2.1.0)

## Introduction

The MongoDB\Driver\BulkWriteCommandResult class encapsulates information about an executed MongoDB\Driver\BulkWriteCommand and is returned by MongoDB\Driver\Manager::executeBulkWriteCommand().

## Class synopsis

final class MongoDB\Driver\BulkWriteCommandResult {
/* Methods */
final public getDeletedCount(): int
final public getDeleteResults(): ?MongoDB\BSON\Document
final public getInsertedCount(): int
final public getInsertResults(): ?MongoDB\BSON\Document
final public getMatchedCount(): int
final public getModifiedCount(): int
final public getUpdateResults(): ?MongoDB\BSON\Document
final public getUpsertedCount(): int
final public isAcknowledged(): bool
}

# MongoDB\Driver\BulkWriteCommandResult::getDeletedCount

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getDeletedCount — Returns the number of documents deleted

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getDeletedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the total number of documents deleted by all operations.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getDeletedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getDeletedCount());
?>`

The above example will output:

    int(3)

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getDeleteResults() - Returns verbose results for successful deletes
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getDeleteResults

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getDeleteResults — Returns verbose results for successful deletes

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getDeleteResults(): ?MongoDB\BSON\Document

### Parameters

This function has no parameters.

### Return Values

Returns a document containing the result of each successful delete operation, or `null` if verbose results were not requested. The document keys will correspond to the index of the write operation from MongoDB\Driver\BulkWriteCommand.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getDeleteResults() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand(['verboseResults' => true]);
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getDeleteResults()->toPHP());
?>`

The above example will output something similar to:

    object(stdClass)#7 (1) {
      ["4"]=>
      object(stdClass)#6 (1) {
        ["deletedCount"]=>
        object(MongoDB\BSON\Int64)#5 (1) {
          ["integer"]=>
          string(1) "3"
        }
      }
    }

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getDeletedCount() - Returns the number of documents deleted
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getInsertedCount

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getInsertedCount — Returns the number of documents inserted

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getInsertedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the total number of documents inserted (excluding upserts) by all operations.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getInsertedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getInsertedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getInsertResults() - Returns verbose results for successful inserts
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getInsertResults

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getInsertResults — Returns verbose results for successful inserts

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getInsertResults(): ?MongoDB\BSON\Document

Since `_id` fields for inserted documents are generated by the extension, the value of `insertedId` in each result will match the return value of MongoDB\Driver\BulkWriteCommand::insertOne() for the corresponding insert operation.

### Parameters

This function has no parameters.

### Return Values

Returns a document containing the result of each successful insert operation, or `null` if verbose results were not requested. The document keys will correspond to the index of the write operation from MongoDB\Driver\BulkWriteCommand.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getInsertResults() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand(['verboseResults' => true]);
$generatedId = $bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($generatedId);
var_dump($result->getInsertResults()->toPHP());
?>`

The above example will output something similar to:

    object(MongoDB\BSON\ObjectId)#3 (1) {
      ["oid"]=>
      string(24) "67f7ee69783dcce702097b41"
    }
    object(stdClass)#8 (1) {
      ["0"]=>
      object(stdClass)#7 (1) {
        ["insertedId"]=>
        object(MongoDB\BSON\ObjectId)#6 (1) {
          ["oid"]=>
          string(24) "67f7ee69783dcce702097b41"
        }
      }
    }

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getInsertedCount() - Returns the number of documents inserted
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged
- MongoDB\Driver\BulkWriteCommand::insertOne() - Add an insertOne operation

# MongoDB\Driver\BulkWriteCommandResult::getMatchedCount

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getMatchedCount — Returns the number of documents selected for update

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getMatchedCount(): int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the matched count may be greater than the value returned by MongoDB\Driver\BulkWriteCommandResult::getModifiedCount().

### Parameters

This function has no parameters.

### Return Values

Returns the total number of documents selected for update by all operations.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getMatchedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getMatchedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getModifiedCount() - Returns the number of existing documents updated
- MongoDB\Driver\BulkWriteCommandResult::getUpdateResults() - Returns verbose results for successful updates
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getModifiedCount

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getModifiedCount — Returns the number of existing documents updated

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getModifiedCount(): int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the modified count may be less than the value returned by MongoDB\Driver\BulkWriteCommandResult::getMatchedCount().

### Parameters

This function has no parameters.

### Return Values

Returns the total number of existing documents updated by all operations.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getModifiedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getModifiedCount());
?>`

The above example will output:

    int(1)

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getMatchedCount() - Returns the number of documents selected for update
- MongoDB\Driver\BulkWriteCommandResult::getUpdateResults() - Returns verbose results for successful updates
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getUpdateResults

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getUpdateResults — Returns verbose results for successful updates

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getUpdateResults(): ?MongoDB\BSON\Document

### Parameters

This function has no parameters.

### Return Values

Returns a document containing the result of each successful update operation, or `null` if verbose results were not requested. The document keys will correspond to the index of the write operation from MongoDB\Driver\BulkWriteCommand.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getUpdateResults() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand(['verboseResults' => true]);
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getUpdateResults()->toPHP());
?>`

The above example will output something similar to:

    object(stdClass)#16 (3) {
      ["1"]=>
      object(stdClass)#7 (2) {
        ["matchedCount"]=>
        object(MongoDB\BSON\Int64)#5 (1) {
          ["integer"]=>
          string(1) "1"
        }
        ["modifiedCount"]=>
        object(MongoDB\BSON\Int64)#6 (1) {
          ["integer"]=>
          string(1) "1"
        }
      }
      ["2"]=>
      object(stdClass)#11 (3) {
        ["matchedCount"]=>
        object(MongoDB\BSON\Int64)#8 (1) {
          ["integer"]=>
          string(1) "1"
        }
        ["modifiedCount"]=>
        object(MongoDB\BSON\Int64)#9 (1) {
          ["integer"]=>
          string(1) "0"
        }
        ["upsertedId"]=>
        object(MongoDB\BSON\ObjectId)#10 (1) {
          ["oid"]=>
          string(24) "67f7eb9b1f198bbcb880d575"
        }
      }
      ["3"]=>
      object(stdClass)#15 (3) {
        ["matchedCount"]=>
        object(MongoDB\BSON\Int64)#12 (1) {
          ["integer"]=>
          string(1) "1"
        }
        ["modifiedCount"]=>
        object(MongoDB\BSON\Int64)#13 (1) {
          ["integer"]=>
          string(1) "0"
        }
        ["upsertedId"]=>
        object(MongoDB\BSON\ObjectId)#14 (1) {
          ["oid"]=>
          string(24) "67f7eb9b1f198bbcb880d576"
        }
      }
    }

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getMatchedCount() - Returns the number of documents selected for update
- MongoDB\Driver\BulkWriteCommandResult::getModifiedCount() - Returns the number of existing documents updated
- MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount() - Returns the number of documents upserted
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount — Returns the number of documents upserted

### Description

final public MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount(): int

### Parameters

This function has no parameters.

### Return Values

Returns the total number of documents upserted by all operations.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the write was not acknowledged.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$bulk->updateOne('db.coll', ['x' => 1], ['$set' => ['y' => 3]]);
$bulk->updateOne('db.coll', ['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->updateOne('db.coll', ['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->deleteMany('db.coll', []);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->getUpsertedCount());
?>`

The above example will output:

    int(2)

### See Also

- MongoDB\Driver\BulkWriteCommandResult::getUpdateResults() - Returns verbose results for successful updates
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() - Returns whether the write was acknowledged

# MongoDB\Driver\BulkWriteCommandResult::isAcknowledged

(mongodb >=2.1.0)

MongoDB\Driver\BulkWriteCommandResult::isAcknowledged — Returns whether the write was acknowledged

### Description

final public MongoDB\Driver\BulkWriteCommandResult::isAcknowledged(): bool

If the write is acknowledged, other fields will be available on the MongoDB\Driver\BulkWriteCommandResult object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the write was acknowledged, and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() with acknowledged write concern

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$result = $manager->executeBulkWriteCommand($bulk);
var_dump($result->isAcknowledged());
?>`

The above example will output:

    bool(true)

Example #2 MongoDB\Driver\BulkWriteCommandResult::isAcknowledged() with unacknowledged write concern

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand(['ordered' => false]);
$bulk->insertOne('db.coll', ['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(0);
$result = $manager->executeBulkWriteCommand($bulk, ['writeConcern' => $writeConcern]);
var_dump($result->isAcknowledged());
?>`

The above example will output:

    bool(false)

### See Also

- MongoDB\Driver\WriteConcern
- » Write Concern reference

## Table of Contents

- MongoDB\Driver\BulkWriteCommandResult::getDeletedCount — Returns the number of documents deleted
- MongoDB\Driver\BulkWriteCommandResult::getDeleteResults — Returns verbose results for successful deletes
- MongoDB\Driver\BulkWriteCommandResult::getInsertedCount — Returns the number of documents inserted
- MongoDB\Driver\BulkWriteCommandResult::getInsertResults — Returns verbose results for successful inserts
- MongoDB\Driver\BulkWriteCommandResult::getMatchedCount — Returns the number of documents selected for update
- MongoDB\Driver\BulkWriteCommandResult::getModifiedCount — Returns the number of existing documents updated
- MongoDB\Driver\BulkWriteCommandResult::getUpdateResults — Returns verbose results for successful updates
- MongoDB\Driver\BulkWriteCommandResult::getUpsertedCount — Returns the number of documents upserted
- MongoDB\Driver\BulkWriteCommandResult::isAcknowledged — Returns whether the write was acknowledged

# MongoDB BSON Classes and Functions

## Table of Contents

- Functions
- MongoDB\BSON\Document
- MongoDB\BSON\PackedArray
- MongoDB\BSON\Iterator
- MongoDB\BSON\Binary
- MongoDB\BSON\VectorType
- MongoDB\BSON\Decimal128
- MongoDB\BSON\Javascript
- MongoDB\BSON\MaxKey
- MongoDB\BSON\MinKey
- MongoDB\BSON\ObjectId
- MongoDB\BSON\Regex
- MongoDB\BSON\Timestamp
- MongoDB\BSON\UTCDateTime
- MongoDB\BSON\Type
- MongoDB\BSON\Persistable
- MongoDB\BSON\Serializable
- MongoDB\BSON\Unserializable
- MongoDB\BSON\BinaryInterface
- MongoDB\BSON\Decimal128Interface
- MongoDB\BSON\JavascriptInterface
- MongoDB\BSON\MaxKeyInterface
- MongoDB\BSON\MinKeyInterface
- MongoDB\BSON\ObjectIdInterface
- MongoDB\BSON\RegexInterface
- MongoDB\BSON\TimestampInterface
- MongoDB\BSON\UTCDateTimeInterface
- MongoDB\BSON\DBPointer
- MongoDB\BSON\Int64
- MongoDB\BSON\Symbol
- MongoDB\BSON\Undefined

# Functions

# MongoDB\BSON\fromJSON

(mongodb >=1.0.0)

MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::fromJSON() instead.

### Description

MongoDB\BSON\fromJSON(string `$json`): string

Converts an » extended JSON string to its BSON representation.

### Parameters

`json` (string)

  JSON value to be converted.

### Return Values

The serialized BSON document as a binary string.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to BSON (e.g. due to a syntax error).

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.

### Examples

Example #1 MongoDB\BSON\fromJSON() example

`<?php
$json = '{ "_id": { "$oid": "563143b280d2387c91807965" } }';
$bson = MongoDB\BSON\fromJSON($json);
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);
?>`

The above example will output:

    object(stdClass)#2 (1) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#1 (1) {
        ["oid"]=>
        string(24) "563143b280d2387c91807965"
      }
    }

### See Also

- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- MongoDB\BSON\toJSON() - Returns the Legacy Extended JSON representation of a BSON value
- » MongoDB Extended JSON
- » MongoDB BSON

# MongoDB\BSON\fromPHP

(mongodb >=1.0.0)

MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::fromPHP() instead.

### Description

MongoDB\BSON\fromPHP(array|object `$value`): string

Serializes a PHP array or object (e.g. document) to its » BSON representation. The returned binary string will describe a BSON document.

### Parameters

`value` (array|object)

  PHP value to be serialized.

### Return Values

The serialized BSON document as a binary string.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\UnexpectedValueException if the PHP value cannot be converted to BSON. Possible reasons include, but are not limited to, encountering an unexpected MongoDB\BSON\Type instance or MongoDB\BSON\Serializable::bsonSerialize() failing to return an array or stdClass.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.

### Examples

Example #1 MongoDB\BSON\fromPHP() example

`<?php
$bson = MongoDB\BSON\fromPHP(['foo' => 1]);
echo bin2hex($bson), "\n";
?>`

The above example will output:

    0e00000010666f6f000100000000cat

### See Also

- MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
- MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
- » MongoDB BSON
- Persisting Data

# MongoDB\BSON\toCanonicalExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::toCanonicalExtendedJSON() instead.

### Description

MongoDB\BSON\toCanonicalExtendedJSON(string `$bson`): string

Converts a BSON string to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

### Parameters

`bson` (string)

  BSON value to be converted.

### Return Values

The converted JSON value.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.

### Examples

Example #1 MongoDB\BSON\toCanonicalExtendedJSON() example

`<?php
$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];
foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toCanonicalExtendedJSON($bson), "\n";
}
?>`

The above example will output:

    { "null" : null }
    { "boolean" : true }
    { "string" : "foo" }
    { "int32" : { "$numberInt" : "123" } }
    { "int64" : { "$numberLong" : "4294967295"} }
    { "double" : { "$numberDouble" : "1.0" } }
    { "nan" : { "$numberDouble" : "NaN" } }
    { "pos_inf" : { "$numberDouble" : "Infinity" } }
    { "neg_inf" : { "$numberDouble" : "-Infinity" } }
    { "array" : [ "foo", "bar" ] }
    { "document" : { "foo" : "bar" } }
    { "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
    { "dec128" : { "$numberDecimal" : "1234.5678" } }
    { "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
    { "date" : { "$date" : { "$numberLong" : "1445990400000" } } }
    { "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
    { "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
    { "code" : { "$code" : "function() { return 1; }" } }
    { "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : { "$numberInt" : "1" } } } }
    { "minkey" : { "$minKey" : 1 } }
    { "maxkey" : { "$maxKey" : 1 } }

### See Also

- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- MongoDB\BSON\Document::toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of the BSON document
- MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » Extended JSON Specification
- » MongoDB BSON

# MongoDB\BSON\toJSON

(mongodb >=1.0.0)

MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::toCanonicalExtendedJSON() or MongoDB\BSON\Document::toRelaxedExtendedJSON() instead.

### Description

MongoDB\BSON\toJSON(string `$bson`): string

Converts a BSON string to its » Legacy Extended JSON representation.

> Note: There exist several JSON formats for representing BSON. This function implements the "strict mode" defined in » MongoDB Extended JSON, which has been superseded by the canonical and relaxed formats defined in the » Extended JSON Specification and implemented by MongoDB\BSON\toCanonicalExtendedJSON() and MongoDB\BSON\toRelaxedExtendedJSON(), respectively.

Warning

» JSON does not support `NAN` and `INF` and MongoDB's Legacy Extended JSON format does not define an alternative representation for these values (» libbson will output `nan` and `inf` literals, which may not be parsed as valid JSON). If you are working with BSON that may contain non-finite numbers, please use MongoDB\BSON\toCanonicalExtendedJSON() or MongoDB\BSON\toRelaxedExtendedJSON().

### Parameters

`bson` (string)

  BSON value to be converted.

### Return Values

The converted JSON value.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.

### Examples

Example #1 MongoDB\BSON\toJSON() example

`<?php
$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];
foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toJSON($bson), "\n";
}
?>`

The above example will output:

    { "null" : null }
    { "boolean" : true }
    { "string" : "foo" }
    { "int32" : 123 }
    { "int64" : 4294967295 }
    { "double" : 1.0 }
    { "nan" : nan }
    { "pos_inf" : inf }
    { "neg_inf" : -inf }
    { "array" : [ "foo", "bar" ] }
    { "document" : { "foo" : "bar" } }
    { "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
    { "dec128" : { "$numberDecimal" : "1234.5678" } }
    { "binary" : { "$binary" : "Zm9v", "$type" : "00" } }
    { "date" : { "$date" : 1445990400000 } }
    { "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
    { "regex" : { "$regex" : "pattern", "$options" : "i" } }
    { "code" : { "$code" : "function() { return 1; }" } }
    { "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
    { "minkey" : { "$minKey" : 1 } }
    { "maxkey" : { "$maxKey" : 1 } }

### See Also

- MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON
- » MongoDB BSON

# MongoDB\BSON\toPHP

(mongodb >=1.0.0)

MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::toPHP() instead.

### Description

MongoDB\BSON\toPHP(string `$bson`, array `$typeMap` = array()): array|object

Unserializes a BSON document (i.e. binary string) to its PHP representation. The `typeMap` paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

### Parameters

`bson` (string)

  BSON value to be unserialized.

`typeMap` (array)

  Type map configuration.

### Return Values

The unserialized PHP value.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.
PECL mongodb 1.4.0 | If the input contains an unsupported, deprecated BSON type, the extension will now no longer log a warning to the debug log, but instead will create an object representing this type.
PECL mongodb 1.3.2 | MongoDB\Driver\Exception\UnexpectedValueException is no longer thrown if the input contains an unsupported, deprecated BSON type. Such types will be ignored (as they were in versions before 1.3.0), although the extension will now log a warning to the debug log (see: mongodb.debug).
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\UnexpectedValueException is thrown if the input contains an unsupported, deprecated BSON type. Previously, such types were ignored.

### Examples

Example #1 MongoDB\BSON\toPHP() example

`<?php
$bson = hex2bin('0e00000010666f6f000100000000');
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);
?>`

The above example will output:

    object(stdClass)#1 (1) {
      ["foo"]=>
      int(1)
    }

### See Also

- MongoDB\BSON\Document::toPHP() - Returns the PHP representation of the BSON document
- MongoDB\BSON\fromPHP() - Returns the BSON representation of a PHP value
- » MongoDB BSON
- Persisting Data

# MongoDB\BSON\toRelaxedExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value

Warning

This function has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\BSON\Document::toRelaxedExtendedJSON() instead.

### Description

MongoDB\BSON\toRelaxedExtendedJSON(string `$bson`): string

Converts a BSON string to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

### Parameters

`bson` (string)

  BSON value to be converted.

### Return Values

The converted JSON value.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This function was removed.

### Examples

Example #1 MongoDB\BSON\toRelaxedExtendedJSON() example

`<?php
$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];
foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toRelaxedExtendedJSON($bson), "\n";
}
?>`

The above example will output:

    { "null" : null }
    { "boolean" : true }
    { "string" : "foo" }
    { "int32" : 123 }
    { "int64" : 4294967295 }
    { "double" : 1.0 }
    { "nan" : { "$numberDouble" : "NaN" } }
    { "pos_inf" : { "$numberDouble" : "Infinity" } }
    { "neg_inf" : { "$numberDouble" : "-Infinity" } }
    { "array" : [ "foo", "bar" ] }
    { "document" : { "foo" : "bar" } }
    { "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
    { "dec128" : { "$numberDecimal" : "1234.5678" } }
    { "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
    { "date" : { "$date" : "2015-10-28T00:00:00Z" } }
    { "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
    { "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
    { "code" : { "$code" : "function() { return 1; }" } }
    { "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
    { "minkey" : { "$minKey" : 1 } }
    { "maxkey" : { "$maxKey" : 1 } }

### See Also

- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- MongoDB\BSON\Document::toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of the BSON document
- MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- » Extended JSON
- » MongoDB BSON

## Table of Contents

- MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
- MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
- MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value
- MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value

# The MongoDB\BSON\Document class

(mongodb >=1.16.0)

## Introduction

Represents a BSON document. This class is used when reading data as raw BSON and cannot be modified.

## Class synopsis

final class MongoDB\BSON\Document implements MongoDB\BSON\Type, ArrayAccess, IteratorAggregate {
/* Methods */
final private __construct()
final static public fromBSON(string `$bson`): MongoDB\BSON\Document
final static public fromJSON(string `$json`): MongoDB\BSON\Document
final static public fromPHP(object|array `$value`): MongoDB\BSON\Document
final public get(string `$key`): mixed
final public getIterator(): MongoDB\BSON\Iterator
final public has(string `$key`): bool
final public offsetExists(mixed `$key`): bool
final public offsetGet(mixed `$key`): mixed
final public offsetSet(mixed `$key`, mixed `$value`): void
final public offsetUnset(mixed `$key`): void
final public toCanonicalExtendedJSON(): string
final public toPHP(?array `$typeMap` = `null`): array|object
final public toRelaxedExtendedJSON(): string
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.17.0 | Implements MongoDB\BSON\Type.

# MongoDB\BSON\Document::__construct

(mongodb >=1.16.0)

MongoDB\BSON\Document::__construct — Construct a new BSON document (unused)

### Description

final private MongoDB\BSON\Document::__construct()

MongoDB\BSON\Document objects are created through static factory methods and cannot be instantiated directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
- MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- » BSON Types

# MongoDB\BSON\Document::fromBSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromBSON — Construct a new document instance from a BSON string

### Description

final static public MongoDB\BSON\Document::fromBSON(string `$bson`): MongoDB\BSON\Document

### Parameters

`bson` (string)

  A string containing a document in BSON format.

### Return Values

Returns a new MongoDB\BSON\Document instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if `bson` is an invalid BSON string or contains more than a single document.

### See Also

- MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- » BSON Types

# MongoDB\BSON\Document::fromJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromJSON — Construct a new document instance from a JSON string

### Description

final static public MongoDB\BSON\Document::fromJSON(string `$json`): MongoDB\BSON\Document

Converts an » extended JSON string to its BSON representation.

### Parameters

`json` (string)

  JSON value to be converted.

### Return Values

Returns a new MongoDB\BSON\Document instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to a BSON document (e.g. due to a syntax error).

### See Also

- MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
- MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
- » MongoDB Extended JSON
- » BSON Types

# MongoDB\BSON\Document::fromPHP

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromPHP — Construct a new document instance from PHP data

### Description

final static public MongoDB\BSON\Document::fromPHP(object|array `$value`): MongoDB\BSON\Document

### Parameters

`value` (object|array)

  A PHP object or array containing the document. When passing an array with numeric keys, the numeric values are converted to strings and used as document keys.

### Return Values

Returns a new MongoDB\BSON\Document instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- » BSON Types

# MongoDB\BSON\Document::get

(mongodb >=1.16.0)

MongoDB\BSON\Document::get — Returns the value of a key in the document

### Description

final public MongoDB\BSON\Document::get(string `$key`): mixed

### Parameters

`key` (string)

  The key to retrieve from the document.

### Return Values

Returns the value associated with the given key. If the key is not present in the document, an exception is thrown.

> Note: When encountering a value encoded as 64-bit integer in the BSON document, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the key is not present in the document.

### See Also

- MongoDB\BSON\Document::has() - Returns whether a key is present in the document
- » BSON Types

# MongoDB\BSON\Document::getIterator

(mongodb >=1.16.0)

MongoDB\BSON\Document::getIterator — Returns an iterator for the BSON document

### Description

final public MongoDB\BSON\Document::getIterator(): MongoDB\BSON\Iterator

### Parameters

This function has no parameters.

### Return Values

Returns a MongoDB\BSON\Iterator instance that can be used to iterate over all keys in the document.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the BSON iterator could not be initialized.

### See Also

- » BSON Types

# MongoDB\BSON\Document::has

(mongodb >=1.16.0)

MongoDB\BSON\Document::has — Returns whether a key is present in the document

### Description

final public MongoDB\BSON\Document::has(string `$key`): bool

### Parameters

`key` (string)

  The key to look for in the document.

### Return Values

Returns `true` if the key is present in the document and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\Document::get() - Returns the value of a key in the document
- » BSON Types

# MongoDB\BSON\Document::offsetExists

(mongodb >=1.17.0)

MongoDB\BSON\Document::offsetExists — Returns whether a key is present in the document

### Description

final public MongoDB\BSON\Document::offsetExists(mixed `$key`): bool

### Parameters

`key`

  The key to look for in the document.

### Return Values

Returns `true` if the key is present in the document and `false` otherwise.

### See Also

- ArrayAccess::offsetExists() - Whether an offset exists
- MongoDB\BSON\Document::has() - Returns whether a key is present in the document

# MongoDB\BSON\Document::offsetGet

(mongodb >=1.17.0)

MongoDB\BSON\Document::offsetGet — Returns the value of a key in the document

### Description

final public MongoDB\BSON\Document::offsetGet(mixed `$key`): mixed

### Parameters

`key`

  The key to retrieve from the document.

### Return Values

Returns the value associated with the given key. If the key is not present in the document, an exception is thrown.

> Note: When encountering a value encoded as 64-bit integer in the BSON document, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the key is not present in the document.

### See Also

- ArrayAccess::offsetGet() - Offset to retrieve
- MongoDB\BSON\Document::get() - Returns the value of a key in the document

# MongoDB\BSON\Document::offsetSet

(mongodb >=1.17.0)

MongoDB\BSON\Document::offsetSet — Implementation of ArrayAccess

### Description

final public MongoDB\BSON\Document::offsetSet(mixed `$key`, mixed `$value`): void

Sets the value at the specified `key` to `value`.

### Parameters

`key`

  The index being set.

`value`

  The new value for the `key`.

### Return Values

No value is returned.

### Errors/Exceptions

- Always throws a MongoDB\Driver\Exception\LogicException.

# MongoDB\BSON\Document::offsetUnset

(mongodb >=1.17.0)

MongoDB\BSON\Document::offsetUnset — Implementation of ArrayAccess

### Description

final public MongoDB\BSON\Document::offsetUnset(mixed `$key`): void

Unsets the value at the specified index.

### Parameters

`key`

  The index being unset.

### Return Values

No value is returned.

### Errors/Exceptions

- Always throws a MongoDB\Driver\Exception\LogicException.

# MongoDB\BSON\Document::toCanonicalExtendedJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON document

### Description

final public MongoDB\BSON\Document::toCanonicalExtendedJSON(): string

Converts the BSON document to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the » Canonical Extended JSON representation of the BSON document.

### Examples

Example #1 MongoDB\BSON\Document::toCanonicalExtendedJSON() example

`<?php
$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0 ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];
foreach ($documents as $document) {
$bson = MongoDB\BSON\Document::fromPHP($document);
echo $bson->toCanonicalExtendedJSON(), "\n";
}
?>`

The above example will output:

    { "null" : null }
    { "boolean" : true }
    { "string" : "foo" }
    { "int32" : { "$numberInt" : "123" } }
    { "int64" : { "$numberLong" : "4294967295"} }
    { "double" : { "$numberDouble" : "1.0" } }
    { "nan" : { "$numberDouble" : "NaN" } }
    { "pos_inf" : { "$numberDouble" : "Infinity" } }
    { "neg_inf" : { "$numberDouble" : "-Infinity" } }
    { "array" : [ "foo", "bar" ] }
    { "document" : { "foo" : "bar" } }
    { "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
    { "dec128" : { "$numberDecimal" : "1234.5678" } }
    { "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
    { "date" : { "$date" : { "$numberLong" : "1445990400000" } } }
    { "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
    { "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
    { "code" : { "$code" : "function() { return 1; }" } }
    { "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : { "$numberInt" : "1" } } } }
    { "minkey" : { "$minKey" : 1 } }
    { "maxkey" : { "$maxKey" : 1 } }

### See Also

- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- MongoDB\BSON\Document::toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of the BSON document
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- » Extended JSON Specification
- » BSON Types

# MongoDB\BSON\Document::toPHP

(mongodb >=1.16.0)

MongoDB\BSON\Document::toPHP — Returns the PHP representation of the BSON document

### Description

final public MongoDB\BSON\Document::toPHP(?array `$typeMap` = `null`): array|object

Unserializes the BSON document to its PHP representation. The `typeMap` paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

### Parameters

`typeMap` (array)

  Type map configuration.

### Return Values

The decoded PHP value.

> Note: When encountering a value encoded as 64-bit integer in the BSON document, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

### See Also

- MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
- » BSON Types

# MongoDB\BSON\Document::toRelaxedExtendedJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON document

### Description

final public MongoDB\BSON\Document::toRelaxedExtendedJSON(): string

Converts the BSON document to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the » Relaxed Extended JSON representation of the BSON document.

### Examples

Example #1 MongoDB\BSON\Document::toRelaxedExtendedJSON() example

`<?php
$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0 ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];
foreach ($documents as $document) {
$bson = MongoDB\BSON\Document::fromPHP($document);
echo $bson->toRelaxedExtendedJSON(), "\n";
}
?>`

The above example will output:

    { "null" : null }
    { "boolean" : true }
    { "string" : "foo" }
    { "int32" : 123 }
    { "int64" : 4294967295 }
    { "double" : 1.0 }
    { "nan" : { "$numberDouble" : "NaN" } }
    { "pos_inf" : { "$numberDouble" : "Infinity" } }
    { "neg_inf" : { "$numberDouble" : "-Infinity" } }
    { "array" : [ "foo", "bar" ] }
    { "document" : { "foo" : "bar" } }
    { "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
    { "dec128" : { "$numberDecimal" : "1234.5678" } }
    { "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
    { "date" : { "$date" : "2015-10-28T00:00:00Z" } }
    { "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
    { "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
    { "code" : { "$code" : "function() { return 1; }" } }
    { "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
    { "minkey" : { "$minKey" : 1 } }
    { "maxkey" : { "$maxKey" : 1 } }

### See Also

- MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
- MongoDB\BSON\Document::toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of the BSON document
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » Extended JSON Specification
- » BSON Types

# MongoDB\BSON\Document::__toString

(mongodb >=1.16.0)

MongoDB\BSON\Document::__toString — Returns the string representation of this BSON Document

### Description

final public MongoDB\BSON\Document::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this document as BSON.

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\Document::__construct — Construct a new BSON document (unused)
- MongoDB\BSON\Document::fromBSON — Construct a new document instance from a BSON string
- MongoDB\BSON\Document::fromJSON — Construct a new document instance from a JSON string
- MongoDB\BSON\Document::fromPHP — Construct a new document instance from PHP data
- MongoDB\BSON\Document::get — Returns the value of a key in the document
- MongoDB\BSON\Document::getIterator — Returns an iterator for the BSON document
- MongoDB\BSON\Document::has — Returns whether a key is present in the document
- MongoDB\BSON\Document::offsetExists — Returns whether a key is present in the document
- MongoDB\BSON\Document::offsetGet — Returns the value of a key in the document
- MongoDB\BSON\Document::offsetSet — Implementation of ArrayAccess
- MongoDB\BSON\Document::offsetUnset — Implementation of ArrayAccess
- MongoDB\BSON\Document::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON document
- MongoDB\BSON\Document::toPHP — Returns the PHP representation of the BSON document
- MongoDB\BSON\Document::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON document
- MongoDB\BSON\Document::__toString — Returns the string representation of this BSON Document

# The MongoDB\BSON\PackedArray class

(mongodb >=1.16.0)

## Introduction

Represents a BSON array. This class is used when reading data as raw BSON and cannot be modified.

## Class synopsis

final class MongoDB\BSON\PackedArray implements MongoDB\BSON\Type, ArrayAccess, IteratorAggregate {
/* Methods */
final private __construct()
final static public fromJSON(string `$json`): MongoDB\BSON\PackedArray
final static public fromPHP(array `$value`): MongoDB\BSON\PackedArray
final public get(int `$key`): mixed
final public getIterator(): MongoDB\BSON\Iterator
final public has(int `$index`): bool
final public offsetExists(mixed `$key`): bool
final public offsetGet(mixed `$key`): mixed
final public offsetSet(mixed `$key`, mixed `$value`): void
final public offsetUnset(mixed `$key`): void
final public toCanonicalExtendedJSON(): string
final public toPHP(?array `$typeMap` = `null`): array|object
final public toRelaxedExtendedJSON(): string
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.17.0 | Implements MongoDB\BSON\Type.
PECL mongodb 1.17.0 | MongoDB\BSON\PackedArray cannot be serialized in contexts where a BSON document is expected. In earlier versions, the BSON array would have been converted to a document.

# MongoDB\BSON\PackedArray::__construct

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::__construct — Construct a new BSON array (unused)

### Description

final private MongoDB\BSON\PackedArray::__construct()

MongoDB\BSON\PackedArray objects are created through static factory methods and cannot be instantiated directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\BSON\PackedArray::fromPHP() - Construct a new BSON array instance from PHP data
- » BSON Types

# MongoDB\BSON\PackedArray::fromJSON

(mongodb >=1.20.0)

MongoDB\BSON\PackedArray::fromJSON — Construct a new BSON array instance from a JSON string

### Description

final static public MongoDB\BSON\PackedArray::fromJSON(string `$json`): MongoDB\BSON\PackedArray

Converts an » extended JSON string to its BSON representation.

### Parameters

`json` (string)

  JSON value to be converted.

### Return Values

Returns a new MongoDB\BSON\PackedArray instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to a BSON array (e.g. due to a syntax error).

### Examples

Example #1 MongoDB\BSON\PackedArray::fromJSON() example

`<?php
$json = '[ "foo", { "$numberInt" : "123" }, { "$numberLong" : "4294967295" }, { "$oid" : "56315a7c6118fd1b920270b1" } ]';
$packedArray = MongoDB\BSON\PackedArray::fromJSON($json);
var_dump($packedArray);
?>`

The above example will output:

    object(MongoDB\BSON\PackedArray)#1 (2) {
      ["data"]=>
      string(68) "MQAAAAIwAAQAAABmb28AEDEAewAAABIyAP////8AAAAABzMAVjFafGEY/RuSAnCxAA=="
      ["value"]=>
      array(4) {
        [0]=>
        string(3) "foo"
        [1]=>
        int(123)
        [2]=>
        int(4294967295)
        [3]=>
        object(MongoDB\BSON\ObjectId)#2 (1) {
          ["oid"]=>
          string(24) "56315a7c6118fd1b920270b1"
        }
      }
    }

### See Also

- MongoDB\BSON\PackedArray::fromPHP() - Construct a new BSON array instance from PHP data
- » MongoDB Extended JSON
- » BSON Types

# MongoDB\BSON\PackedArray::fromPHP

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::fromPHP — Construct a new BSON array instance from PHP data

### Description

final static public MongoDB\BSON\PackedArray::fromPHP(array `$value`): MongoDB\BSON\PackedArray

### Parameters

`value` (array)

  The PHP array to convert to a BSON array. The array must be a list (i.e. have sequential numeric keys starting with `0`).

### Return Values

Returns a new MongoDB\BSON\PackedArray instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the given array is not a list (i.e. has sequential numeric keys starting with `0`).

### See Also

- » BSON Types

# MongoDB\BSON\PackedArray::get

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::get — Returns the value of an index in the array

### Description

final public MongoDB\BSON\PackedArray::get(int `$key`): mixed

### Parameters

`key` (int)

  The index to retrieve from the array.

### Return Values

Returns the value associated with the given index. If the index is not present in the array, an exception is thrown.

> Note: When encountering a value encoded as 64-bit integer in the BSON array, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the index is not present in the array.

### See Also

- MongoDB\BSON\PackedArray::has() - Returns whether a index is present in the array
- » BSON Types

# MongoDB\BSON\PackedArray::getIterator

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::getIterator — Returns an iterator for the BSON array

### Description

final public MongoDB\BSON\PackedArray::getIterator(): MongoDB\BSON\Iterator

### Parameters

This function has no parameters.

### Return Values

Returns a MongoDB\BSON\Iterator instance that can be used to iterate over all indexes in the array.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\UnexpectedValueException if the BSON iterator could not be initialized.

### See Also

- » BSON Types

# MongoDB\BSON\PackedArray::has

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::has — Returns whether a index is present in the array

### Description

final public MongoDB\BSON\PackedArray::has(int `$index`): bool

### Parameters

`index` (int)

  The index to look for in the array.

### Return Values

Returns `true` if the index is present in the array and `false` otherwise.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\PackedArray::get() - Returns the value of an index in the array
- » BSON Types

# MongoDB\BSON\PackedArray::offsetExists

(mongodb >=1.17.0)

MongoDB\BSON\PackedArray::offsetExists — Returns whether a index is present in the array

### Description

final public MongoDB\BSON\PackedArray::offsetExists(mixed `$key`): bool

### Parameters

`key`

  The index to look for in the array.

### Return Values

Returns `true` if the index is present in the array and `false` otherwise.

### See Also

- ArrayAccess::offsetExists() - Whether an offset exists
- MongoDB\BSON\PackedArray::has() - Returns whether a index is present in the array

# MongoDB\BSON\PackedArray::offsetGet

(mongodb >=1.17.0)

MongoDB\BSON\PackedArray::offsetGet — Returns the value of an index in the array

### Description

final public MongoDB\BSON\PackedArray::offsetGet(mixed `$key`): mixed

### Parameters

`key`

  The index to retrieve from the array. Only int is supported.

### Return Values

Returns the value associated with the given index. If the index is not present in the array, an exception is thrown.

> Note: When encountering a value encoded as 64-bit integer in the BSON array, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\RuntimeException if the index is not present in the array.

### See Also

- ArrayAccess::offsetGet() - Offset to retrieve
- MongoDB\BSON\PackedArray::get() - Returns the value of an index in the array

# MongoDB\BSON\PackedArray::offsetSet

(mongodb >=1.17.0)

MongoDB\BSON\PackedArray::offsetSet — Implementation of ArrayAccess

### Description

final public MongoDB\BSON\PackedArray::offsetSet(mixed `$key`, mixed `$value`): void

Sets the value at the specified `key` to `value`.

### Parameters

`key`

  The index being set.

`value`

  The new value for the `key`.

### Return Values

No value is returned.

### Errors/Exceptions

- Always throws a MongoDB\Driver\Exception\LogicException.

# MongoDB\BSON\PackedArray::offsetUnset

(mongodb >=1.17.0)

MongoDB\BSON\PackedArray::offsetUnset — Implementation of ArrayAccess

### Description

final public MongoDB\BSON\PackedArray::offsetUnset(mixed `$key`): void

Unsets the value at the specified index.

### Parameters

`key`

  The index being unset.

### Return Values

No value is returned.

### Errors/Exceptions

- Always throws a MongoDB\Driver\Exception\LogicException.

# MongoDB\BSON\PackedArray::toCanonicalExtendedJSON

(mongodb >=1.20.0)

MongoDB\BSON\PackedArray::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON array

### Description

final public MongoDB\BSON\PackedArray::toCanonicalExtendedJSON(): string

Converts the BSON array to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the » Canonical Extended JSON representation of the BSON array.

### Examples

Example #1 MongoDB\BSON\PackedArray::toCanonicalExtendedJSON() example

`<?php
$array = [
'foo',
123,
4294967295,
new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1'),
];
$packedArray = MongoDB\BSON\PackedArray::fromPHP($array);
echo $packedArray->toCanonicalExtendedJSON(), "\n";
?>`

The above example will output:

    [ "foo", { "$numberInt" : "123" }, { "$numberLong" : "4294967295" }, { "$oid" : "56315a7c6118fd1b920270b1" } ]

### See Also

- MongoDB\BSON\PackedArray::fromJSON() - Construct a new BSON array instance from a JSON string
- MongoDB\BSON\PackedArray::toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of the BSON array
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- » Extended JSON Specification
- » BSON Types

# MongoDB\BSON\PackedArray::toPHP

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::toPHP — Returns the PHP representation of the BSON array

### Description

final public MongoDB\BSON\PackedArray::toPHP(?array `$typeMap` = `null`): array|object

### Parameters

`typeMap` (array)

  Type map configuration.

### Return Values

The decoded PHP value.

> Note: When encountering a value encoded as 64-bit integer in the BSON array, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

### See Also

- MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
- » BSON Types

# MongoDB\BSON\PackedArray::toRelaxedExtendedJSON

(mongodb >=1.20.0)

MongoDB\BSON\PackedArray::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON array

### Description

final public MongoDB\BSON\PackedArray::toRelaxedExtendedJSON(): string

Converts the BSON array to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the » Relaxed Extended JSON representation of the BSON array.

### Examples

Example #1 MongoDB\BSON\PackedArray::toRelaxedExtendedJSON() example

`<?php
$array = [
'foo',
123,
4294967295,
new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1'),
];
$packedArray = MongoDB\BSON\PackedArray::fromPHP($array);
echo $packedArray->toRelaxedExtendedJSON(), "\n";
?>`

The above example will output:

    [ "foo", 123, 4294967295, { "$oid" : "56315a7c6118fd1b920270b1" } ]

### See Also

- MongoDB\BSON\PackedArray::fromJSON() - Construct a new BSON array instance from a JSON string
- MongoDB\BSON\PackedArray::toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of the BSON array
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » Extended JSON Specification
- » BSON Types

# MongoDB\BSON\PackedArray::__toString

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::__toString — Returns the string representation of this BSON array

### Description

final public MongoDB\BSON\PackedArray::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this array as BSON.

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\PackedArray::__construct — Construct a new BSON array (unused)
- MongoDB\BSON\PackedArray::fromJSON — Construct a new BSON array instance from a JSON string
- MongoDB\BSON\PackedArray::fromPHP — Construct a new BSON array instance from PHP data
- MongoDB\BSON\PackedArray::get — Returns the value of an index in the array
- MongoDB\BSON\PackedArray::getIterator — Returns an iterator for the BSON array
- MongoDB\BSON\PackedArray::has — Returns whether a index is present in the array
- MongoDB\BSON\PackedArray::offsetExists — Returns whether a index is present in the array
- MongoDB\BSON\PackedArray::offsetGet — Returns the value of an index in the array
- MongoDB\BSON\PackedArray::offsetSet — Implementation of ArrayAccess
- MongoDB\BSON\PackedArray::offsetUnset — Implementation of ArrayAccess
- MongoDB\BSON\PackedArray::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON array
- MongoDB\BSON\PackedArray::toPHP — Returns the PHP representation of the BSON array
- MongoDB\BSON\PackedArray::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON array
- MongoDB\BSON\PackedArray::__toString — Returns the string representation of this BSON array

# The MongoDB\BSON\Iterator class

(mongodb >=1.16.0)

## Introduction

Iterator used to iterate a BSON document or array.

## Class synopsis

final class MongoDB\BSON\Iterator implements Iterator {
/* Methods */
final private __construct()
public current(): mixed
public key(): string|int
public next(): void
public rewind(): void
public valid(): bool
}

# MongoDB\BSON\Iterator::__construct

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::__construct — Construct a new BSON iterator (unused)

### Description

final private MongoDB\BSON\Iterator::__construct()

MongoDB\BSON\Iterator objects are created by calling MongoDB\BSON\Document::getIterator() or MongoDB\BSON\PackedArray::getIterator() and cannot be instantiated directly.

### Parameters

This function has no parameters.

### See Also

- MongoDB\BSON\Document::getIterator() - Returns an iterator for the BSON document
- MongoDB\BSON\PackedArray::getIterator() - Returns an iterator for the BSON array
- » BSON Types

# MongoDB\BSON\Iterator::current

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::current — Returns the current element

### Description

public MongoDB\BSON\Iterator::current(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns the value of the current element.

> Note: When encountering a value encoded as 64-bit integer in the BSON structure, the return value of this method will be a MongoDB\BSON\Int64 instance.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the iterator is not valid.

### See Also

- Iterator::current() - Return the current element

# MongoDB\BSON\Iterator::key

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::key — Returns the key of the current element

### Description

public MongoDB\BSON\Iterator::key(): string|int

### Parameters

This function has no parameters.

### Return Values

Returns the key of the current element. When iterating a BSON document, the key will always be a string. When iterating a BSON array, the key will be an int.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\LogicException if the iterator is not valid.

### See Also

- Iterator::key() - Return the key of the current element

# MongoDB\BSON\Iterator::next

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::next — Advances the iterator to next element

### Description

public MongoDB\BSON\Iterator::next(): void

### Parameters

This function has no parameters.

### See Also

- Iterator::next() - Move forward to next element

# MongoDB\BSON\Iterator::rewind

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::rewind — Rewinds the Iterator to the first element

### Description

public MongoDB\BSON\Iterator::rewind(): void

### Parameters

This function has no parameters.

### See Also

- Iterator::rewind() - Rewind the Iterator to the first element

# MongoDB\BSON\Iterator::valid

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::valid — Checks if current position is valid

### Description

public MongoDB\BSON\Iterator::valid(): bool

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the current iterator position is valid, `false` otherwise.

### See Also

- Iterator::valid() - Checks if current position is valid

## Table of Contents

- MongoDB\BSON\Iterator::__construct — Construct a new BSON iterator (unused)
- MongoDB\BSON\Iterator::current — Returns the current element
- MongoDB\BSON\Iterator::key — Returns the key of the current element
- MongoDB\BSON\Iterator::next — Advances the iterator to next element
- MongoDB\BSON\Iterator::rewind — Rewinds the Iterator to the first element
- MongoDB\BSON\Iterator::valid — Checks if current position is valid

# The MongoDB\BSON\Binary class

(mongodb >=1.0.0)

## Introduction

BSON type for binary data (i.e. array of bytes). Binary values also have a subtype, which is used to indicate what kind of data is in the byte array. Subtypes from zero to 127 are predefined or reserved. Subtypes from 128-255 are user-defined.

## Class synopsis

final class MongoDB\BSON\Binary implements MongoDB\BSON\BinaryInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Constants */
const int TYPE_GENERIC = 0;
const int TYPE_FUNCTION = 1;
const int TYPE_OLD_BINARY = 2;
const int TYPE_OLD_UUID = 3;
const int TYPE_UUID = 4;
const int TYPE_MD5 = 5;
const int TYPE_ENCRYPTED = 6;
const int TYPE_COLUMN = 7;
const int TYPE_SENSITIVE = 8;
const int TYPE_VECTOR = 9;
const int TYPE_USER_DEFINED = 128;
/* Methods */
final public __construct(string `$data`, int `$type` = MongoDB\BSON\Binary::TYPE_GENERIC)
final public static fromVector(array `$vector`, MongoDB\BSON\VectorType `$vectorType`): MongoDB\BSON\Binary
final public getData(): string
final public getType(): int
final public getVectorType(): MongoDB\BSON\VectorType
final public jsonSerialize(): mixed
final public toArray(): array
final public __toString(): string
}

## Predefined Constants

`MongoDB\BSON\Binary::TYPE_GENERIC`

  Generic binary data.

`MongoDB\BSON\Binary::TYPE_FUNCTION`

  Function.

`MongoDB\BSON\Binary::TYPE_OLD_BINARY`

  Generic binary data (deprecated in favor of `MongoDB\BSON\Binary::TYPE_GENERIC`).

`MongoDB\BSON\Binary::TYPE_OLD_UUID`

  Universally unique identifier (deprecated in favor of `MongoDB\BSON\Binary::TYPE_UUID`). When using this type, the Binary's data should be 16 bytes in length.

  Historically, other drivers encoded values with this type based on their language conventions (e.g. varying endianness), which makes it non-portable. The PHP extension applies no special handling for encoding or decoding data with this type.

`MongoDB\BSON\Binary::TYPE_UUID`

  Universally unique identifier. When using this type, the Binary's data should be 16 bytes in length and encoded according to » RFC 4122.

`MongoDB\BSON\Binary::TYPE_MD5`

  MD5 hash. When using this type, the Binary's data should be 16 bytes in length.

`MongoDB\BSON\Binary::TYPE_ENCRYPTED`

  Encrypted value. This subtype is used for client-side encryption.

`MongoDB\BSON\Binary::TYPE_COLUMN`

  Column data. This subtype is used for time-series collections.

`MongoDB\BSON\Binary::TYPE_SENSITIVE`

  Sensitive data. This subtype is used for sensitive data that should be excluded from server-side logging when possible.

`MongoDB\BSON\Binary::TYPE_VECTOR`

  Vector data. This subtype is used to efficiently store vector data for use with MongoDB's vector search.

`MongoDB\BSON\Binary::TYPE_USER_DEFINED`

  User-defined type. While types between 0 and 127 are predefined or reserved, types between 128 and 255 are user-defined and may be used for anything.

## Changelog

Version | Description
--- | ---
PECL mongodb 2.2.0 | Added `MongoDB\BSON\Binary::TYPE_VECTOR`, as well as the MongoDB\BSON\Binary::fromVector(), MongoDB\BSON\Binary::getVectorType(), and MongoDB\BSON\Binary::toArray() functions.
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.17.0 | Added `MongoDB\BSON\Binary::TYPE_SENSITIVE`.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+. Added `MongoDB\BSON\Binary::TYPE_COLUMN`.
PECL mongodb 1.7.0 | Added `MongoDB\BSON\Binary::TYPE_ENCRYPTED`.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\BinaryInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\Binary::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Binary::__construct — Construct a new Binary

### Description

final public MongoDB\BSON\Binary::__construct(string `$data`, int `$type` = MongoDB\BSON\Binary::TYPE_GENERIC)

### Parameters

`data` (string)

  Binary data.

`type` (int)

  Unsigned 8-bit integer denoting the data's type. Defaults to `MongoDB\BSON\Binary::TYPE_GENERIC` if not specified.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `type` is not an unsigned 8-bit integer.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `type` is `MongoDB\BSON\Binary::TYPE_UUID` or `MongoDB\BSON\Binary::TYPE_OLD_UUID` and `data` is not exactly 16 bytes in length.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.15.0 | The `type` parameter defaults to `MongoDB\BSON\Binary::TYPE_GENERIC` if not specified.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if `type` is `MongoDB\BSON\Binary::TYPE_UUID` or `MongoDB\BSON\Binary::TYPE_OLD_UUID` and `data` is not exactly 16 bytes in length.
PECL mongodb 1.1.3 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if `type` is not an unsigned 8-bit integer.

### Examples

Example #1 MongoDB\BSON\Binary::__construct() example

`<?php
$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary);
?>`

The above example will output:

    object(MongoDB\BSON\Binary)#1 (2) {
      ["data"]=>
      string(3) "foo"
      ["type"]=>
      int(0)
    }

### See Also

- » BSON Types

# MongoDB\BSON\Binary::fromVector

(mongodb >=2.2.0)

MongoDB\BSON\Binary::fromVector — Creates a new binary with subtype `MongoDB\BSON\Binary::SUBTYPE_VECTOR` from the given array and vector type

### Description

final public static MongoDB\BSON\Binary::fromVector(array `$vector`, MongoDB\BSON\VectorType `$vectorType`): MongoDB\BSON\Binary

### Parameters

`vector` (array)

  An array of values representing the vector data. The type of each value must match the type indicated by the `vectorType` parameter:

  - for `MongoDB\BSON\VectorType::Float32`, each value must be a float
  - for `MongoDB\BSON\VectorType::Int8`, each value must be an 8-bit int, i.e. from `-127` to `128`
  - for `MongoDB\BSON\VectorType::PackedBit`, each value must be a bool or 1-bit int, i.e. `0` or `1`
`vectorType` (MongoDB\BSON\VectorType)

  The vector data type.

### Return Values

Returns a new Binary with subtype `MongoDB\BSON\Binary::SUBTYPE_VECTOR`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\Binary::toArray() - Returns the vector as an array for a Binary with subtype MongoDB\BSON\Binary::SUBTYPE_VECTOR
- MongoDB\BSON\Binary::getVectorType() - Returns the data type for a Binary with the vector subtype
- MongoDB\BSON\VectorType
- » BSON Types

# MongoDB\BSON\Binary::getData

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getData — Returns the Binary's data

### Description

final public MongoDB\BSON\Binary::getData(): string

### Parameters

This function has no parameters.

### Return Values

Returns the Binary's data.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Binary::getData() example

`<?php
$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getData());
?>`

The above example will output:

    string(3) "foo"

### See Also

- » BSON Types

# MongoDB\BSON\Binary::getType

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getType — Returns the Binary's type

### Description

final public MongoDB\BSON\Binary::getType(): int

### Parameters

This function has no parameters.

### Return Values

Returns the Binary's type.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Binary::getType() example

`<?php
$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getType());
?>`

The above example will output:

    int(0)

### See Also

- » BSON Types

# MongoDB\BSON\Binary::getVectorType

(mongodb >=2.2.0)

MongoDB\BSON\Binary::getVectorType — Returns the data type for a Binary with the vector subtype

### Description

final public MongoDB\BSON\Binary::getVectorType(): MongoDB\BSON\VectorType

### Parameters

This function has no parameters.

### Return Values

Returns the data type of the Binary vector.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the subtype is not `MongoDB\BSON\Binary::SUBTYPE_VECTOR`.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- » BSON Types
- MongoDB\BSON\VectorType

# MongoDB\BSON\Binary::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Binary::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Binary.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Binary::toArray

(mongodb >=2.2.0)

MongoDB\BSON\Binary::toArray — Returns the vector as an array for a Binary with subtype `MongoDB\BSON\Binary::SUBTYPE_VECTOR`

### Description

final public MongoDB\BSON\Binary::toArray(): array

### Parameters

This function has no parameters.

### Return Values

Returns an array containing the vector data.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\LogicException if the subtype is not `MongoDB\BSON\Binary::SUBTYPE_VECTOR`.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\BSON\Binary::fromVector() - Creates a new binary with subtype MongoDB\BSON\Binary::SUBTYPE_VECTOR from the given array and vector type
- » BSON Types

# MongoDB\BSON\Binary::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Binary::__toString — Returns the Binary's data

### Description

final public MongoDB\BSON\Binary::__toString(): string

This method is an alias of: MongoDB\BSON\Binary::getData().

### Parameters

This function has no parameters.

### Return Values

Returns the Binary's data.

### Examples

Example #1 MongoDB\BSON\Binary::__toString() example

`<?php
var_dump((string) new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC));
?>`

The above example will output:

    string(3) "foo"

### See Also

- MongoDB\BSON\Binary::getData() - Returns the Binary's data
- » BSON Types

## Table of Contents

- MongoDB\BSON\Binary::__construct — Construct a new Binary
- MongoDB\BSON\Binary::fromVector — Creates a new binary with subtype MongoDB\BSON\Binary::SUBTYPE_VECTOR from the given array and vector type
- MongoDB\BSON\Binary::getData — Returns the Binary's data
- MongoDB\BSON\Binary::getType — Returns the Binary's type
- MongoDB\BSON\Binary::getVectorType — Returns the data type for a Binary with the vector subtype
- MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Binary::toArray — Returns the vector as an array for a Binary with subtype MongoDB\BSON\Binary::SUBTYPE_VECTOR
- MongoDB\BSON\Binary::__toString — Returns the Binary's data

# The MongoDB\BSON\VectorType enum

(mongodb >=2.2.0)

## Introduction

The MongoDB\BSON\VectorType enum is used to specify the type of vector data stored in a MongoDB\BSON\Binary with subtype `MongoDB\BSON\Binary::TYPE_VECTOR`.

## Enum synopsis

enum MongoDB\BSON\VectorType
{
case Float32 ; // Each element in the vector is a 32-bit floating point value.
case Int8 ; // Each element in the vector is an 8-bit integer value.
case PackedBit ; // Each element in the vector is a 1-bit value. When creating vectors of this type, you may pass either bool or 1-bit int values, i.e. `0` or `1`.
}

# The MongoDB\BSON\Decimal128 class

(mongodb >=1.2.0)

## Introduction

BSON type for the » Decimal128 floating-point format, which supports numbers with up to 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144.

Unlike the double BSON type (i.e. float in PHP), which only stores an approximation of the decimal values, the decimal data type stores the exact value. For example, `MongoDB\BSON\Decimal128('9.99')` has a precise value of 9.99 where as a double 9.99 would have an approximate value of 9.9900000000000002131628….

> Note: MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

## Class synopsis

final class MongoDB\BSON\Decimal128 implements MongoDB\BSON\Decimal128Interface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(string `$value`)
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\Decimal128Interface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\Decimal128::__construct

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128

### Description

final public MongoDB\BSON\Decimal128::__construct(string `$value`)

> Note: MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

### Parameters

`value` (string)

  A decimal string.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `value` is not a valid decimal string.

### Examples

Example #1 MongoDB\BSON\Decimal128::__construct() example

`<?php
var_dump(new MongoDB\BSON\Decimal128(1234.5678));
var_dump(new MongoDB\BSON\Decimal128(NAN));
var_dump(new MongoDB\BSON\Decimal128(INF));
?>`

The above example will output something similar to:

    object(MongoDB\BSON\Decimal128)#1 (1) {
      ["dec"]=>
      string(9) "1234.5678"
    }
    object(MongoDB\BSON\Decimal128)#1 (1) {
      ["dec"]=>
      string(3) "NaN"
    }
    object(MongoDB\BSON\Decimal128)#1 (1) {
      ["dec"]=>
      string(8) "Infinity"
    }

### See Also

- » Decimal128 floating-point format
- » BSON Types

# MongoDB\BSON\Decimal128::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Decimal128::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Decimal128.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Decimal128::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128

### Description

final public MongoDB\BSON\Decimal128::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Decimal128.

### Examples

Example #1 MongoDB\BSON\Decimal128::__toString() example

`<?php
var_dump((string) new MongoDB\BSON\Decimal128(1234.5678));
var_dump((string) new MongoDB\BSON\Decimal128(NAN));
var_dump((string) new MongoDB\BSON\Decimal128(INF));
?>`

The above example will output something similar to:

    string(9) "1234.5678"
    string(3) "NaN"
    string(8) "Infinity"

### See Also

- » Decimal128 floating-point format
- » BSON Types

## Table of Contents

- MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128
- MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128

# The MongoDB\BSON\Javascript class

(mongodb >=1.0.0)

## Introduction

BSON type for Javascript code. An optional scope document may be specified that maps identifiers to values and defines the scope in which the code should be evaluated by the server.

> Note: This BSON type is mainly used when executing database commands that take a Javascript function as a parameter, such as » mapReduce.

## Class synopsis

final class MongoDB\BSON\Javascript implements MongoDB\BSON\JavascriptInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(string `$code`, array|object|null `$scope` = `null`)
final public getCode(): string
final public getScope(): ?object
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\JavascriptInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\Javascript::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Javascript::__construct — Construct a new Javascript

### Description

final public MongoDB\BSON\Javascript::__construct(string `$code`, array|object|null `$scope` = `null`)

### Parameters

`code` (string)

  Javascript code.

`scope` (array|object)

  Javascript scope.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `code` contains null bytes.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.2.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if `code` contains null bytes. Previously, values would be truncated at the first null byte.

### Examples

Example #1 MongoDB\BSON\Javascript::__construct() example

`<?php
$code = new MongoDB\BSON\Javascript('function() { return 1; }');
var_dump($code);
$codews = new MongoDB\BSON\Javascript('function() { return foo; }', ['foo' => 'bar']);
var_dump($codews);
?>`

The above example will output:

    object(MongoDB\BSON\Javascript)#1 (2) {
      ["javascript"]=>
      string(24) "function() { return 1; }"
      ["scope"]=>
      object(stdClass)#2 (0) {
      }
    }
    object(MongoDB\BSON\Javascript)#2 (2) {
      ["javascript"]=>
      string(26) "function() { return foo; }"
      ["scope"]=>
      object(stdClass)#1 (1) {
        ["foo"]=>
        string(3) "bar"
      }
    }

### See Also

- » BSON Types

# MongoDB\BSON\Javascript::getCode

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getCode — Returns the Javascript's code

### Description

final public MongoDB\BSON\Javascript::getCode(): string

### Parameters

This function has no parameters.

### Return Values

Returns the Javascript's code.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Javascript::getCode() example

`<?php
$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getCode());
?>`

The above example will output:

    string(33) "function foo(bar) { return bar; }"

### See Also

- » BSON Types

# MongoDB\BSON\Javascript::getScope

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document

### Description

final public MongoDB\BSON\Javascript::getScope(): ?object

### Parameters

This function has no parameters.

### Return Values

Returns the Javascript's scope document, or `null` if the is no scope.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Javascript::getScope() example

`<?php
$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getScope());
$js = new MongoDB\BSON\Javascript('function foo() { return foo; }', ['foo' => 42]);
var_dump($js->getScope());
?>`

The above example will output:

    NULL
    object(stdClass)#1 (1) {
      ["foo"]=>
      int(42)
    }

### See Also

- » BSON Types

# MongoDB\BSON\Javascript::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Javascript::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Javascript.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Javascript::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::__toString — Returns the Javascript's code

### Description

final public MongoDB\BSON\Javascript::__toString(): string

This method is an alias of: MongoDB\BSON\Javascript::getCode().

### Parameters

This function has no parameters.

### Return Values

Returns the Javascript's code.

### Examples

Example #1 MongoDB\BSON\Javascript::__toString() example

`<?php
var_dump((string) new MongoDB\BSON\Javascript('function foo(bar) { return bar; }'));
?>`

The above example will output:

    string(33) "function foo(bar) { return bar; }"

### See Also

- MongoDB\BSON\Javascript::getCode() - Returns the Javascript's code
- » BSON Types

## Table of Contents

- MongoDB\BSON\Javascript::__construct — Construct a new Javascript
- MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
- MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
- MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Javascript::__toString — Returns the Javascript's code

# The MongoDB\BSON\MaxKey class

(mongodb >=1.0.0)

## Introduction

Special BSON type which compares higher than all other possible BSON element values.

> Note: This is an internal MongoDB type used for indexing and sharding.

## Class synopsis

final class MongoDB\BSON\MaxKey implements MongoDB\BSON\MaxKeyInterface, MongoDB\BSON\Type, JsonSerializable {
/* Methods */
final public __construct()
final public jsonSerialize(): mixed
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\MaxKeyInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\MaxKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey

### Description

final public MongoDB\BSON\MaxKey::__construct()

### Parameters

This function has no parameters.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\MaxKey::__construct() example

`<?php
var_dump(new MongoDB\BSON\MaxKey());
?>`

The above example will output:

    object(MongoDB\BSON\MaxKey)#1 (0) {
    }

### See Also

- » BSON Types

# MongoDB\BSON\MaxKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\MaxKey::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\MaxKey.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

## Table of Contents

- MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
- MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON

# The MongoDB\BSON\MinKey class

(mongodb >=1.0.0)

## Introduction

Special BSON type which compares lower than all other possible BSON element values.

> Note: This is an internal MongoDB type used for indexing and sharding.

## Class synopsis

final class MongoDB\BSON\MinKey implements MongoDB\BSON\MinKeyInterface, MongoDB\BSON\Type, JsonSerializable {
/* Methods */
final public __construct()
final public jsonSerialize(): mixed
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\MinKeyInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\MinKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MinKey::__construct — Construct a new MinKey

### Description

final public MongoDB\BSON\MinKey::__construct()

### Parameters

This function has no parameters.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\MinKey::__construct() example

`<?php
var_dump(new MongoDB\BSON\MinKey());
?>`

The above example will output:

    object(MongoDB\BSON\MinKey)#1 (0) {
    }

### See Also

- » BSON Types

# MongoDB\BSON\MinKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\MinKey::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\MinKey.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

## Table of Contents

- MongoDB\BSON\MinKey::__construct — Construct a new MinKey
- MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON

# The MongoDB\BSON\ObjectId class

(mongodb >=1.0.0)

## Introduction

BSON type for an » ObjectId. The value consists of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId's creation. Specifically, the value consists of:

- a 4-byte value representing the seconds since the Unix epoch,
- a 5-byte random number unique to a machine and process, and
- a 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique `_id` field that acts as a primary key. If an inserted document omits the `_id` field, the extension automatically generates an ObjectId for the `_id` field.

Using ObjectIds for the `_id` field provides the following additional benefits:

- The creation time of the ObjectId may be accessed using the MongoDB\BSON\ObjectId::getTimestamp() method.
- Sorting on an `_id` field that stores ObjectId values is roughly equivalent to sorting by creation time.

## Class synopsis

final class MongoDB\BSON\ObjectId implements MongoDB\BSON\ObjectIdInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(?string `$id` = `null`)
final public getTimestamp(): int
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Renamed from `MongoDB\BSON\ObjectID` to `MongoDB\BSON\ObjectId`. Implements MongoDB\BSON\ObjectIdInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\ObjectId::__construct

(mongodb >=1.0.0)

MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId

### Description

final public MongoDB\BSON\ObjectId::__construct(?string `$id` = `null`)

### Parameters

`id` (string)

  A 24-character hexadecimal string. If not provided, the extension will generate an ObjectId.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `id` is not a 24-character hexadecimal string.

### Examples

Example #1 MongoDB\BSON\ObjectId::__construct() example

`<?php
var_dump(new MongoDB\BSON\ObjectId());
var_dump(new MongoDB\BSON\ObjectId('000000000000000000000001'));
?>`

The above example will output something similar to:

    object(MongoDB\BSON\ObjectId)#1 (1) {
      ["oid"]=>
      string(24) "56732d3dda14d81214634921"
    }
    object(MongoDB\BSON\ObjectId)#1 (1) {
      ["oid"]=>
      string(24) "000000000000000000000001"
    }

### See Also

- » ObjectId Reference
- » BSON Types: ObjectId

# MongoDB\BSON\ObjectId::getTimestamp

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId

### Description

final public MongoDB\BSON\ObjectId::getTimestamp(): int

The timestamp component of an ObjectId is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

> Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The `"%u"` formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

### Parameters

This function has no parameters.

### Return Values

Returns the timestamp component of this ObjectId.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\ObjectId::getTimestamp() example

`<?php
var_dump((new MongoDB\BSON\ObjectId())->getTimestamp());
var_dump((new MongoDB\BSON\ObjectId('0000002a0000000000000000'))->getTimestamp());
?>`

The above example will output something similar to:

    integer(1484854719)
    integer(42)

### See Also

- » ObjectId Reference
- » BSON Types: ObjectId

# MongoDB\BSON\ObjectId::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\ObjectId::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\ObjectId.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\ObjectId::__toString

(mongodb >=1.0.0)

MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId

### Description

final public MongoDB\BSON\ObjectId::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hexidecimal representation of this ObjectId.

### Examples

Example #1 MongoDB\BSON\ObjectId::__toString() example

`<?php
var_dump((string) new MongoDB\BSON\ObjectId());
var_dump((string) new MongoDB\BSON\ObjectId('000000000000000000000001'));
?>`

The above example will output something similar to:

    string(24) "56731b49da14d8747d701211"
    string(24) "000000000000000000000001"

### See Also

- » ObjectId Reference
- » BSON Types: ObjectId

## Table of Contents

- MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId
- MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId
- MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId

# The MongoDB\BSON\Regex class

(mongodb >=1.0.0)

## Introduction

BSON type for a regular expression pattern and optional » flags.

> Note: This BSON type is mainly used when querying the database. Alternatively, the » $regex query operator may be used.

## Class synopsis

final class MongoDB\BSON\Regex implements MongoDB\BSON\RegexInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(string `$pattern`, string `$flags` = "")
final public getFlags(): string
final public getPattern(): string
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\RegexInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\Regex::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__construct — Construct a new Regex

### Description

final public MongoDB\BSON\Regex::__construct(string `$pattern`, string `$flags` = "")

### Parameters

`pattern` (string)

  The regular expression pattern.

  > Note: The pattern should not be wrapped with delimiter characters.

`flags` (string)

  The » regular expression flags. Characters in this argument will be sorted alphabetically.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if `pattern` or `flags` contain null bytes.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.2.0 | The `flags` argument is optional and defaults to an empty string. Characters in the `flags` argument will be sorted alphabetically when a Regex is constructed. Previously, the characters were stored in the order provided. MongoDB\Driver\Exception\InvalidArgumentException is thrown if `pattern` or `flags` contain null bytes. Previously, values would be truncated at the first null byte.

### Examples

Example #1 MongoDB\BSON\Regex::__construct() example

`<?php
$regex = new MongoDB\BSON\Regex('^foo', 'i');
var_dump($regex);
?>`

The above example will output:

    object(MongoDB\BSON\Regex)#1 (2) {
      ["pattern"]=>
      string(4) "^foo"
      ["flags"]=>
      string(1) "i"
    }

### See Also

- » BSON Types
- » Supported regular expression flags

# MongoDB\BSON\Regex::getFlags

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getFlags — Returns the Regex's flags

### Description

final public MongoDB\BSON\Regex::getFlags(): string

### Parameters

This function has no parameters.

### Return Values

Returns the Regex's flags.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Regex::getFlags() example

`<?php
$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getFlags());
?>`

The above example will output something similar to:

    string(1) "i"

### See Also

- » BSON Types
- » Supported regular expression flags

# MongoDB\BSON\Regex::getPattern

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern

### Description

final public MongoDB\BSON\Regex::getPattern(): string

### Parameters

This function has no parameters.

### Return Values

Returns the Regex's pattern.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Regex::getPattern() example

`<?php
$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getPattern());
?>`

The above example will output something similar to:

    string(5) "regex"

### See Also

- » BSON Types

# MongoDB\BSON\Regex::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Regex::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Regex.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Regex::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex

### Description

final public MongoDB\BSON\Regex::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Regex.

### Examples

Example #1 MongoDB\BSON\Regex::__toString() example

`<?php
$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump((string) $regex);
?>`

The above example will output:

    string(8) "/regex/i"

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\Regex::__construct — Construct a new Regex
- MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
- MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
- MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex

# The MongoDB\BSON\Timestamp class

(mongodb >=1.0.0)

## Introduction

Represents a » BSON timestamp, The value consists of a 4-byte timestamp (i.e. seconds since the epoch) and a 4-byte increment.

> Note: This is an internal MongoDB type used for replication and sharding. It is not intended for general date storage (MongoDB\BSON\UTCDateTime should be used instead).

## Class synopsis

final class MongoDB\BSON\Timestamp implements MongoDB\BSON\TimestampInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(int `$increment`, int `$timestamp`)
final public getIncrement(): int
final public getTimestamp(): int
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\TimestampInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\Timestamp::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp

### Description

final public MongoDB\BSON\Timestamp::__construct(int `$increment`, int `$timestamp`)

### Parameters

`increment` (int)

  32-bit integer denoting the incrementing ordinal for operations within a given second.

`timestamp` (int)

  32-bit integer denoting seconds since the Unix epoch.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\Timestamp::__construct() example

`<?php
$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);
?>`

The above example will output:

    object(MongoDB\BSON\Timestamp)#1 (2) {
      ["increment"]=>
      int(1234)
      ["timestamp"]=>
      int(5678)
    }

### See Also

- » BSON Types: Timestamps

# MongoDB\BSON\Timestamp::getIncrement

(mongodb >=1.3.0)

MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp

### Description

final public MongoDB\BSON\Timestamp::getIncrement(): int

The increment component of a Timestamp is its least significant 32 bits, whichs denotes the incrementing ordinal for operations within a given second. This value is read as an unsigned 32-bit integer with big-endian byte order.

> Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The `"%u"` formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

### Parameters

This function has no parameters.

### Return Values

Returns the increment component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- » BSON Types: Timestamps

# MongoDB\BSON\Timestamp::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp

### Description

final public MongoDB\BSON\Timestamp::getTimestamp(): int

The timestamp component of a Timestamp is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

> Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The `"%u"` formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

### Parameters

This function has no parameters.

### Return Values

Returns the timestamp component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- » BSON Types: Timestamps

# MongoDB\BSON\Timestamp::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Timestamp::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Timestamp.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Timestamp::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp

### Description

final public MongoDB\BSON\Timestamp::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Timestamp.

### Examples

Example #1 MongoDB\BSON\Timestamp::__toString() example

`<?php
$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);
var_dump((string) $timestamp);
?>`

The above example will output something similar to:

    string(11) "[1234:5678]"

### See Also

- » BSON Types: Timestamps

## Table of Contents

- MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
- MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp
- MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp
- MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp

# The MongoDB\BSON\UTCDateTime class

(mongodb >=1.0.0)

## Introduction

Represents a » BSON date. The value is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970.

## Class synopsis

final class MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface, MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(int|MongoDB\BSON\Int64|DateTimeInterface|null `$milliseconds` = `null`)
final public jsonSerialize(): mixed
final public toDateTime(): DateTime
final public toDateTimeImmutable(): DateTimeImmutable
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\UTCDateTimeInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

# MongoDB\BSON\UTCDateTime::__construct

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime

### Description

final public MongoDB\BSON\UTCDateTime::__construct(int|MongoDB\BSON\Int64|DateTimeInterface|null `$milliseconds` = `null`)

### Parameters

`milliseconds` (int|MongoDB\BSON\Int64|DateTimeInterface|null)

  Number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970. This value may be provided as a 64-bit int. For compatibility on 32-bit systems, this parameter may also be provided as a MongoDB\BSON\Int64.

  If the argument is a DateTimeInterface, the number of milliseconds since the Unix epoch will be derived from that value.

  If this argument is `null`, the current time will be used by default.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | The `milliseconds` no longer accepts a string or float argument.
PECL mongodb 1.20.0 | The `milliseconds` argument now accepts a MongoDB\BSON\Int64 object (for compatibility on 32-bit platforms). Specifying a string or float is deprecated.
PECL mongodb 1.2.0 | The `milliseconds` argument is optional and defaults to `null` (i.e. current time). The argument also accepts a DateTimeInterface, which may be used to derive the number of milliseconds since the Unix epoch. Previously, only int, float, and string types were accepted.

### Examples

Example #1 MongoDB\BSON\UTCDateTime::__construct() example

`<?php
var_dump(new MongoDB\BSON\UTCDateTime);
var_dump(new MongoDB\BSON\UTCDateTime(new DateTime));
var_dump(new MongoDB\BSON\UTCDateTime(1416445411987));
?>`

The above example will output something similar to:

    object(MongoDB\BSON\UTCDateTime)#1 (1) {
      ["milliseconds"]=>
      string(13) "1484852905560"
    }
    object(MongoDB\BSON\UTCDateTime)#1 (1) {
      ["milliseconds"]=>
      string(13) "1484852905560"
    }
    object(MongoDB\BSON\UTCDateTime)#1 (1) {
      ["milliseconds"]=>
      string(13) "1416445411987"
    }

### See Also

- » BSON Types: Date

# MongoDB\BSON\UTCDateTime::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\UTCDateTime::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\UTCDateTime.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\UTCDateTime::toDateTime

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime

### Description

final public MongoDB\BSON\UTCDateTime::toDateTime(): DateTime

### Parameters

This function has no parameters.

### Return Values

Returns the DateTime representation of this UTCDateTime. The returned DateTime will use the UTC time zone.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\UTCDatetime::toDateTime() example

`<?php
$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime->format('r'));
var_dump($datetime->format('U.u'));
var_dump($datetime->getTimezone());
?>`

The above example will output something similar to:

    string(31) "Thu, 20 Nov 2014 01:03:31 +0000"
    string(17) "1416445411.987000"
    object(DateTimeZone)#3 (2) {
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "+00:00"
    }

### See Also

- MongoDB\BSON\UTCDateTime::toDateTimeImmutable() - Returns the DateTimeImmutable representation of this UTCDateTime
- » BSON Types: Date

# MongoDB\BSON\UTCDateTime::toDateTimeImmutable

(mongodb >=1.20.0)

MongoDB\BSON\UTCDateTime::toDateTimeImmutable — Returns the DateTimeImmutable representation of this UTCDateTime

### Description

final public MongoDB\BSON\UTCDateTime::toDateTimeImmutable(): DateTimeImmutable

### Parameters

This function has no parameters.

### Return Values

Returns the DateTimeImmutable representation of this UTCDateTime. The returned DateTimeImmutable will use the UTC time zone.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Examples

Example #1 MongoDB\BSON\UTCDatetime::toDateTimeImmutable() example

`<?php
$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTimeImmutable();
var_dump($datetime->format('r'));
var_dump($datetime->format('U.u'));
var_dump($datetime->getTimezone());
?>`

The above example will output something similar to:

    string(31) "Thu, 20 Nov 2014 01:03:31 +0000"
    string(17) "1416445411.987000"
    object(DateTimeZone)#3 (2) {
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "+00:00"
    }

### See Also

- MongoDB\BSON\UTCDateTime::toDateTime() - Returns the DateTime representation of this UTCDateTime
- » BSON Types: Date

# MongoDB\BSON\UTCDateTime::__toString

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime

### Description

final public MongoDB\BSON\UTCDateTime::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this UTCDateTime.

### Examples

Example #1 MongoDB\BSON\UTCDateTime::__toString() example

`<?php
$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
var_dump((string) $utcdatetime);
?>`

The above example will output:

    string(13) "1416445411987"

### See Also

- » BSON Types: Date

## Table of Contents

- MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
- MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
- MongoDB\BSON\UTCDateTime::toDateTimeImmutable — Returns the DateTimeImmutable representation of this UTCDateTime
- MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime

# The MongoDB\BSON\Type interface

(mongodb >=1.0.0)

## Introduction

Abstract base interface that should not be implemented directly.

## Interface synopsis

class MongoDB\BSON\Type {
}

This interface has no methods. Its only purpose is to be the base interface for all BSON type classes.

# The MongoDB\BSON\Persistable interface

(mongodb >=1.0.0)

## Introduction

Classes may implement this interface to take advantage of automatic ODM (object document mapping) behavior in the extension. During serialization, the extension will inject a __pclass property containing the PHP class name into the data returned by MongoDB\BSON\Serializable::bsonSerialize(). During unserialization, the same __pclass property will then be used to infer the PHP class (independent of any type map configuration) to be constructed before MongoDB\BSON\Unserializable::bsonUnserialize() is invoked. See Persisting Data for additional information.

> Note: Even if MongoDB\BSON\Serializable::bsonSerialize() would return a sequential array, injection of the __pclass property will cause the object to be serialized as a BSON document.

## Interface synopsis

class MongoDB\BSON\Persistable implements MongoDB\BSON\Unserializable, MongoDB\BSON\Serializable {
/* Methods */
abstract public bsonSerialize(): array|stdClass|MongoDB\BSON\Document
/* Inherited methods */
abstract public MongoDB\BSON\Serializable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray
abstract public MongoDB\BSON\Unserializable::bsonUnserialize(array `$data`): void
}

# MongoDB\BSON\Persistable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Persistable::bsonSerialize — Provides an array or document to serialize as BSON

### Description

abstract public MongoDB\BSON\Persistable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document

Called during serialization of the object to BSON. The method must return an array, stdClass, or MongoDB\BSON\Document.

The return value will always be serialized as a BSON document. The serialized document will include a field containing the class name of the object. For this reason, it is not possible to return a MongoDB\BSON\PackedArray instance in this method.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectId initialized in the constructor) when returning data for a BSON root document. In the absence of an _id property, the extension or server will generate a MongoDB\BSON\ObjectId for insert or upsert operations, respectively.

### Parameters

This function has no parameters.

### Return Values

An array, stdClass, or MongoDB\BSON\Document to be serialized as a BSON document.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.17.0 | This method may now also return MongoDB\BSON\Document instances in addition to array and stdClass.

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
- MongoDB\BSON\Unserializable::bsonUnserialize() - Constructs the object from a BSON array or document
- MongoDB\BSON\Persistable
- Persisting Data

## Table of Contents

- MongoDB\BSON\Persistable::bsonSerialize — Provides an array or document to serialize as BSON

# The MongoDB\BSON\Serializable interface

(mongodb >=1.0.0)

## Introduction

Classes that implement this interface may return data to be serialized as a BSON array or document in lieu of the object's public properties.

## Interface synopsis

class MongoDB\BSON\Serializable implements MongoDB\BSON\Type {
/* Methods */
abstract public bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\Serializable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON

### Description

abstract public MongoDB\BSON\Serializable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray

Called during serialization of the object to BSON. The method must return an array, stdClass, MongoDB\BSON\Document, or MongoDB\BSON\PackedArray.

Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\Document::fromPHP()) will always be serialized as a BSON document. For field values, associative arrays and stdClass instances will be serialized as a BSON document and sequential arrays (i.e. sequential, numeric indexes starting at `0`) will be serialized as a BSON array.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectId initialized in the constructor) when returning data for a BSON root document. In the absence of an _id property, the extension or server will generate a MongoDB\BSON\ObjectId for insert or upsert operations, respectively.

### Parameters

This function has no parameters.

### Return Values

An array, stdClass, MongoDB\BSON\Document, or MongoDB\BSON\PackedArray to be serialized as a BSON array or document.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.17.0 | The return type was changed from array|object. Instead of object, the return type now specifies stdClass. Classes that implement this interface must be changed to no longer declare an object return type. As the return type is tentative, a deprecation warning is emitted on PHP 8.1 and newer. In addition to the changes above, the extension now also supports returning instances of MongoDB\BSON\Document and MongoDB\BSON\PackedArray. Please note that any MongoDB\BSON\PackedArray instances returned are silently converted to objects when stored as root documents. They are stored as arrays when used as an embedded field value.

### Examples

Example #1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document

`<?php
class MyDocument implements MongoDB\BSON\Serializable
{
private $id;
function __construct()
{
$this->id = new MongoDB\BSON\ObjectId;
}
function bsonSerialize(): array
{
return ['_id' => $this->id, 'foo' => 'bar'];
}
}
echo MongoDB\BSON\Document::fromPHP(new MyDocument)->toRelaxedExtendedJSON(), "\n";
?>`

The above example will output something similar to:

    { "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }

Example #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document

`<?php
class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}
echo MongoDB\BSON\Document::fromPHP(new MyArray)->toRelaxedExtendedJSON(), "\n";
?>`

The above example will output:

    { "0" : 1, "1" : 2, "2" : 3 }

Example #3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field

`<?php
class MyDocument implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return ['foo' => 'bar'];
}
}
$value = ['document' => new MyDocument];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>`

The above example will output:

    { "document" : { "foo" : "bar" } }

Example #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field

`<?php
class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}
$value = ['array' => new MyArray];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>`

The above example will output:

    { "array" : [ 1, 2, 3 ] }

### See Also

- MongoDB\BSON\Unserializable::bsonUnserialize() - Constructs the object from a BSON array or document
- MongoDB\BSON\Persistable
- Persisting Data

## Table of Contents

- MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON

# The MongoDB\BSON\Unserializable interface

(mongodb >=1.0.0)

## Introduction

Classes that implement this interface may be specified in a type map for unserializing BSON arrays and documents (both root and embedded).

## Interface synopsis

class MongoDB\BSON\Unserializable {
/* Methods */
abstract public bsonUnserialize(array `$data`): void
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\Unserializable::bsonUnserialize

(mongodb >=1.0.0)

MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document

### Description

abstract public MongoDB\BSON\Unserializable::bsonUnserialize(array `$data`): void

Called during unserialization of the object from BSON. The properties of the BSON array or document will be passed to the method as an array.

Remember to check for an _id property when handling data from a BSON document.

> Note: This method acts as the constructor of the object. The __construct() method will not be called after this method.

### Parameters

`data` (array)

  Properties within the BSON array or document.

### Return Values

The return value from this method is ignored.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.

### Examples

Example #1 MongoDB\BSON\Unserializable::bsonUnserialize() example

`<?php
class MyDocument implements MongoDB\BSON\Unserializable
{
private $data = [];
function bsonUnserialize(array $data): void
{
$this->data = $data;
}
}
$bson = MongoDB\BSON\Document::fromJSON('{ "foo": "bar" }');
var_dump($bson->toPHP(['root' => 'MyDocument']));
?>`

The above example will output:

    object(MyDocument)#1 (1) {
      ["data":"MyDocument":private]=>
      array(1) {
        ["foo"]=>
        string(3) "bar"
      }
    }

### See Also

- MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
- MongoDB\BSON\Persistable
- Persisting Data

## Table of Contents

- MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document

# The MongoDB\BSON\BinaryInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\Binary to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\BinaryInterface {
/* Methods */
abstract public getData(): string
abstract public getType(): int
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\BinaryInterface::getData

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data

### Description

abstract public MongoDB\BSON\BinaryInterface::getData(): string

### Parameters

This function has no parameters.

### Return Values

Returns the BinaryInterface's data.

### See Also

- MongoDB\BSON\Binary::getData() - Returns the Binary's data

# MongoDB\BSON\BinaryInterface::getType

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type

### Description

abstract public MongoDB\BSON\BinaryInterface::getType(): int

### Parameters

This function has no parameters.

### Return Values

Returns the BinaryInterface's type.

### See Also

- MongoDB\BSON\Binary::getType() - Returns the Binary's type

# MongoDB\BSON\BinaryInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data

### Description

abstract public MongoDB\BSON\BinaryInterface::__toString(): string

This method is an alias of: MongoDB\BSON\BinaryInterface::getData().

### Parameters

This function has no parameters.

### Return Values

Returns the BinaryInterface's data.

### See Also

- MongoDB\BSON\BinaryInterface::getData() - Returns the BinaryInterface's data
- MongoDB\BSON\Binary::__toString() - Returns the Binary's data

## Table of Contents

- MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data
- MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type
- MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data

# The MongoDB\BSON\Decimal128Interface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\Decimal128 to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\Decimal128Interface {
/* Methods */
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\Decimal128Interface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface

### Description

abstract public MongoDB\BSON\Decimal128Interface::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Decimal128Interface.

### See Also

- MongoDB\BSON\Decimal128::__toString() - Returns the string representation of this Decimal128

## Table of Contents

- MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface

# The MongoDB\BSON\JavascriptInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\Javascript to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\JavascriptInterface {
/* Methods */
abstract public getCode(): string
abstract public getScope(): ?object
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\JavascriptInterface::getCode

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code

### Description

abstract public MongoDB\BSON\JavascriptInterface::getCode(): string

### Parameters

This function has no parameters.

### Return Values

Returns the JavascriptInterface's code.

### See Also

- MongoDB\BSON\Javascript::getCode() - Returns the Javascript's code

# MongoDB\BSON\JavascriptInterface::getScope

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document

### Description

abstract public MongoDB\BSON\JavascriptInterface::getScope(): ?object

### Parameters

This function has no parameters.

### Return Values

Returns the JavascriptInterface's scope document.

### See Also

- MongoDB\BSON\Javascript::getScope() - Returns the Javascript's scope document

# MongoDB\BSON\JavascriptInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code

### Description

abstract public MongoDB\BSON\JavascriptInterface::__toString(): string

This method is an alias of: MongoDB\BSON\JavascriptInterface::getCode().

### Parameters

This function has no parameters.

### Return Values

Returns the JavascriptInterface's code.

### See Also

- MongoDB\BSON\JavascriptInterface::getCode() - Returns the JavascriptInterface's code
- MongoDB\BSON\Javascript::__toString() - Returns the Javascript's code

## Table of Contents

- MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code
- MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document
- MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code

# The MongoDB\BSON\MaxKeyInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\MaxKey to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\MaxKeyInterface {
}

This interface has no methods.

# The MongoDB\BSON\MinKeyInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\MinKey to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\MinKeyInterface {
}

This interface has no methods.

# The MongoDB\BSON\ObjectIdInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\ObjectId to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\ObjectIdInterface {
/* Methods */
abstract public getTimestamp(): int
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\ObjectIdInterface::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface

### Description

abstract public MongoDB\BSON\ObjectIdInterface::getTimestamp(): int

### Parameters

This function has no parameters.

### Return Values

Returns the timestamp component of this ObjectIdInterface.

### See Also

- MongoDB\BSON\ObjectId::getTimestamp() - Returns the timestamp component of this ObjectId

# MongoDB\BSON\ObjectIdInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface

### Description

abstract public MongoDB\BSON\ObjectIdInterface::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hexidecimal representation of this ObjectIdInterface.

### See Also

- MongoDB\BSON\ObjectId::__toString() - Returns the hexidecimal representation of this ObjectId

## Table of Contents

- MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface
- MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface

# The MongoDB\BSON\RegexInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\Regex to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\RegexInterface {
/* Methods */
abstract public getFlags(): string
abstract public getPattern(): string
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\RegexInterface::getFlags

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags

### Description

abstract public MongoDB\BSON\RegexInterface::getFlags(): string

### Parameters

This function has no parameters.

### Return Values

Returns the RegexInterface's flags.

### See Also

- MongoDB\BSON\Regex::getFlags() - Returns the Regex's flags

# MongoDB\BSON\RegexInterface::getPattern

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern

### Description

abstract public MongoDB\BSON\RegexInterface::getPattern(): string

### Parameters

This function has no parameters.

### Return Values

Returns the RegexInterface's pattern.

### See Also

- MongoDB\BSON\Regex::getPattern() - Returns the Regex's pattern

# MongoDB\BSON\RegexInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface

### Description

abstract public MongoDB\BSON\RegexInterface::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this RegexInterface.

### See Also

- MongoDB\BSON\Regex::__toString() - Returns the string representation of this Regex

## Table of Contents

- MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags
- MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern
- MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface

# The MongoDB\BSON\TimestampInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\Timestamp to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\TimestampInterface {
/* Methods */
abstract public getIncrement(): int
abstract public getTimestamp(): int
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\TimestampInterface::getIncrement

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface

### Description

abstract public MongoDB\BSON\TimestampInterface::getIncrement(): int

### Parameters

This function has no parameters.

### Return Values

Returns the increment component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

### See Also

- MongoDB\BSON\Timestamp::getIncrement() - Returns the increment component of this Timestamp

# MongoDB\BSON\TimestampInterface::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface

### Description

abstract public MongoDB\BSON\TimestampInterface::getTimestamp(): int

### Parameters

This function has no parameters.

### Return Values

Returns the timestamp component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

### See Also

- MongoDB\BSON\Timestamp::getTimestamp() - Returns the timestamp component of this Timestamp

# MongoDB\BSON\TimestampInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface

### Description

abstract public MongoDB\BSON\TimestampInterface::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this TimestampInterface.

### See Also

- MongoDB\BSON\Timestamp::__toString() - Returns the string representation of this Timestamp

## Table of Contents

- MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface
- MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface
- MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface

# The MongoDB\BSON\UTCDateTimeInterface interface

(mongodb >=1.3.0)

## Introduction

This interface is implemented by MongoDB\BSON\UTCDateTime to be used as a parameter, return, or property type in userland classes.

## Class synopsis

class MongoDB\BSON\UTCDateTimeInterface {
/* Methods */
abstract public toDateTime(): DateTime
abstract public toDateTimeImmutable(): DateTimeImmutable
abstract public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\BSON\UTCDateTimeInterface::toDateTime

(mongodb >=1.3.0)

MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface

### Description

abstract public MongoDB\BSON\UTCDateTimeInterface::toDateTime(): DateTime

### Parameters

This function has no parameters.

### Return Values

Returns the DateTime representation of this UTCDateTimeInterface. The returned DateTime should use the UTC time zone.

### See Also

- MongoDB\BSON\UTCDateTime::toDateTime() - Returns the DateTime representation of this UTCDateTime

# MongoDB\BSON\UTCDateTimeInterface::toDateTimeImmutable

(mongodb >=2.0.0)

MongoDB\BSON\UTCDateTimeInterface::toDateTimeImmutable — Returns the DateTimeImmutable representation of this UTCDateTimeInterface

### Description

abstract public MongoDB\BSON\UTCDateTimeInterface::toDateTimeImmutable(): DateTimeImmutable

### Parameters

This function has no parameters.

### Return Values

Returns the DateTimeImmutable representation of this UTCDateTimeInterface. The returned DateTimeImmutable will use the UTC time zone.

### See Also

- MongoDB\BSON\UTCDateTime::toDateTimeImmutable() - Returns the DateTimeImmutable representation of this UTCDateTime

# MongoDB\BSON\UTCDateTimeInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface

### Description

abstract public MongoDB\BSON\UTCDateTimeInterface::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this UTCDateTimeInterface.

### See Also

- MongoDB\BSON\UTCDateTime::__toString() - Returns the string representation of this UTCDateTime

## Table of Contents

- MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
- MongoDB\BSON\UTCDateTimeInterface::toDateTimeImmutable — Returns the DateTimeImmutable representation of this UTCDateTimeInterface
- MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface

# The MongoDB\BSON\DBPointer class

(mongodb >=1.4.0)

## Introduction

BSON type for the "DBPointer" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON DBPointer type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

## Class synopsis

final class MongoDB\BSON\DBPointer implements MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final private __construct()
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

# MongoDB\BSON\DBPointer::__construct

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)

### Description

final private MongoDB\BSON\DBPointer::__construct()

MongoDB\BSON\DBPointer objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- » BSON Types

# MongoDB\BSON\DBPointer::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\DBPointer::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\DBPointer.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\DBPointer::__toString

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__toString — Returns an empty string

### Description

final public MongoDB\BSON\DBPointer::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns an empty string.

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)
- MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\DBPointer::__toString — Returns an empty string

# The MongoDB\BSON\Int64 class

(mongodb >=1.5.0)

## Introduction

BSON type for a 64-bit integer. When decoding BSON to PHP data, this class is used when a 64-bit integer cannot be represented as a PHP integer on 32-bit platforms. These objects support overloaded arithmetic, bitwise, and comparison operators.

When working with raw BSON data through the MongoDB\BSON\Document, MongoDB\BSON\PackedArray, and MongoDB\BSON\Iterator classes, any 64-bit integer will be returned as an instance of this class, regardless of platform and whether the value can be represented as a PHP integer. This ensures that values can be roundtripped without changing the type.

During BSON encoding, objects of this class will convert back to a 64-bit integer type, even when the value would fit in a 32-bit integer. This allows explicitly storing values as 64-bit integers in BSON.

## Class synopsis

final class MongoDB\BSON\Int64 implements MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final public __construct(int|string `$value`)
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.16.0 | The class can now be instantiated on all platforms. Added support for overloaded arithmetic, bitwise, and comparison operators.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

# MongoDB\BSON\Int64::__construct

(mongodb >=1.5.0)

MongoDB\BSON\Int64::__construct — Construct a new Int64

### Description

final public MongoDB\BSON\Int64::__construct(int|string `$value`)

Creates a new MongoDB\BSON\Int64 instance for the given integer value.

### Parameters

`value` (int|string)

  The value to assign to the Int64 instance. This value can be provided as an int or string, the latter being required on 32-bit platforms to represent 64-bit values.

### Changelog

Version | Description
--- | ---
PECL mongodb 1.16.0 | This method was made public to support creating Int64 instances when working with raw BSON.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if string `value` cannot be parsed as a 64-bit integer.

### See Also

- » BSON Types

# MongoDB\BSON\Int64::jsonSerialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Int64::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Int64.

> Note: The output is consistent with the MongoDB\BSON\toCanonicalExtendedJSON() function, which uses the » canonical extended JSON format. This differs from other BSON classes, which use the driver-specific legacy extended JSON format (MongoDB\BSON\toJSON()), in order to ensure that the 64-bit integer value is correctly represented on 32-bit platforms.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Int64::__toString

(mongodb >=1.5.0)

MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64

### Description

final public MongoDB\BSON\Int64::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Int64.

### Examples

Example #1 MongoDB\BSON\Int64::__toString() example

`<?php
$int64 = new MongoDB\BSON\Int64('9223372036854775807');
var_dump((string) $int64);
?>`

The above example will output something similar to:

    string(19) "9223372036854775807"

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\Int64::__construct — Construct a new Int64
- MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64

# The MongoDB\BSON\Symbol class

(mongodb >=1.4.0)

## Introduction

BSON type for the "Symbol" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON symbol type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

## Class synopsis

final class MongoDB\BSON\Symbol implements MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final private __construct()
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

# MongoDB\BSON\Symbol::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)

### Description

final private MongoDB\BSON\Symbol::__construct()

MongoDB\BSON\Symbol objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- » BSON Types

# MongoDB\BSON\Symbol::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Symbol::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Symbol.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Symbol::__toString

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string

### Description

final public MongoDB\BSON\Symbol::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns the string representation of this Symbol.

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)
- MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string

# The MongoDB\BSON\Undefined class

(mongodb >=1.4.0)

## Introduction

BSON type for the "Undefined" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON undefined type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

## Class synopsis

final class MongoDB\BSON\Undefined implements MongoDB\BSON\Type, JsonSerializable, Stringable {
/* Methods */
final private __construct()
final public jsonSerialize(): mixed
final public __toString(): string
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class no longer implements the Serializable interface.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

# MongoDB\BSON\Undefined::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)

### Description

final private MongoDB\BSON\Undefined::__construct()

MongoDB\BSON\Undefined objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

### Parameters

This function has no parameters.

### See Also

- » BSON Types

# MongoDB\BSON\Undefined::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON

### Description

final public MongoDB\BSON\Undefined::jsonSerialize(): mixed

### Parameters

This function has no parameters.

### Return Values

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Undefined.

> Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
- json_encode() - Returns the JSON representation of a value
- MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
- » MongoDB Extended JSON

# MongoDB\BSON\Undefined::__toString

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__toString — Returns an empty string

### Description

final public MongoDB\BSON\Undefined::__toString(): string

### Parameters

This function has no parameters.

### Return Values

Returns an empty string.

### See Also

- » BSON Types

## Table of Contents

- MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)
- MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Undefined::__toString — Returns an empty string

# Monitoring classes and subscriber functions

## Table of Contents

- Functions
- MongoDB\Driver\Monitoring\CommandFailedEvent
- MongoDB\Driver\Monitoring\CommandStartedEvent
- MongoDB\Driver\Monitoring\CommandSucceededEvent
- MongoDB\Driver\Monitoring\ServerChangedEvent
- MongoDB\Driver\Monitoring\ServerClosedEvent
- MongoDB\Driver\Monitoring\ServerOpeningEvent
- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
- MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
- MongoDB\Driver\Monitoring\TopologyChangedEvent
- MongoDB\Driver\Monitoring\TopologyClosedEvent
- MongoDB\Driver\Monitoring\TopologyOpeningEvent
- MongoDB\Driver\Monitoring\CommandSubscriber
- MongoDB\Driver\Monitoring\LogSubscriber
- MongoDB\Driver\Monitoring\SDAMSubscriber
- MongoDB\Driver\Monitoring\Subscriber

# Functions

# MongoDB\Driver\Monitoring\addSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\addSubscriber — Registers a monitoring event subscriber globally

### Description

MongoDB\Driver\Monitoring\addSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void

Registers a monitoring event subscriber globally. The subscriber will be notified of all events in the extension for any Manager.

> Note: If `subscriber` is already registered globally, this function is a no-op. If `subscriber` is also registered with one or more Managers, it will still only be notified once of each event for each Manager.

### Parameters

`subscriber` (MongoDB\Driver\Monitoring\Subscriber)

  A monitoring event subscriber to register globally.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\removeSubscriber() - Unregisters a monitoring event subscriber globally
- MongoDB\Driver\Monitoring\Subscriber
- MongoDB\Driver\Monitoring\CommandSubscriber
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\removeSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\removeSubscriber — Unregisters a monitoring event subscriber globally

### Description

MongoDB\Driver\Monitoring\removeSubscriber(MongoDB\Driver\Monitoring\Subscriber `$subscriber`): void

Unregisters a monitoring event subscriber globally.

> Note: If `subscriber` is not already registered globally, this function is a no-op.

### Parameters

`subscriber` (MongoDB\Driver\Monitoring\Subscriber)

  A monitoring event subscriber to unregister globally.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Monitoring\Subscriber
- MongoDB\Driver\Monitoring\CommandSubscriber
- MongoDB\Driver\Manager::removeSubscriber() - Unregisters a monitoring event subscriber with this Manager
- Application Performance Monitoring (APM)

## Table of Contents

- MongoDB\Driver\Monitoring\addSubscriber — Registers a monitoring event subscriber globally
- MongoDB\Driver\Monitoring\removeSubscriber — Unregisters a monitoring event subscriber globally

# The MongoDB\Driver\Monitoring\CommandFailedEvent class

(mongodb >=1.3.0)

## Introduction

The MongoDB\Driver\Monitoring\CommandFailedEvent class encapsulates information about a failed command.

## Class synopsis

final class MongoDB\Driver\Monitoring\CommandFailedEvent {
/* Methods */
final public getCommandName(): string
final public getDatabaseName(): string
final public getDurationMicros(): int
final public getError(): Exception
final public getHost(): string
final public getOperationId(): string
final public getPort(): int
final public getReply(): object
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName(): string

Returns the command name (e.g. `"find"`, `"aggregate"`).

### Parameters

This function has no parameters.

### Return Values

Returns the command name.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getDatabaseName

(mongodb >=1.19.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getDatabaseName — Returns the database on which the command was executed

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getDatabaseName(): string

### Parameters

This function has no parameters.

### Return Values

Returns the database on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros(): int

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

### Parameters

This function has no parameters.

### Return Values

Returns the command's duration in microseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getError

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getError(): Exception

### Parameters

This function has no parameters.

### Return Values

Returns the Exception associated with the failed command.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getHost

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getHost — Returns the server hostname for the command

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId(): string

The operation ID is generated by the extension and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

> Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() should be used instead.

### Parameters

This function has no parameters.

### Return Values

Returns the command's operation ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId() - Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getPort

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getPort — Returns the server port for the command

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandFailedEvent::getReply

(mongodb >=1.5.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

### Parameters

This function has no parameters.

### Return Values

Returns the command reply document as a stdClass object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)
- Persisting Data

# MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId(): string

The request ID is generated by the extension and may be used to associate this MongoDB\Driver\Monitoring\CommandFailedEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

### Parameters

This function has no parameters.

### Return Values

Returns the command's request ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed

Warning

This method has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\Driver\Monitoring\CommandFailedEvent::getHost() and MongoDB\Driver\Monitoring\CommandFailedEvent::getPort() instead.

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method was removed.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getServer() - Returns the Server on which the command was executed
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId — Returns the server connection ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandFailedEvent::getServer()) and is returned in the "connectionId" field of a `hello` command response MongoDB 4.2+.

### Parameters

This function has no parameters.

### Return Values

Returns the server connection ID, or `null` if it is not available.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId — Returns the load balancer service ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the `serviceId` field in the `hello` command response.

### Parameters

This function has no parameters.

### Return Values

Returns the load balancer service ID, or `null` if the driver is not connected to a load balancer.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandFailedEvent::getDatabaseName — Returns the database on which the command was executed
- MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds
- MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command
- MongoDB\Driver\Monitoring\CommandFailedEvent::getHost — Returns the server hostname for the command
- MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandFailedEvent::getPort — Returns the server port for the command
- MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document
- MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId — Returns the server connection ID for the command
- MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId — Returns the load balancer service ID for the command

# The MongoDB\Driver\Monitoring\CommandStartedEvent class

(mongodb >=1.3.0)

## Introduction

The MongoDB\Driver\Monitoring\CommandStartedEvent class encapsulates information about a started command.

## Class synopsis

final class MongoDB\Driver\Monitoring\CommandStartedEvent {
/* Methods */
final public getCommand(): object
final public getCommandName(): string
final public getDatabaseName(): string
final public getHost(): string
final public getOperationId(): string
final public getPort(): int
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

### Parameters

This function has no parameters.

### Return Values

Returns the command document as a stdClass object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)
- Persisting Data

# MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName(): string

Returns the command name (e.g. `"find"`, `"aggregate"`).

### Parameters

This function has no parameters.

### Return Values

Returns the command name.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName(): string

### Parameters

This function has no parameters.

### Return Values

Returns the database on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandStartedEvent::getHost

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getHost — Returns the server hostname for the command

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId(): string

The operation ID is generated by the extension and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

> Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() should be used instead.

### Parameters

This function has no parameters.

### Return Values

Returns the command's operation ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId() - Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId() - Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandStartedEvent::getPort

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getPort — Returns the server port for the command

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId(): string

The request ID is generated by the extension and may be used to associate this MongoDB\Driver\Monitoring\CommandStartedEvent with a later MongoDB\Driver\Monitoring\CommandFailedEvent or MongoDB\Driver\Monitoring\CommandSucceededEvent.

### Parameters

This function has no parameters.

### Return Values

Returns the command's request ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() - Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandStartedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed

Warning

This method has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\Driver\Monitoring\CommandStartedEvent::getHost() and MongoDB\Driver\Monitoring\CommandStartedEvent::getPort() instead.

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method was removed.

### See Also

- MongoDB\Driver\Monitoring\CommandFailedEvent::getServer() - Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer() - Returns the Server on which the command was executed
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId — Returns the server connection ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandStartedEvent::getServer()) and is returned in the "connectionId" field of a `hello` command response MongoDB 4.2+.

### Parameters

This function has no parameters.

### Return Values

Returns the server connection ID, or `null` if it is not available.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId — Returns the load balancer service ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the `serviceId` field in the `hello` command response.

### Parameters

This function has no parameters.

### Return Values

Returns the load balancer service ID, or `null` if the driver is not connected to a load balancer.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document
- MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed
- MongoDB\Driver\Monitoring\CommandStartedEvent::getHost — Returns the server hostname for the command
- MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandStartedEvent::getPort — Returns the server port for the command
- MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId — Returns the server connection ID for the command
- MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId — Returns the load balancer service ID for the command

# The MongoDB\Driver\Monitoring\CommandSucceededEvent class

(mongodb >=1.3.0)

## Introduction

The MongoDB\Driver\Monitoring\CommandSucceededEvent class encapsulates information about a successful command.

## Class synopsis

final class MongoDB\Driver\Monitoring\CommandSucceededEvent {
/* Methods */
final public getCommandName(): string
final public getDatabaseName(): string
final public getDurationMicros(): int
final public getHost(): string
final public getOperationId(): string
final public getPort(): int
final public getReply(): object
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName(): string

Returns the command name (e.g. `"find"`, `"aggregate"`).

### Parameters

This function has no parameters.

### Return Values

Returns the command name.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getDatabaseName

(mongodb >=1.19.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getDatabaseName — Returns the database on which the command was executed

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getDatabaseName(): string

### Parameters

This function has no parameters.

### Return Values

Returns the database on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros(): int

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

### Parameters

This function has no parameters.

### Return Values

Returns the command's duration in microseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getHost

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getHost — Returns the server hostname for the command

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId(): string

The operation ID is generated by the extension and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

> Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() should be used instead.

### Parameters

This function has no parameters.

### Return Values

Returns the command's operation ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId() - Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getPort

(mongodb >=1.20.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getPort — Returns the server port for the command

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port of the server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

### Parameters

This function has no parameters.

### Return Values

Returns the command reply document as a stdClass object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)
- Persisting Data

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId(): string

The request ID is generated by the extension and may be used to associate this MongoDB\Driver\Monitoring\CommandSucceededEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

### Parameters

This function has no parameters.

### Return Values

Returns the command's request ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed

Warning

This method has been DEPRECATED as of extension version 1.20.0 and was removed in 2.0. Applications should use MongoDB\Driver\Monitoring\CommandSucceededEvent::getHost() and MongoDB\Driver\Monitoring\CommandSucceededEvent::getPort() instead.

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

### Parameters

This function has no parameters.

### Return Values

Returns the MongoDB\Driver\Server on which the command was executed.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This method was removed.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent::getServer() - Returns the Server on which the command was executed
- MongoDB\Driver\Cursor::getServer() - Returns the server associated with this cursor
- MongoDB\Driver\WriteResult::getServer() - Returns the server associated with this write result
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId — Returns the server connection ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer()) and is returned in the "connectionId" field of a `hello` command response MongoDB 4.2+.

### Parameters

This function has no parameters.

### Return Values

Returns the server connection ID, or `null` if it is not available.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId — Returns the load balancer service ID for the command

### Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the `serviceId` field in the `hello` command response.

### Parameters

This function has no parameters.

### Return Values

Returns the load balancer service ID, or `null` if the driver is not connected to a load balancer.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getDatabaseName — Returns the database on which the command was executed
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getHost — Returns the server hostname for the command
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getPort — Returns the server port for the command
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId — Returns the server connection ID for the command
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId — Returns the load balancer service ID for the command

# The MongoDB\Driver\Monitoring\ServerChangedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerChangedEvent class encapsulates information about a changed server description. For example, a server's type changing from secondary to primary would cause its server description to change.

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerChangedEvent {
/* Methods */
final public getHost(): string
final public getNewDescription(): MongoDB\Driver\ServerDescription
final public getPort(): int
final public getPreviousDescription(): MongoDB\Driver\ServerDescription
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\ServerChangedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription — Returns the new description for the server

### Description

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription(): MongoDB\Driver\ServerDescription

### Parameters

This function has no parameters.

### Return Values

Returns the new MongoDB\Driver\ServerDescription for the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerChangedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription — Returns the previous description for the server

### Description

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription(): MongoDB\Driver\ServerDescription

### Parameters

This function has no parameters.

### Return Values

Returns the previous MongoDB\Driver\ServerDescription for the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId — Returns the topology ID associated with this server

### Description

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerChangedEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription — Returns the new description for the server
- MongoDB\Driver\Monitoring\ServerChangedEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription — Returns the previous description for the server
- MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId — Returns the topology ID associated with this server

# The MongoDB\Driver\Monitoring\ServerClosedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerClosedEvent class encapsulates information about a closed server. This corresponds to an existing server being removed from the topology.

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerClosedEvent {
/* Methods */
final public getHost(): string
final public getPort(): int
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\ServerClosedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerClosedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId — Returns the topology ID associated with this server

### Description

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerClosedEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerClosedEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId — Returns the topology ID associated with this server

# The MongoDB\Driver\Monitoring\ServerOpeningEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerOpeningEvent class encapsulates information about an opened server. This corresponds to a new server being added to the topology.

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerOpeningEvent {
/* Methods */
final public getHost(): string
final public getPort(): int
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId — Returns the topology ID associated with this server

### Description

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId — Returns the topology ID associated with this server

# The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class encapsulates information about a failed server heartbeat (i.e. » hello command issued through » server monitoring).

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent {
/* Methods */
final public getDurationMicros(): int
final public getError(): Exception
final public getHost(): string
final public getPort(): int
final public isAwaited(): bool
}

# MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros — Returns the heartbeat's duration in microseconds

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros(): int

The heartbeat's duration is a calculated value that includes the time to send the message and receive the reply from the server.

### Parameters

This function has no parameters.

### Return Values

Returns the heartbeat's duration in microseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError — Returns the Exception associated with the failed heartbeat

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError(): Exception

### Parameters

This function has no parameters.

### Return Values

Returns the Exception associated with the failed heartbeat.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The extension does not use the streaming protocol for monitoring, so this method will always return `false`.

### Parameters

This function has no parameters.

### Return Values

Returns `false`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError — Returns the Exception associated with the failed heartbeat
- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

# The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class encapsulates information about a started server heartbeat (i.e. » hello command issued through » server monitoring).

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent {
/* Methods */
final public getHost(): string
final public getPort(): int
final public isAwaited(): bool
}

# MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The extension does not use the streaming protocol for monitoring, so this method will always return `false`.

### Parameters

This function has no parameters.

### Return Values

Returns `false`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

# The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class encapsulates information about a successful server heartbeat (i.e. » hello command issued through » server monitoring).

## Class synopsis

final class MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent {
/* Methods */
final public getDurationMicros(): int
final public getHost(): string
final public getPort(): int
final public getReply(): object
final public isAwaited(): bool
}

# MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros — Returns the heartbeat's duration in microseconds

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros(): int

The heartbeat's duration is a calculated value that includes the time to send the message and receive the reply from the server.

### Parameters

This function has no parameters.

### Return Values

Returns the heartbeat's duration in microseconds.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost — Returns the hostname of the server

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost(): string

### Parameters

This function has no parameters.

### Return Values

Returns the hostname of the server.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort — Returns the port on which this server is listening

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort(): int

### Parameters

This function has no parameters.

### Return Values

Returns the port on which this server is listening.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply — Returns the heartbeat reply document

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

### Parameters

This function has no parameters.

### Return Values

Returns the heartbeat reply document as a stdClass object.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- Application Performance Monitoring (APM)
- Persisting Data

# MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

### Description

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The extension does not use the streaming protocol for monitoring, so this method will always return `false`.

### Parameters

This function has no parameters.

### Return Values

Returns `false`.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost — Returns the hostname of the server
- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply — Returns the heartbeat reply document
- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

# The MongoDB\Driver\Monitoring\TopologyChangedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\TopologyChangedEvent class encapsulates information about a changed topology description. For example, a topology discovering a new replica set primary would cause its topology description to change.

## Class synopsis

final class MongoDB\Driver\Monitoring\TopologyChangedEvent {
/* Methods */
final public getNewDescription(): MongoDB\Driver\TopologyDescription
final public getPreviousDescription(): MongoDB\Driver\TopologyDescription
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription — Returns the new description for the topology

### Description

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription(): MongoDB\Driver\TopologyDescription

### Parameters

This function has no parameters.

### Return Values

Returns the new MongoDB\Driver\TopologyDescription for the topology.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription — Returns the previous description for the topology

### Description

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription(): MongoDB\Driver\TopologyDescription

### Parameters

This function has no parameters.

### Return Values

Returns the previous MongoDB\Driver\TopologyDescription for the topology.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

# MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId — Returns the topology ID

### Description

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription — Returns the new description for the topology
- MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription — Returns the previous description for the topology
- MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId — Returns the topology ID

# The MongoDB\Driver\Monitoring\TopologyClosedEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\TopologyClosedEvent class encapsulates information about a closed topology.

> Note: Due to the driver's connection handling and persistence behavior, this event can only be observed when a MongoDB\Driver\Manager is created with the `"disableClientPersistence"` driver option and freed before request shutdown (RSHUTDOWN).

## Class synopsis

final class MongoDB\Driver\Monitoring\TopologyClosedEvent {
/* Methods */
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId — Returns the topology ID

### Description

final public MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId — Returns the topology ID

# The MongoDB\Driver\Monitoring\TopologyOpeningEvent class

(mongodb >=1.13.0)

## Introduction

The MongoDB\Driver\Monitoring\TopologyOpeningEvent class encapsulates information about an opened topology.

> Note: Due to the driver's connection handling and persistence behavior, this event may not be observed if a MongoDB\Driver\Manager uses a previously persisted » libmongoc client.

## Class synopsis

final class MongoDB\Driver\Monitoring\TopologyOpeningEvent {
/* Methods */
final public getTopologyId(): MongoDB\BSON\ObjectId
}

# MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId — Returns the topology ID

### Description

final public MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId(): MongoDB\BSON\ObjectId

### Parameters

This function has no parameters.

### Return Values

Returns the topology ID.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

## Table of Contents

- MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId — Returns the topology ID

# The MongoDB\Driver\Monitoring\CommandSubscriber interface

(mongodb >=1.3.0)

## Introduction

Classes may implement this interface to register an event subscriber that is notified for each started, successful, and failed command event. See Application Performance Monitoring (APM) for additional information.

## Interface synopsis

class MongoDB\Driver\Monitoring\CommandSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* Methods */
abstract public commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent `$event`): void
abstract public commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent `$event`): void
abstract public commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent `$event`): void
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command

### Description

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent `$event`): void

If the subscriber is registered, this method is called when a command fails.

### Parameters

`event` (MongoDB\Driver\Monitoring\CommandFailedEvent)

  An event object encapsulating information about the failed command.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandFailedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command

### Description

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent `$event`): void

If the subscriber is registered, this method is called when a command is sent to the server.

### Parameters

`event` (MongoDB\Driver\Monitoring\CommandStartedEvent)

  An event object encapsulating information about the started command.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandStartedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
- Application Performance Monitoring (APM)

# MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command

### Description

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent `$event`): void

If the subscriber is registered, this method is called when a command succeeds.

### Parameters

`event` (MongoDB\Driver\Monitoring\CommandSucceededEvent)

  An event object encapsulating information about the successful command.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\CommandSucceededEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
- Application Performance Monitoring (APM)

## Table of Contents

- MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command
- MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command
- MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command

# The MongoDB\Driver\Monitoring\LogSubscriber interface

(mongodb >=1.17.0)

## Introduction

Classes implementing this interface may be registered as a subscriber and receive log messages from the extension. This is similar to stream-based debug logging (i.e. mongodb.debug) except that trace-level log messages are not received.

As with stream-based logging, it is only possible to register a logger globally using MongoDB\Driver\Monitoring\addSubscriber(). The extension is not able to distinguish log messages for individual MongoDB\Driver\Manager objects.

## Interface synopsis

class MongoDB\Driver\Monitoring\LogSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* Constants */
const int LEVEL_ERROR = 0;
const int LEVEL_CRITICAL = 1;
const int LEVEL_WARNING = 2;
const int LEVEL_MESSAGE = 3;
const int LEVEL_INFO = 4;
const int LEVEL_DEBUG = 5;
/* Methods */
abstract public log(int `$level`, string `$domain`, string `$message`): void
}

## Predefined Constants

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_ERROR`

  Error log level. An error condition that the extension is unable to report through its API. This is the most severe log level in the extension.

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_CRITICAL`

  Critical log level. An error condition with slightly less severity. This constant exists for consistency with libmongoc; however, the extension is unlikely to use it in practice.

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_WARNING`

  Warning log level. Indicates a situation where undesirable application behavior may occur.

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_MESSAGE`

  Message or notice log level. Indicates an event that is unusual but not problematic.

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_INFO`

  Info log level. High-level information about normal driver behavior.

`MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_DEBUG`

  Debug log level. Detailed information that may be helpful when debugging an application.

# MongoDB\Driver\Monitoring\LogSubscriber::log

(mongodb >=1.17.0)

MongoDB\Driver\Monitoring\LogSubscriber::log — Notification method for a log message

### Description

abstract public MongoDB\Driver\Monitoring\LogSubscriber::log(int `$level`, string `$domain`, string `$message`): void

If the subscriber is registered, this method is called for each logged message.

### Parameters

`level`

  The severity level. This will be one of the interface constants.

`domain`

  The name of the driver component that emitted the log message.

`message`

  The log message.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally

## Table of Contents

- MongoDB\Driver\Monitoring\LogSubscriber::log — Notification method for a log message

# The MongoDB\Driver\Monitoring\SDAMSubscriber interface

(mongodb >=1.13.0)

## Introduction

Classes may implement this interface to register an event subscriber that is notified for various SDAM events. See the » Server Discovery and Monitoring and » SDAM Monitoring specifications for additional information.

## Interface synopsis

class MongoDB\Driver\Monitoring\SDAMSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* Methods */
abstract public serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent `$event`): void
abstract public serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent `$event`): void
abstract public serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent `$event`): void
abstract public serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent `$event`): void
abstract public serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent `$event`): void
abstract public serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent `$event`): void
abstract public topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent `$event`): void
abstract public topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent `$event`): void
abstract public topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent `$event`): void
}

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | Return types previously declared as tentative are now enforced.
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice.

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged — Notification method for a server description change

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent `$event`): void

If the subscriber is registered, this method is called when a server's description changes. For example, a server's type changing from secondary to primary would cause its server description to change.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerChangedEvent)

  An event object encapsulating information about the changed server description.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerChangedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed — Notification method for closing a server

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent `$event`): void

If the subscriber is registered, this method is called when an existing server is removed from the topology.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerClosedEvent)

  An event object encapsulating information about the closed server.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerClosedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed — Notification method for a failed server heartbeat

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent `$event`): void

If the subscriber is registered, this method is called when a server heartbeat (i.e. » hello command issued through » server monitoring) fails.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent)

  An event object encapsulating information about the failed server heartbeat.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted — Notification method for a started server heartbeat

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent `$event`): void

If the subscriber is registered, this method is called when a server heartbeat (i.e. » hello command issued through » server monitoring) is sent to the server.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent)

  An event object encapsulating information about the started server heartbeat.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded — Notification method for a successful server heartbeat

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent `$event`): void

If the subscriber is registered, this method is called when a server heartbeat (i.e. » hello command issued through » server monitoring) succeeds.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent)

  An event object encapsulating information about the successful server heartbeat.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening — Notification method for opening a server

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent `$event`): void

If the subscriber is registered, this method is called when a new server is added to the topology.

### Parameters

`event` (MongoDB\Driver\Monitoring\ServerOpeningEvent)

  An event object encapsulating information about the opened server.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\ServerOpeningEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged — Notification method for a topology description change

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent `$event`): void

If the subscriber is registered, this method is called when the topology's description changes. For example, a topology discovering a new replica set primary would cause its topology description to change.

### Parameters

`event` (MongoDB\Driver\Monitoring\TopologyChangedEvent)

  An event object encapsulating information about the changed topology description.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\TopologyChangedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed — Notification method for closing the topology

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent `$event`): void

If the subscriber is registered, this method is called when the topology is closed.

> Note: Due to the driver's connection handling and persistence behavior, this event can only be observed when a MongoDB\Driver\Manager is created with the `"disableClientPersistence"` driver option and freed before request shutdown (RSHUTDOWN).

### Parameters

`event` (MongoDB\Driver\Monitoring\TopologyClosedEvent)

  An event object encapsulating information about the closed topology.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\TopologyClosedEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

# MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening — Notification method for opening the topology

### Description

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent `$event`): void

If the subscriber is registered, this method is called when the topology is opened.

> Note: Due to the driver's connection handling and persistence behavior, this event may not be observed if a MongoDB\Driver\Manager uses a previously persisted » libmongoc client.

### Parameters

`event` (MongoDB\Driver\Monitoring\TopologyOpeningEvent)

  An event object encapsulating information about the opened topology.

### Return Values

No value is returned.

### Errors/Exceptions

- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

### See Also

- MongoDB\Driver\Monitoring\TopologyOpeningEvent
- MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
- MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

## Table of Contents

- MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged — Notification method for a server description change
- MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed — Notification method for closing a server
- MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed — Notification method for a failed server heartbeat
- MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted — Notification method for a started server heartbeat
- MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded — Notification method for a successful server heartbeat
- MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening — Notification method for opening a server
- MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged — Notification method for a topology description change
- MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed — Notification method for closing the topology
- MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening — Notification method for opening the topology

# The MongoDB\Driver\Monitoring\Subscriber interface

(mongodb >=1.3.0)

## Introduction

Base interface for event subscribers. This is used as a parameter type in the functions MongoDB\Driver\Monitoring\addSubscriber() and MongoDB\Driver\Monitoring\removeSubscriber() and should not be implemented directly.

## Interface synopsis

class MongoDB\Driver\Monitoring\Subscriber {
}

This interface has no methods. Its only purpose is to be the base interface for all event subscribers.

# Exception classes

## Table of Contents

- MongoDB\Driver\Exception\AuthenticationException
- MongoDB\Driver\Exception\BulkWriteException
- MongoDB\Driver\Exception\BulkWriteCommandException
- MongoDB\Driver\Exception\CommandException
- MongoDB\Driver\Exception\ConnectionException
- MongoDB\Driver\Exception\ConnectionTimeoutException
- MongoDB\Driver\Exception\EncryptionException
- MongoDB\Driver\Exception\Exception
- MongoDB\Driver\Exception\ExecutionTimeoutException
- MongoDB\Driver\Exception\InvalidArgumentException
- MongoDB\Driver\Exception\LogicException
- MongoDB\Driver\Exception\RuntimeException
- MongoDB\Driver\Exception\ServerException
- MongoDB\Driver\Exception\SSLConnectionException
- MongoDB\Driver\Exception\UnexpectedValueException
- MongoDB\Driver\Exception\WriteException
- Class Tree

# The MongoDB\Driver\Exception\AuthenticationException class

(mongodb >= 1.0.0)

## Introduction

Thrown when the driver fails to authenticate with the server.

## Class synopsis

class MongoDB\Driver\Exception\AuthenticationException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\BulkWriteException class

(mongodb >= 1.0.0)

## Introduction

Thrown when a bulk write operation fails.

## Class synopsis

class MongoDB\Driver\Exception\BulkWriteException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected MongoDB\Driver\WriteResult $writeResult;
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
final public getWriteResult(): MongoDB\Driver\WriteResult
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

writeResult

  The MongoDB\Driver\WriteResult associated with the failed write operation.

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\WriteException.

# MongoDB\Driver\Exception\BulkWriteException::getWriteResult

(mongodb >= 1.0.0)

MongoDB\Driver\Exception\BulkWriteException::getWriteResult — Returns the WriteResult for the failed write operation

### Description

final public MongoDB\Driver\Exception\BulkWriteException::getWriteResult(): MongoDB\Driver\WriteResult

Returns the MongoDB\Driver\WriteResult for the failed write operation. The MongoDB\Driver\WriteResult::getWriteErrors() and MongoDB\Driver\WriteResult::getWriteConcernError() methods may be used to get more details about the failure.

### Parameters

This function has no parameters.

### Return Values

The MongoDB\Driver\WriteResult for the failed write operation.

### Examples

Example #1 MongoDB\Driver\Exception\BulkWriteException::getWriteResult() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$writeResult = $e->getWriteResult();
if ($writeConcernError = $writeResult->getWriteConcernError()) {
var_dump($writeConcernError);
}
if ($writeErrors = $writeResult->getWriteErrors()) {
var_dump($writeErrors);
}
}
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(1)
        ["info"]=>
        NULL
      }
    }

### See Also

- MongoDB\Driver\WriteResult
- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations

## Table of Contents

- MongoDB\Driver\Exception\BulkWriteException::getWriteResult — Returns the WriteResult for the failed write operation

# The MongoDB\Driver\Exception\BulkWriteCommandException class

(mongodb >=2.1.0)

## Introduction

Exception thrown due to failed execution of a MongoDB\Driver\BulkWriteCommand. The methods of this class provide more details of the error that occurred, including the error reply and partial results from the bulk write.

## Class synopsis

class MongoDB\Driver\Exception\BulkWriteCommandException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
private ?MongoDB\BSON\Document $errorReply;
private ?MongoDB\Driver\BulkWriteCommandResult $partialResult;
private array $writeConcernErrors;
private array $writeErrors;
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
final public getErrorReply(): ?MongoDB\BSON\Document
final public getPartialResult(): ?MongoDB\Driver\BulkWriteCommandResult
final public getWriteConcernErrors(): array
final public getWriteErrors(): array
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

errorReply

  Any top-level error that occurred when attempting to communicate with the server or execute the bulk write. This value may be `null` if the exception was thrown due to errors occurring on individual writes.

partialResult

  A MongoDB\Driver\BulkWriteCommandResult reporting the result of any successful operations that were performed before the error was encountered. This value may be `null` if it cannot be determined that at least one write was successfully performed (and acknowledged).

writeConcernErrors

  An array of any MongoDB\Driver\WriteConcernErrors that occurred while executing the bulk write. This list may have multiple items if more than one server command was required to execute the bulk write.

writeErrors

  An array of any MongoDB\Driver\WriteErrors that occurred during the execution of individual write operations. Array keys will correspond to the index of the write operation from MongoDB\Driver\BulkWriteCommand. This map will contain at most one entry if the bulk write was ordered.

# MongoDB\Driver\Exception\BulkWriteCommandException::getErrorReply

(mongodb >=2.1.0)

MongoDB\Driver\Exception\BulkWriteCommandException::getErrorReply — Returns any top-level command error

### Description

final public MongoDB\Driver\Exception\BulkWriteCommandException::getErrorReply(): ?MongoDB\BSON\Document

### Parameters

This function has no parameters.

### Return Values

Returns any top-level error that occurred when attempting to communicate with the server or execute the bulk write. This value may be `null` if the exception was thrown due to errors occurring on individual writes.

### Examples

Example #1 MongoDB\Driver\Exception\BulkWriteCommandException::getErrorReply() example

`<?php
$manager = new MongoDB\Driver\Manager;
// This example uses configureFailPoint to simulate a top-level command error
$manager->executeCommand('admin', new MongoDB\Driver\Command([
'configureFailPoint' => 'failCommand',
'mode' => ['times' => 1],
'data' => [
'failCommands' => ['bulkWrite'],
'errorCode' => 8, /* UnknownError */
],
]));
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
var_dump($e->getErrorReply()?->toPHP());
}
?>`

The above example will output something similar to:

    object(stdClass)#12 (6) {
      ["ok"]=>
      float(0)
      ["errmsg"]=>
      string(43) "Failing command via 'failCommand' failpoint"
      ["code"]=>
      int(8)
      ["codeName"]=>
      string(12) "UnknownError"
      ["$clusterTime"]=>
      object(stdClass)#10 (2) {
        ["clusterTime"]=>
        object(MongoDB\BSON\Timestamp)#6 (2) {
          ["increment"]=>
          string(1) "7"
          ["timestamp"]=>
          string(10) "1744319389"
        }
        ["signature"]=>
        object(stdClass)#9 (2) {
          ["hash"]=>
          object(MongoDB\BSON\Binary)#7 (2) {
            ["data"]=>
            string(20) ""
            ["type"]=>
            int(0)
          }
          ["keyId"]=>
          object(MongoDB\BSON\Int64)#8 (1) {
            ["integer"]=>
            string(1) "0"
          }
        }
      }
      ["operationTime"]=>
      object(MongoDB\BSON\Timestamp)#11 (2) {
        ["increment"]=>
        string(1) "7"
        ["timestamp"]=>
        string(10) "1744319389"
      }
    }

### See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command

# MongoDB\Driver\Exception\BulkWriteCommandException::getPartialResult

(mongodb >=2.1.0)

MongoDB\Driver\Exception\BulkWriteCommandException::getPartialResult — Returns the result of any successful write operations

### Description

final public MongoDB\Driver\Exception\BulkWriteCommandException::getPartialResult(): ?MongoDB\Driver\BulkWriteCommandResult

### Parameters

This function has no parameters.

### Return Values

Returns a MongoDB\Driver\BulkWriteCommandResult reporting the result of any successful operations that were performed before the error was encountered. The return value will be `null` if it cannot be determined that at least one write was successfully performed (and acknowledged).

### Examples

Example #1 Partial result if at least one write is successful

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteMany('db.coll', []);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 1]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
$result = $e->getPartialResult();
}
var_dump($result?->getInsertedCount());
?>`

The above example will output:

    int(1)

Example #2 No partial result if no writes are successful

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->deleteMany('db.coll', []);
$bulk->insertOne('db.coll', ['_id' => 1]);
$manager->executeBulkWriteCommand($bulk);
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['_id' => 1]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
$result = $e->getPartialResult();
}
var_dump($result?->getInsertedCount());
?>`

The above example will output:

    NULL

### See Also

- MongoDB\Driver\BulkWriteCommandResult
- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command

# MongoDB\Driver\Exception\BulkWriteCommandException::getWriteConcernErrors

(mongodb >=2.1.0)

MongoDB\Driver\Exception\BulkWriteCommandException::getWriteConcernErrors — Returns any write concern errors

### Description

final public MongoDB\Driver\Exception\BulkWriteCommandException::getWriteConcernErrors(): array

### Parameters

This function has no parameters.

### Return Values

An array of any MongoDB\Driver\WriteConcernErrors that occurred while executing the bulk write. This list may have multiple items if more than one server command was required to execute the bulk write.

### Examples

Example #1 MongoDB\Driver\Exception\BulkWriteCommandException::getWriteConcernErrors() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand;
$bulk->insertOne('db.coll', ['x' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(50);
try {
$result = $manager->executeBulkWriteCommand($bulk, ['writeConcern' => $writeConcern]);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
var_dump($e->getWriteConcernErrors());
}
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      object(MongoDB\Driver\WriteConcernError)#6 (3) {
        ["message"]=>
        string(29) "Not enough data-bearing nodes"
        ["code"]=>
        int(100)
        ["info"]=>
        object(stdClass)#8 (1) {
          ["writeConcern"]=>
          object(stdClass)#7 (3) {
            ["w"]=>
            int(50)
            ["wtimeout"]=>
            int(0)
            ["provenance"]=>
            string(14) "clientSupplied"
          }
        }
      }
    }

### See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\WriteConcernError

# MongoDB\Driver\Exception\BulkWriteCommandException::getWriteErrors

(mongodb >=2.1.0)

MongoDB\Driver\Exception\BulkWriteCommandException::getWriteErrors — Returns any write errors

### Description

final public MongoDB\Driver\Exception\BulkWriteCommandException::getWriteErrors(): array

### Parameters

This function has no parameters.

### Return Values

An array of any MongoDB\Driver\WriteErrors that occurred during the execution of individual write operations. Array keys will correspond to the index of the write operation from MongoDB\Driver\BulkWriteCommand. This map will contain at most one entry if the bulk write was ordered.

### Examples

Example #1 MongoDB\Driver\Exception\BulkWriteCommandException::getWriteErrors() example

`<?php
$manager = new MongoDB\Driver\Manager;
$bulk = new MongoDB\Driver\BulkWriteCommand(['ordered' => false]);
$bulk->deleteMany('db.coll', []);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 1]);
$bulk->insertOne('db.coll', ['_id' => 1]);
try {
$result = $manager->executeBulkWriteCommand($bulk);
} catch (MongoDB\Driver\Exception\BulkWriteCommandException $e) {
var_dump($e->getWriteErrors());
}
?>`

The above example will output something similar to:

    array(2) {
      [2]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(78) "E11000 duplicate key error collection: db.coll index: _id_ dup key: { _id: 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(2)
        ["info"]=>
        object(stdClass)#6 (0) {
        }
      }
      [3]=>
      object(MongoDB\Driver\WriteError)#7 (4) {
        ["message"]=>
        string(78) "E11000 duplicate key error collection: db.coll index: _id_ dup key: { _id: 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(3)
        ["info"]=>
        object(stdClass)#8 (0) {
        }
      }
    }

### See Also

- MongoDB\Driver\Manager::executeBulkWriteCommand() - Execute write operations using the bulkWrite command
- MongoDB\Driver\WriteError

## Table of Contents

- MongoDB\Driver\Exception\BulkWriteCommandException::getErrorReply — Returns any top-level command error
- MongoDB\Driver\Exception\BulkWriteCommandException::getPartialResult — Returns the result of any successful write operations
- MongoDB\Driver\Exception\BulkWriteCommandException::getWriteConcernErrors — Returns any write concern errors
- MongoDB\Driver\Exception\BulkWriteCommandException::getWriteErrors — Returns any write errors

# The MongoDB\Driver\Exception\CommandException class

(mongodb >= 1.5.0)

## Introduction

Thrown when a command fails.

## Class synopsis

class MongoDB\Driver\Exception\CommandException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected object $resultDocument;
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
final public getResultDocument(): object
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

resultDocument

  The result document associated with the failed command.

# MongoDB\Driver\Exception\CommandException::getResultDocument

(mongodb >= 1.5.0)

MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command

### Description

final public MongoDB\Driver\Exception\CommandException::getResultDocument(): object

Returns the result document for the failed command.

### Parameters

This function has no parameters.

### Return Values

The result document for the failed command.

### See Also

- MongoDB\Driver\Manager::executeCommand() - Execute a database command

## Table of Contents

- MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command

# The MongoDB\Driver\Exception\ConnectionException class

(mongodb >= 1.0.0)

## Introduction

Base class for exceptions thrown when the driver fails to establish a database connection.

## Class synopsis

class MongoDB\Driver\Exception\ConnectionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\ConnectionTimeoutException class

(mongodb >= 1.0.0)

## Introduction

Thrown when the driver fails to establish a database connection within a specified time limit (connectTimeoutMS) or server selection fails (serverSelectionTimeoutMS).

## Class synopsis

final class MongoDB\Driver\Exception\ConnectionTimeoutException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\EncryptionException class

(mongodb >= 1.7.0)

## Introduction

Base class for exceptions thrown during client-side encryption.

## Class synopsis

class MongoDB\Driver\Exception\EncryptionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\Exception interface

(mongodb >= 1.0.0)

## Introduction

Common interface for all extension exceptions. This interface is also used by the library, and may be used to identify any exceptions originating from the MongoDB PHP driver (i.e. extension and library).

## Class synopsis

class MongoDB\Driver\Exception\Exception {
}

# The MongoDB\Driver\Exception\ExecutionTimeoutException class

(mongodb >= 1.0.0)

## Introduction

Thrown when a query or command fails to complete within a specified time limit (e.g. » maxTimeMS).

## Class synopsis

final class MongoDB\Driver\Exception\ExecutionTimeoutException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Changelog

Version | Description
--- | ---
PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException.

# The MongoDB\Driver\Exception\InvalidArgumentException class

(mongodb >= 1.0.0)

## Introduction

Thrown when a driver method is given invalid arguments (e.g. invalid option types).

## Class synopsis

class MongoDB\Driver\Exception\InvalidArgumentException extends InvalidArgumentException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\LogicException class

(mongodb >= 1.0.0)

## Introduction

Thrown when the driver is incorrectly used (e.g. rewinding a cursor).

## Class synopsis

class MongoDB\Driver\Exception\LogicException extends LogicException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\RuntimeException class

(mongodb >= 1.0.0)

## Introduction

Thrown when the driver encounters a runtime error (e.g. internal error from » libmongoc).

## Class synopsis

class MongoDB\Driver\Exception\RuntimeException extends RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected ?array $errorLabels;
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
final public hasErrorLabel(string `$errorLabel`): bool
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

errorLabels

  Contains an array of error labels to go with an exception. For example, error labels can be used to detect whether a transaction can be retried safely if the `TransientTransactionError` label is present. The existence of a specific error label should be tested for with the MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(), instead of interpreting this `errorLabels` property manually.

## Changelog

Version | Description
--- | ---
PECL mongodb 1.6.0 | The MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() method and MongoDB\Driver\Exception\RuntimeException::errorLabels property have been added.

# MongoDB\Driver\Exception\RuntimeException::hasErrorLabel

(mongodb >= 1.6.0)

MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception

### Description

final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool

Returns whether the `errorLabel` has been set for this exception. Error labels are set by either the server or the extension to indicate specific situations that may be handled by an application. A common situation might be determining whether to safely retry a transaction that failed due to a transient error (e.g. network error, transaction conflict). Examples of error labels are `TransientTransactionError` and `UnknownTransactionCommitResult`.

### Parameters

`errorLabel`

  The name of the `errorLabel` to test for.

### Return Values

Whether the given `errorLabel` is associated with this exception.

### See Also

- MongoDB\Driver\Session::commitTransaction() - Commits a transaction
- » MongoDB documentation on transactions

## Table of Contents

- MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception

# The MongoDB\Driver\Exception\ServerException class

(mongodb >= 1.5.0)

## Introduction

Base class for exceptions thrown by the server. The code of this exception and its subclasses will correspond to the original error code from the server.

## Class synopsis

class MongoDB\Driver\Exception\ServerException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\SSLConnectionException class

(mongodb >= 1.0.0)

Warning

This exception class is DEPRECATED as of extension version 1.5.0 and was removed in 2.0. This exception was never thrown by the extension. Applications should use MongoDB\Driver\Exception\ConnectionException instead.

## Introduction

Thrown when the driver fails to establish an SSL connection with the server.

## Class synopsis

final class MongoDB\Driver\Exception\SSLConnectionException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\UnexpectedValueException class

(mongodb >= 1.0.0)

## Introduction

Thrown when the driver encounters an unexpected value (e.g. during BSON serialization or deserialization).

## Class synopsis

class MongoDB\Driver\Exception\UnexpectedValueException extends UnexpectedValueException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The MongoDB\Driver\Exception\WriteException class

(mongodb >= 1.0.0)

Warning

This exception class is DEPRECATED as of extension version 1.20.0 and was removed in 2.0. This exception was never directly thrown by the extension. Applications should use MongoDB\Driver\Exception\BulkWriteException instead.

## Introduction

Base class for exceptions thrown by a failed write operation. The exception encapsulates a MongoDB\Driver\WriteResult object.

## Class synopsis

abstract class MongoDB\Driver\Exception\WriteException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected MongoDB\Driver\WriteResult $writeResult;
/* Inherited properties */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
final public getWriteResult(): MongoDB\Driver\WriteResult
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string `$errorLabel`): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

writeResult

  The MongoDB\Driver\WriteResult associated with the failed write operation.

## Changelog

Version | Description
--- | ---
PECL mongodb 2.0.0 | This class was removed.
PECL mongodb 1.20.0 | This class has been deprecated and will be removed in version 2.0.
PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException.

# MongoDB\Driver\Exception\WriteException::getWriteResult

(mongodb >= 1.0.0)

MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation

### Description

final public MongoDB\Driver\Exception\WriteException::getWriteResult(): MongoDB\Driver\WriteResult

Returns the MongoDB\Driver\WriteResult for the failed write operation. The MongoDB\Driver\WriteResult::getWriteErrors() and MongoDB\Driver\WriteResult::getWriteConcernError() methods may be used to get more details about the failure.

### Parameters

This function has no parameters.

### Return Values

The MongoDB\Driver\WriteResult for the failed write operation.

### Examples

Example #1 MongoDB\Driver\Exception\WriteException::getWriteResult() example

`<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\WriteException $e) {
$writeResult = $e->getWriteResult();
if ($writeConcernError = $writeResult->getWriteConcernError()) {
var_dump($writeConcernError);
}
if ($writeErrors = $writeResult->getWriteErrors()) {
var_dump($writeErrors);
}
}
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      object(MongoDB\Driver\WriteError)#5 (4) {
        ["message"]=>
        string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
        ["code"]=>
        int(11000)
        ["index"]=>
        int(1)
        ["info"]=>
        NULL
      }
    }

### See Also

- MongoDB\Driver\WriteResult
- MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations

## Table of Contents

- MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation

# MongoDB Exception Class Tree

The class hierarchy for MongoDB exceptions is modeled after that of the SPL Exceptions. Base classes extend their SPL counterpart and all exception classes in the extension implement the MongoDB\Driver\Exception\Exception interface.

- MongoDB\Driver\Exception\LogicException (extends LogicException)
- MongoDB\Driver\Exception\InvalidArgumentException (extends InvalidArgumentException)
- MongoDB\Driver\Exception\UnexpectedValueException (extends UnexpectedValueException)
- MongoDB\Driver\Exception\RuntimeException (extends RuntimeException)
  - MongoDB\Driver\Exception\ConnectionException
    - MongoDB\Driver\Exception\AuthenticationException
    - MongoDB\Driver\Exception\ConnectionTimeoutException
    - MongoDB\Driver\Exception\SSLConnectionException (deprecated)
  - MongoDB\Driver\Exception\EncryptionException
  - MongoDB\Driver\Exception\ServerException
    - MongoDB\Driver\Exception\BulkWriteCommandException
    - MongoDB\Driver\Exception\CommandException
    - MongoDB\Driver\Exception\ExecutionTimeoutException
    - MongoDB\Driver\Exception\WriteException (deprecated)
      - MongoDB\Driver\Exception\BulkWriteException

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Tutorials
  - Using the PHP Library for MongoDB (PHPLIB)
  - Application Performance Monitoring (APM)
- Driver Architecture and Internals — Explains the driver architecture, and special features
  - Architecture — Architecture Overview
  - Connections — Connection handling and persistence
  - Persisting Data — Serialization and deserialization of PHP variables into MongoDB
- Security
  - Request Injection Attacks
  - Script Injection Attacks
- MongoDB\Driver — MongoDB Extension Classes
  - MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
  - MongoDB\Driver\Command — The MongoDB\Driver\Command class
  - MongoDB\Driver\Query — The MongoDB\Driver\Query class
  - MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
  - MongoDB\Driver\BulkWriteCommand — The MongoDB\Driver\BulkWriteCommand class
  - MongoDB\Driver\Session — The MongoDB\Driver\Session class
  - MongoDB\Driver\ClientEncryption — The MongoDB\Driver\ClientEncryption class
  - MongoDB\Driver\ServerApi — The MongoDB\Driver\ServerApi class
  - MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
  - MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
  - MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
  - MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
  - MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
  - MongoDB\Driver\CursorInterface — The MongoDB\Driver\CursorInterface interface
  - MongoDB\Driver\Server — The MongoDB\Driver\Server class
  - MongoDB\Driver\ServerDescription — The MongoDB\Driver\ServerDescription class
  - MongoDB\Driver\TopologyDescription — The MongoDB\Driver\TopologyDescription class
  - MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
  - MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
  - MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
  - MongoDB\Driver\BulkWriteCommandResult — The MongoDB\Driver\BulkWriteCommandResult class
- MongoDB\BSON — MongoDB BSON Classes and Functions
  - Functions
  - MongoDB\BSON\Document — The MongoDB\BSON\Document class
  - MongoDB\BSON\PackedArray — The MongoDB\BSON\PackedArray class
  - MongoDB\BSON\Iterator — The MongoDB\BSON\Iterator class
  - MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
  - MongoDB\BSON\VectorType — The MongoDB\BSON\VectorType enum
  - MongoDB\BSON\Decimal128 — The MongoDB\BSON\Decimal128 class
  - MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
  - MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
  - MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
  - MongoDB\BSON\ObjectId — The MongoDB\BSON\ObjectId class
  - MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
  - MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
  - MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
  - MongoDB\BSON\Type — The MongoDB\BSON\Type interface
  - MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
  - MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
  - MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
  - MongoDB\BSON\BinaryInterface — The MongoDB\BSON\BinaryInterface interface
  - MongoDB\BSON\Decimal128Interface — The MongoDB\BSON\Decimal128Interface interface
  - MongoDB\BSON\JavascriptInterface — The MongoDB\BSON\JavascriptInterface interface
  - MongoDB\BSON\MaxKeyInterface — The MongoDB\BSON\MaxKeyInterface interface
  - MongoDB\BSON\MinKeyInterface — The MongoDB\BSON\MinKeyInterface interface
  - MongoDB\BSON\ObjectIdInterface — The MongoDB\BSON\ObjectIdInterface interface
  - MongoDB\BSON\RegexInterface — The MongoDB\BSON\RegexInterface interface
  - MongoDB\BSON\TimestampInterface — The MongoDB\BSON\TimestampInterface interface
  - MongoDB\BSON\UTCDateTimeInterface — The MongoDB\BSON\UTCDateTimeInterface interface
  - MongoDB\BSON\DBPointer — The MongoDB\BSON\DBPointer class
  - MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
  - MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class
  - MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class
- MongoDB\Driver\Monitoring — Monitoring classes and subscriber functions
  - Functions
  - MongoDB\Driver\Monitoring\CommandFailedEvent — The MongoDB\Driver\Monitoring\CommandFailedEvent class
  - MongoDB\Driver\Monitoring\CommandStartedEvent — The MongoDB\Driver\Monitoring\CommandStartedEvent class
  - MongoDB\Driver\Monitoring\CommandSucceededEvent — The MongoDB\Driver\Monitoring\CommandSucceededEvent class
  - MongoDB\Driver\Monitoring\ServerChangedEvent — The MongoDB\Driver\Monitoring\ServerChangedEvent class
  - MongoDB\Driver\Monitoring\ServerClosedEvent — The MongoDB\Driver\Monitoring\ServerClosedEvent class
  - MongoDB\Driver\Monitoring\ServerOpeningEvent — The MongoDB\Driver\Monitoring\ServerOpeningEvent class
  - MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class
  - MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class
  - MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class
  - MongoDB\Driver\Monitoring\TopologyChangedEvent — The MongoDB\Driver\Monitoring\TopologyChangedEvent class
  - MongoDB\Driver\Monitoring\TopologyClosedEvent — The MongoDB\Driver\Monitoring\TopologyClosedEvent class
  - MongoDB\Driver\Monitoring\TopologyOpeningEvent — The MongoDB\Driver\Monitoring\TopologyOpeningEvent class
  - MongoDB\Driver\Monitoring\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber interface
  - MongoDB\Driver\Monitoring\LogSubscriber — The MongoDB\Driver\Monitoring\LogSubscriber interface
  - MongoDB\Driver\Monitoring\SDAMSubscriber — The MongoDB\Driver\Monitoring\SDAMSubscriber interface
  - MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface
- MongoDB\Driver\Exception — Exception classes
  - MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
  - MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
  - MongoDB\Driver\Exception\BulkWriteCommandException — The MongoDB\Driver\Exception\BulkWriteCommandException class
  - MongoDB\Driver\Exception\CommandException — The MongoDB\Driver\Exception\CommandException class
  - MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
  - MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
  - MongoDB\Driver\Exception\EncryptionException — The MongoDB\Driver\Exception\EncryptionException class
  - MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
  - MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
  - MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
  - MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
  - MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
  - MongoDB\Driver\Exception\ServerException — The MongoDB\Driver\Exception\ServerException class
  - MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class
  - MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
  - MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
  - Class Tree — MongoDB Exception Class Tree

# MySQL Drivers and Plugins

PHP offers several MySQL drivers and plugins for accessing and handling MySQL.

The differences and functionality of the MySQL extensions are described within the overview of this section.

The extensions listed support the MySQL protocol. Examples of compatible database servers are » MariaDB Server, » MySQL Server, » Percona Server for MySQL, and » TiDB.

# Overview of the MySQL PHP drivers

# Introduction

There are several PHP APIs for accessing the MySQL database. Users can choose between the mysqli or PDO_MySQL extensions.

This guide explains the terminology used to describe each API, information about choosing which API to use, and also information to help choose which MySQL library to use with the API.

# Terminology overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two, the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term driver is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation, you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extension, `mysqli`, is implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

# Choosing an API

PHP offers different APIs to connect to MySQL. Below we show the APIs provided by the mysqli and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "user" and the password "password". And a query is run to greet the user.

Example #1 Comparing the MySQL APIs

`<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);`

Example #2 Comparing prepared statements

`<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$statement = $mysqli->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$result = $statement->get_result();
$row = $result->fetch_assoc();
echo htmlentities($row['District']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['District']);`

Feature comparison

The overall performance of both extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

| ext/mysqli | PDO_MySQL
--- | --- | ---
PHP version introduced | 5.0 | 5.1
Included with PHP 7.x and 8.x | Yes | Yes
Development status | Active | Active
Lifecycle | Active | Active
Recommended for new projects | Yes | Yes
OOP Interface | Yes | Yes
Procedural Interface | Yes | No
API supports non-blocking, asynchronous queries with mysqlnd | Yes | No
Persistent Connections | Yes | Yes
API supports Charsets | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes
API supports client-side Prepared Statements | No | Yes
API supports Stored Procedures | Yes | Yes
API supports Multiple Statements | Yes | Most
API supports Transactions | Yes | Yes
Transactions can be controlled with SQL | Yes | Yes
Supports all MySQL 5.1+ functionality | Yes | Most

# Choosing a library

The mysqli and PDO_MySQL PHP extensions are lightweight wrappers on top of a C client library. The extensions can either use the mysqlnd library or the `libmysqlclient` library. Choosing a library is a compile time decision.

The mysqlnd library is part of the PHP distribution. It offers features like lazy connections and query caching, features that are not available with libmysqlclient, so using the built-in mysqlnd library is highly recommended. See the mysqlnd documentation for additional details, and a listing of features and functionality that it offers.

Example #1 Configure commands for using mysqlnd or libmysqlclient

    // Recommended, compiles with mysqlnd
    $ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd

    // Alternatively recommended, compiles with mysqlnd
    $ ./configure --with-mysqli --with-pdo-mysql

    // Not recommended, compiles with libmysqlclient
    $ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config

Library feature comparison

It is recommended to use the mysqlnd library instead of the MySQL Client Server library (libmysqlclient). Both libraries are supported and constantly being improved.

| MySQL native driver (mysqlnd) | MySQL client server library (`libmysqlclient`)
--- | --- | ---
Part of the PHP distribution | Yes | No
PHP version introduced | 5.3.0 | N/A
License | PHP License 3.01 | Dual-License
Development status | Active | Active
Lifecycle | No end announced | No end announced
Compile default (for all MySQL extensions) | Yes | No
Compression protocol support | Yes | Yes
SSL support | Yes | Yes
Named pipe support | Yes | Yes
Non-blocking, asynchronous queries | Yes | No
Performance statistics | Yes | No
LOAD LOCAL INFILE respects the open_basedir directive | Yes | No
Uses PHP's native memory management system (e.g., follows PHP memory limits) | Yes | No
Return numeric column as double (COM_QUERY) | Yes | No
Return numeric column as string (COM_QUERY) | Yes | Yes
Plugin API | Yes | Limited
Automatic reconnect | No | Optional

# Concepts

## Table of Contents

- Buffered and Unbuffered queries
- Character sets

These concepts are specific to the MySQL drivers for PHP.

## Buffered and Unbuffered queries

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process. This allows additional operations like counting the number of rows, and moving (seeking) the current result pointer. It also allows issuing further queries on the same connection while working on the result set. The downside of the buffered mode is that larger result sets might require quite a lot memory. The memory will be kept occupied till all references to the result set are unset or the result set was explicitly freed, which will automatically happen during request end at the latest. The terminology "store result" is also used for buffered mode, as the whole result set is stored at once.

> Note: When using libmysqlclient as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

Unbuffered MySQL queries execute the query and then wait for the data from the MySQL server to be fetched. This uses less memory on the PHP-side, but can increase the load on the server. Unless the full result set was fetched from the server no further queries can be sent over the same connection. Unbuffered queries can also be referred to as "use result". Once all rows in the result set are fetched, the result set is gone and it cannot be iterated again.

Following these characteristics, unbuffered queries should be used only when a large result set is expected that will be processed sequentially. Unbuffered queries contain a number of pitfalls that makes it more difficult to use them, e.g. the number of rows in the result set is unknown until the last row is fetched. Buffered queries are the easier and more flexible way to process result sets.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

Example #1 Unbuffered query example: mysqli

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$unbufferedResult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);
foreach ($unbufferedResult as $row) {
echo $row['Name'] . PHP_EOL;
}
?>`

Example #2 Unbuffered query example: pdo_mysql

`<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_password');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$unbufferedResult = $pdo->query("SELECT Name FROM City");
foreach ($unbufferedResult as $row) {
echo $row['Name'] . PHP_EOL;
}
?>`

## Character sets

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

Caution

# The character set and character escaping

The character set should be understood and defined, as it has an affect on every action, and includes security implications. For example, the escaping mechanism (e.g., mysqli_real_escape_string() for mysqli and PDO::quote() for PDO_MySQL) will adhere to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

Example #1 Problems with setting the character set with SQL

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8mb4");
// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8mb4");
// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8mb4');
// But, this will NOT affect it (UTF-8 vs utf8mb4) -- don't use dashes here
$mysqli->set_charset('UTF-8');
?>`

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

> Note: Possible UTF-8 confusion
> Because character set names in MySQL do not contain dashes, the string "utf8" is valid in MySQL to set the character set to UTF-8 (up to 3 byte UTF-8 Unicode Encoding). The string "UTF-8" is not valid, as using "UTF-8" will fail to change the character set and will throw an error.

Example #2 Setting the character set example: mysqli

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
echo 'Initial character set: ' . $mysqli->character_set_name() . "\n";
if (!$mysqli->set_charset('utf8mb4')) {
printf("Error loading character set utf8mb4: %s\n", $mysqli->error);
exit;
}
echo 'Your current character set is: ' . $mysqli->character_set_name() . "\n";
?>`

Example #3 Setting the character set example: pdo_mysql

`<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8mb4", 'my_user', 'my_pass');
?>`

- Terminology overview
- Choosing an API
- Choosing a library
- Concepts
  - Buffered and Unbuffered queries
  - Character sets

# MySQL Improved Extension

# Introduction

The `mysqli` extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at » http://www.mysql.com/

An overview of software available for using MySQL from PHP can be found at Overview

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of Oracle Corporation.

Examples use either the » world or » sakila database, which are freely available.

# Overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API, you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two, the latter is usually the preferred interface, as it is more modern and leads to better-organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database, and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term driver is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the PDO MySQL driver extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

What are the main PHP API offerings for using MySQL?

There are two main API options when considering connecting to a MySQL database server:

- PHP's mysqli Extension

- PHP Data Objects (PDO)

Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API.

What is PHP's mysqli Extension?

The `mysqli` extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The `mysqli` extension is included with PHP versions 5 and later.

The `mysqli` extension has a number of benefits, the key enhancements over the `mysql` extension being:

- Object-oriented interface

- Support for Prepared Statements

- Support for Multiple Statements

- Support for Transactions

- Enhanced debugging capabilities

As well as the object-oriented interface the extension also provides a procedural interface.

The `mysqli` extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

For further information on the `mysqli` extension, see MySQLi.

What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.

Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.

PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.

For further information on PDO, see the PDO.

What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact, the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.

The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.

For further information on the PDO MYSQL driver, see MySQL PDO Driver.

What is PHP's MySQL Native Driver?

In order to communicate with the MySQL database server, `mysqli` and the PDO MYSQL driver each use a low-level library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as `libmysqlclient`.

However, the interface presented by `libmysqlclient` was not optimized for communication with PHP applications, as `libmysqlclient` was originally designed with C applications in mind. For this reason, the MySQL Native Driver, `mysqlnd`, was developed as an alternative to `libmysqlclient` for PHP applications.

Both, the `mysqli` extension and the PDO MySQL driver can each be individually configured to use either `libmysqlclient` or `mysqlnd`. As `mysqlnd` is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over `libmysqlclient`. You are strongly encouraged to take advantage of these improvements.

The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer.

Comparison of Features

The following table compares the functionality of the main methods of connecting to MySQL from PHP:

Comparison of MySQL API options for PHP
| PHP's mysqli Extension | PDO (Using PDO MySQL Driver and MySQL Native Driver)
--- | --- | ---
PHP version introduced | 5.0 | 5.0
MySQL development status | Active development | Active development
API supports Charsets | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes
API supports client-side Prepared Statements | No | Yes
API supports Stored Procedures | Yes | Yes
API supports Multiple Statements | Yes | Most
Supports all MySQL 4.1+ functionality | Yes | Most

# Quick start guide

## Table of Contents

- Dual procedural and object-oriented interface
- Connections
- Executing statements
- Prepared Statements
- Stored Procedures
- Multiple Statements
- API support for transactions
- Metadata

This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API.

This quick start gives an overview on the mysqli extension. Code examples are provided for all major aspects of the API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL.

Required: A familiarity with the PHP programming language, the SQL language, and basic knowledge of the MySQL server.

## Dual procedural and object-oriented interface

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigm.

Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension. In many cases, the function names differ only by prefix. Some mysqli functions take a connection handle as their first argument, whereas matching functions in the old mysql interface take it as an optional last argument.

Example #1 Easy migration from the old mysql extension

`<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Please do not use the deprecated mysql extension for new development. ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];
$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$result = mysql_query("SELECT 'Use the mysqli extension instead.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($result);
echo $row['_msg'];`

The above example will output:

    Please do not use the deprecated mysql extension for new development. Use the mysqli extension instead.

The object-oriented interface

In addition to the classical procedural interface, users can choose to use the object-oriented interface. The documentation is organized using the object-oriented interface. The object-oriented interface shows functions grouped by their purpose, making it easier to get started. The reference section gives examples for both syntax variants.

There are no significant performance differences between the two interfaces. Users can base their choice on personal preference.

Example #2 Object-oriented and procedural interface

`<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $result->fetch_assoc();
echo $row['_msg'];`

The above example will output:

    A world full of choices to please everybody.

The object-oriented interface is used for the quickstart because the reference section is organized that way.

Mixing styles

It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons.

Example #3 Bad coding style

`<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if ($row = $result->fetch_assoc()) {
echo $row['_msg'];
}`

The above example will output:

    Possible but bad style.

See also

- mysqli::__construct()
- mysqli::query()
- mysqli_result::fetch_assoc()
- $mysqli::connect_errno
- $mysqli::connect_error
- $mysqli::errno
- $mysqli::error
- The MySQLi Extension Function Summary

## Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname `localhost` has a special meaning. It is bound to the use of Unix domain sockets. To open a TCP/IP connection to the localhost, `127.0.0.1` must be used instead of the hostname `localhost`.

Example #1 Special meaning of localhost

`<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
echo $mysqli->host_info . "\n";`

The above example will output:

    Localhost via UNIX socket
    127.0.0.1 via TCP/IP

Connection parameter defaults

Depending on the connection function used, assorted parameters can be omitted. If a parameter is not provided, then the extension attempts to use the default values that are set in the PHP configuration file.

Example #2 Setting defaults

    mysqli.default_host=192.168.2.27
    mysqli.default_user=root
    mysqli.default_pw=""
    mysqli.default_port=3306
    mysqli.default_socket=/tmp/mysql.sock

The resulting parameter values are then passed to the client library that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.

Built-in connection library defaults

If the host value is unset or empty, then the client library will default to a Unix socket connection on `localhost`. If socket is unset or empty, and a Unix socket connection is requested, then a connection to the default socket on `/tmp/mysql.sock` is attempted.

On Windows systems, the host name `.` is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipe name. If not given or empty, then the socket (pipe name) defaults to `\\.\pipe\MySQL`.

If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port `3306`.

The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.

Connection options

Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.

For setting a connection option, the connect operation has to be performed in three steps: creating a connection handle with mysqli_init() or mysqli::__construct(), setting the requested options using mysqli::options(), and establishing the network connection with mysqli::real_connect().

Connection pooling

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.

Persistent connection

If an unused persistent connection for a given combination of host, username, password, socket, port and default database cannot be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note that the web server may spawn many PHP processes.

A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name `persistent` may be understood as a promise that the state is persisted.

The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli::change_user() to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.

The mysqli::change_user() call is an expensive operation. For best performance, users may want to recompile the extension with the compile flag `MYSQLI_NO_CHANGE_USER_ON_PCONNECT` being set.

It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.

See also

- mysqli::__construct()
- mysqli_init()
- mysqli::options()
- mysqli::real_connect()
- mysqli::change_user()
- $mysqli::host_info
- MySQLi Configuration Options
- Persistent Database Connections

## Executing statements

Statements can be executed with the mysqli::query(), mysqli::real_query() and mysqli::multi_query(). The mysqli::query() function is the most common, and combines the executing statement with a buffered fetch of its result set, if any, in one call. Calling mysqli::query() is identical to calling mysqli::real_query() followed by mysqli::store_result().

Example #1 Executing queries

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");`

Buffered result sets

After statement execution, results can be either retrieved all at once or read row by row from the server. Client-side result set buffering allows the server to free resources associated with the statement's results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli::query() combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Example #2 Navigation through buffered results

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$result = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
echo "Reverse order...\n";
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
$row = $result->fetch_assoc();
echo " id = " . $row['id'] . "\n";
}
echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}`

The above example will output:

    Reverse order...
     id = 3
     id = 2
     id = 1
    Result set order...
     id = 1
     id = 2
     id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

Example #3 Navigation through unbuffered results

`<?php
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$result = $mysqli->use_result();
echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}`

Result set values data types

The mysqli::query(), mysqli::real_query() and mysqli::multi_query() functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command `COM_QUERY` and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

Example #4 Text protocol returns strings by default

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));`

The above example will output:

    id = 1 (string)
    label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the `MYSQLI_OPT_INT_AND_FLOAT_NATIVE` connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

Example #5 Native data types with mysqlnd and connection option

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));`

The above example will output:

    id = 1 (integer)
    label = a (string)

See also

- mysqli::__construct()
- mysqli::options()
- mysqli::real_connect()
- mysqli::query()
- mysqli::multi_query()
- mysqli::use_result()
- mysqli::store_result()

## Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency and protect against SQL injections.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with `?`.

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server executes the statement with the bound values using the previously created internal resources.

Example #1 Prepared statement

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$stmt->execute();`

Repeated execution

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

Example #2 INSERT prepared once, executed multiple times

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$data = [
1 => 'PHP',
2 => 'Java',
3 => 'C++'
];
foreach ($data as $id => $label) {
$stmt->execute();
}
$result = $mysqli->query('SELECT id, label FROM test');
var_dump($result->fetch_all(MYSQLI_ASSOC));`

The above example will output:

    array(3) {
      [0]=>
      array(2) {
        ["id"]=>
        string(1) "1"
        ["label"]=>
        string(3) "PHP"
      }
      [1]=>
      array(2) {
        ["id"]=>
        string(1) "2"
        ["label"]=>
        string(4) "Java"
      }
      [2]=>
      array(2) {
        ["id"]=>
        string(1) "3"
        ["label"]=>
        string(3) "C++"
      }
    }

Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the `SELECT` is not run as a prepared statement above.

Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, multi-INSERT requires fewer round-trips between the server and client than the prepared statement shown above.

Example #3 Less round trips using multi-INSERT SQL

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$values = [1, 2, 3, 4];
$stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?), (?), (?), (?)");
$stmt->bind_param('iiii', ...$values);
$stmt->execute();`

Result set values data types

The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. Client libraries receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL `INT` column will be provided as PHP integer variables.

Example #4 Native datatypes

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));`

The above example will output:

    id = 1 (integer)
    label = PHP (string)

This behavior differs from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.

Fetching results using bound variables

Results from prepared statements can either be retrieved by binding output variables, or by requesting a mysqli_result object.

Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.

Example #5 Output variable binding

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$stmt->bind_result($out_id, $out_label);
while ($stmt->fetch()) {
printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}`

The above example will output:

    id = 1 (integer), label = PHP (string)

Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by `mysqli`.

It is also possible to buffer the results of a prepared statement using mysqli_stmt::store_result().

Fetching results using mysqli_result interface

Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt::get_result() returns a buffered result set.

Example #6 Using mysqli_result to fetch results

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
var_dump($result->fetch_all(MYSQLI_ASSOC));`

The above example will output:

    array(1) {
      [0]=>
      array(2) {
        ["id"]=>
        int(1)
        ["label"]=>
        string(3) "PHP"
      }
    }

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

Example #7 Buffered result set for flexible read out

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP'), (2, 'Java'), (3, 'C++')");
$stmt = $mysqli->prepare("SELECT id, label FROM test");
$stmt->execute();
$result = $stmt->get_result();
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
var_dump($result->fetch_assoc());
}`

The above example will output:

    array(2) {
      ["id"]=>
      int(3)
      ["label"]=>
      string(3) "C++"
    }
    array(2) {
      ["id"]=>
      int(2)
      ["label"]=>
      string(4) "Java"
    }
    array(2) {
      ["id"]=>
      int(1)
      ["label"]=>
      string(3) "PHP"
    }

Escaping and SQL injection

Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt::bind_param() function for more information.

Such a separation is sometimes considered the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.

Client-side prepared statement emulation

The API does not include emulation for client-side prepared statement emulation.

See also

- mysqli::__construct()
- mysqli::query()
- mysqli::prepare()
- mysqli_stmt::prepare()
- mysqli_stmt::execute()
- mysqli_stmt::bind_param()
- mysqli_stmt::bind_result()

## Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The `CALL` SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have `IN`, `INOUT` and `OUT` parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the `CALL` statement. Please, make sure values are escaped correctly.

Example #1 Calling a stored procedure

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;");
$mysqli->query("CALL p(1)");
$result = $mysqli->query("SELECT id FROM test");
var_dump($result->fetch_assoc());`

The above example will output:

    array(1) {
      ["id"]=>
      string(1) "1"
    }

INOUT/OUT parameter

The values of `INOUT`/`OUT` parameters are accessed using session variables.

Example #2 Using session variables

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;');
$mysqli->query("SET @msg = ''");
$mysqli->query("CALL p(@msg)");
$result = $mysqli->query("SELECT @msg as _p_out");
$row = $result->fetch_assoc();
echo $row['_p_out'];`

The above example will output:

    Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli::query(). The mysqli::query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli::query() to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli::real_query() or mysqli::multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as `CALL`. Failing to fetch all result sets returned by a stored procedure causes an error.

Example #3 Fetching results from stored procedures

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$mysqli->multi_query("CALL p()");
do {
if ($result = $mysqli->store_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($mysqli->next_result());`

The above example will output:

    ---
    array(3) {
      [0]=>
      array(1) {
        [0]=>
        string(1) "1"
      }
      [1]=>
      array(1) {
        [0]=>
        string(1) "2"
      }
      [2]=>
      array(1) {
        [0]=>
        string(1) "3"
      }
    }
    ---
    array(3) {
      [0]=>
      array(1) {
        [0]=>
        string(1) "2"
      }
      [1]=>
      array(1) {
        [0]=>
        string(1) "3"
      }
      [2]=>
      array(1) {
        [0]=>
        string(1) "4"
      }
    }

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the `CALL` SQL statement.

Example #4 Stored Procedures and Prepared Statements

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($result = $stmt->get_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($stmt->next_result());`

The above example will output:

    ---
    array(3) {
      [0]=>
      array(1) {
        [0]=>
        int(1)
      }
      [1]=>
      array(1) {
        [0]=>
        int(2)
      }
      [2]=>
      array(1) {
        [0]=>
        int(3)
      }
    }
    ---
    array(3) {
      [0]=>
      array(1) {
        [0]=>
        int(2)
      }
      [1]=>
      array(1) {
        [0]=>
        int(3)
      }
      [2]=>
      array(1) {
        [0]=>
        int(4)
      }
    }

Of course, use of the bind API for fetching is supported as well.

Example #5 Stored Procedures and Prepared Statements using bind API

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($stmt->store_result()) {
$stmt->bind_result($id_out);
while ($stmt->fetch()) {
echo "id = $id_out\n";
}
}
} while ($stmt->next_result());`

The above example will output:

    id = 1
    id = 2
    id = 3
    id = 2
    id = 3
    id = 4

See also

- mysqli::query()
- mysqli::multi_query()
- mysqli::next_result()
- mysqli::more_results()

## Multiple Statements

MySQL optionally allows having multiple statements in one statement string, but it requires special handling.

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

Example #1 Multiple Statements

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
do {
if ($result = $mysqli->store_result()) {
var_dump($result->fetch_all(MYSQLI_ASSOC));
$result->free();
}
} while ($mysqli->next_result());`

The above example will output:

    array(1) {
      [0]=>
      array(1) {
        ["_num"]=>
        string(1) "0"
      }
    }
    array(1) {
      [0]=>
      array(1) {
        ["_num"]=>
        string(1) "1"
      }
    }

Security considerations

The API functions mysqli::query() and mysqli::real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the damage of accidental SQL injection attacks. An attacker may try to add statements such as `; DROP DATABASE mysql` or `; SELECT SLEEP(999)`. If the attacker succeeds in adding SQL to the statement string but mysqli::multi_query() is not used, the server will not execute the injected and malicious SQL statement.

Example #2 SQL Injection

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
?>`

The above example will output:

    PHP Fatal error:  Uncaught mysqli_sql_exception: You have an error in your SQL syntax;
    check the manual that corresponds to your MySQL server version for the right syntax to
    use near 'DROP TABLE mysql.user' at line 1

Prepared statements

Use of the multiple statement with prepared statements is not supported.

See also

- mysqli::query()
- mysqli::multi_query()
- mysqli::next_result()
- mysqli::more_results()

## API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the `autocommit` mode and for committing and rolling back transactions.

Example #1 Setting `autocommit` mode with SQL and through the API

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);
/* Won't be monitored and recognized by the replication and the load balancing plugin */
$mysqli->query('SET AUTOCOMMIT = 0');`

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting `autocommit` mode, committing or rolling back a transaction.

Example #2 Commit and rollback

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);
$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();
$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();`

Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.

See also

- mysqli::autocommit()
- mysqli::begin_transaction()
- mysqli::commit()
- mysqli::rollback()

## Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the `mysqli` interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

Example #1 Accessing result set meta data

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($result->fetch_fields());`

The above example will output:

    array(2) {
      [0]=>
      object(stdClass)#3 (13) {
        ["name"]=>
        string(4) "_one"
        ["orgname"]=>
        string(0) ""
        ["table"]=>
        string(0) ""
        ["orgtable"]=>
        string(0) ""
        ["def"]=>
        string(0) ""
        ["db"]=>
        string(0) ""
        ["catalog"]=>
        string(3) "def"
        ["max_length"]=>
        int(1)
        ["length"]=>
        int(1)
        ["charsetnr"]=>
        int(63)
        ["flags"]=>
        int(32897)
        ["type"]=>
        int(8)
        ["decimals"]=>
        int(0)
      }
      [1]=>
      object(stdClass)#4 (13) {
        ["name"]=>
        string(4) "_two"
        ["orgname"]=>
        string(0) ""
        ["table"]=>
        string(0) ""
        ["orgtable"]=>
        string(0) ""
        ["def"]=>
        string(0) ""
        ["db"]=>
        string(0) ""
        ["catalog"]=>
        string(3) "def"
        ["max_length"]=>
        int(5)
        ["length"]=>
        int(5)
        ["charsetnr"]=>
        int(8)
        ["flags"]=>
        int(1)
        ["type"]=>
        int(253)
        ["decimals"]=>
        int(31)
      }
    }

Prepared statements

Meta data of result sets created using prepared statements are accessed the same way. A suitable mysqli_result handle is returned by mysqli_stmt::result_metadata().

Example #2 Prepared statements metadata

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$result = $stmt->result_metadata();
var_dump($result->fetch_fields());`

See also

- mysqli::query()
- mysqli_result::fetch_fields()

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

In order to have these functions available, you must compile PHP with support for the mysqli extension.

MySQL 8

When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password plugin to mysql_native_password or else you will see errors similar to The server requested authentication method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.

This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP (mysqlnd) releases. Instead, change it by setting `default_authentication_plugin=mysql_native_password` in my.cnf. The caching_sha2_password plugin is fully supported as of PHP 7.4.4. For older releases, the mysql_xdevapi extension does support it.

## Installation

The `mysqli` extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.

## Installation on Linux

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for the MySQL extensions, the extension libraries themselves may need to be installed using an additional package. Check the package manager that comes with your chosen distribution for availability.

For example, on Ubuntu the `php5-mysql` package installs the ext/mysql, ext/mysqli, and pdo_mysql PHP extensions. On CentOS, the `php-mysql` package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

The MySQL Native Driver is the recommended client library option, as it results in improved performance and gives access to features not available when using the MySQL Client Library. Refer to What is PHP's MySQL Native Driver? for a brief overview of the advantages of MySQL Native Driver.

The `/path/to/mysql_config` represents the location of the `mysql_config` program that comes with MySQL Server.

mysqli compile time support matrix
PHP Version | Default | Configure Options: mysqlnd | Configure Options: `libmysqlclient` | Changelog
--- | --- | --- | --- | ---
5.4.x and above | mysqlnd | --with-mysqli | --with-mysqli=/path/to/mysql_config | mysqlnd is the default
5.3.x | libmysqlclient | --with-mysqli=mysqlnd | --with-mysqli=/path/to/mysql_config | mysqlnd is supported
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Not Available | --with-mysqli=/path/to/mysql_config | mysqlnd is not supported

Note that it is possible to freely mix MySQL extensions and client libraries. For example, it is possible to enable the MySQL extension to use the MySQL Client Library (libmysqlclient), while configuring the `mysqli` extension to use the MySQL Native Driver. However, all permutations of extension and client library are possible.

## Installation on Windows Systems

On Windows, php_mysqli.dll DLL must be enabled in php.ini.

As with enabling any PHP extension (such as php_mysqli.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example `extension_dir` value is c:\php\ext.

> Note:

> If when starting the web server an error similar to the following occurs: `"Unable to load dynamic library './php_mysqli.dll'"`, this is because php_mysqli.dll cannot be found by the system.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQLi Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mysqli.allow_local_infile | "0" | `INI_SYSTEM` | Before PHP 7.2.16 and 7.3.3 the default was "1".
mysqli.local_infile_directory |  | `INI_SYSTEM` | Available as of PHP 8.1.0.
mysqli.allow_persistent | "1" | `INI_SYSTEM` |
mysqli.max_persistent | "-1" | `INI_SYSTEM` |
mysqli.max_links | "-1" | `INI_SYSTEM` |
mysqli.default_port | "3306" | `INI_ALL` |
mysqli.default_socket | NULL | `INI_ALL` |
mysqli.default_host | NULL | `INI_ALL` |
mysqli.default_user | NULL | `INI_ALL` |
mysqli.default_pw | NULL | `INI_ALL` |
mysqli.reconnect | "0" | `INI_SYSTEM` | Removed as of PHP 8.2.0
mysqli.rollback_on_cached_plink | "0" | `INI_SYSTEM` |

For further details and definitions of the preceding INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

`mysqli.allow_local_infile` bool

  Allow accessing, from PHP's perspective, local files with LOAD DATA statements

`mysqli.local_infile_directory` string

  Allows restricting LOCAL DATA loading to files located in this designated directory.

`mysqli.allow_persistent` bool

  Enable the ability to create persistent connections using mysqli_connect().

`mysqli.max_persistent` int

  Maximum of persistent connections that can be made. Set to 0 for unlimited.

`mysqli.max_links` int

  The maximum number of MySQL connections per process.

`mysqli.default_port` int

  The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the `MYSQL_TCP_PORT` environment variable, the `mysql-tcp` entry in /etc/services or the compile-time `MYSQL_PORT` constant, in that order. Win32 will only use the `MYSQL_PORT` constant.

`mysqli.default_socket` string

  The default socket name to use when connecting to a local database server if no other socket name is specified.

`mysqli.default_host` string

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

`mysqli.default_user` string

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

`mysqli.default_pw` string

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

`mysqli.reconnect` int

  Automatically reconnect if the connection was lost.

  > Note: This php.ini setting had been ignored by the mysqlnd driver, and was removed as of PHP 8.2.0.

`mysqli.rollback_on_cached_plink` bool

  If this option is enabled, closing a persistent connection will rollback any pending transactions of this connection before it is put back into the persistent connection pool. Otherwise, pending transactions will be rolled back only when the connection is reused, or when it is actually closed.

Users cannot set `MYSQL_OPT_READ_TIMEOUT` through an API call or runtime configuration setting. Note that if it were possible there would be differences between how `libmysqlclient` and streams would interpret the value of `MYSQL_OPT_READ_TIMEOUT`.

# The mysqli Extension and Persistent Connections

The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.

Unlike the mysql extension, mysqli does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend `p:` to the hostname when connecting.

The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection as is. Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.

The persistent connection of the `mysqli` extension however provides built-in cleanup handling code. The cleanup carried out by `mysqli` includes:

- Rollback active transactions

- Close and drop temporary tables

- Unlock tables

- Reset session variables

- Close prepared statements (always happens with PHP)

- Close handler

- Release locks acquired with GET_LOCK()

This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.

The `mysqli` extension does this cleanup by automatically calling the C-API function `mysql_change_user()`.

The automatic cleanup feature has advantages and disadvantages though. The advantage is that the programmer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.

It is possible to switch off the automatic cleanup code, by compiling PHP with `MYSQLI_NO_CHANGE_USER_ON_PCONNECT` defined.

> Note:

> The `mysqli` extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

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

`MYSQLI_READ_DEFAULT_GROUP` (int)

  Read options from the named group from my.cnf or the file specified with `MYSQLI_READ_DEFAULT_FILE`.

`MYSQLI_READ_DEFAULT_FILE` (int)

  Read options from the named option file instead of from my.cnf.

`MYSQLI_OPT_CAN_HANDLE_EXPIRED_PASSWORDS` (int)
  Indicates to the server that the client can handle sandbox mode for expired passwords. Can be used with mysqli_options().
`MYSQLI_OPT_LOAD_DATA_LOCAL_DIR` (int)
  If enabled, this option specifies the directory from which client-side `LOCAL` data loading is permitted in `LOAD DATA LOCAL` statements.
`MYSQLI_OPT_CONNECT_TIMEOUT` (int)

  Connect timeout in seconds.

`MYSQLI_OPT_READ_TIMEOUT` (int)

  Command execution result timeout in seconds. Available as of PHP 7.2.0.

`MYSQLI_OPT_LOCAL_INFILE` (int)

  Enables command `LOAD LOCAL INFILE`.

`MYSQLI_OPT_INT_AND_FLOAT_NATIVE` (int)

  Convert integer and float columns back to PHP numbers. Only valid for mysqlnd.

`MYSQLI_OPT_NET_CMD_BUFFER_SIZE` (int)

  The size of the internal command/network buffer. Only valid for mysqlnd.

`MYSQLI_OPT_NET_READ_BUFFER_SIZE` (int)

  Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.

`MYSQLI_OPT_SSL_VERIFY_SERVER_CERT` (int)

`MYSQLI_INIT_COMMAND` (int)

  Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

`MYSQLI_CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS` (int)
  Indicates to the server that the client can handle sandbox mode for expired passwords. Can be used with mysqli_real_connect().
`MYSQLI_CLIENT_FOUND_ROWS` (int)
  Return number of matched rows, not the number of affected rows.
`MYSQLI_CLIENT_SSL_VERIFY_SERVER_CERT` (int)
  Verify server certificate.
`MYSQLI_CLIENT_SSL` (int)

  Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library.

`MYSQLI_CLIENT_COMPRESS` (int)

  Use compression protocol.

`MYSQLI_CLIENT_INTERACTIVE` (int)

  Allow `interactive_timeout` seconds (instead of `wait_timeout` seconds) of inactivity before closing the connection. The client's session `wait_timeout` variable will be set to the value of the session `interactive_timeout` variable.

`MYSQLI_CLIENT_IGNORE_SPACE` (int)

  Allow spaces after function names. Makes all functions names reserved words.

`MYSQLI_CLIENT_NO_SCHEMA` (int)

  Don't allow the `db_name.tbl_name.col_name` syntax.

`MYSQLI_CLIENT_MULTI_QUERIES`

  Allows multiple semicolon-delimited queries in a single mysqli_query() call.

`MYSQLI_STORE_RESULT` (int)

  For using buffered result sets. It has a value of `0`.

`MYSQLI_STORE_RESULT_COPY_DATA` (int)
  As of PHP 8.1, this constant no longer has any effect. Before PHP 8.1, this constant is used to copy results from the internal `mysqlnd` buffer into the PHP variables fetched. By default, `mysqlnd` will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier. Available with `mysqlnd` only. Deprecated as of PHP 8.4.0.
`MYSQLI_USE_RESULT` (int)

  For using unbuffered result sets. It has a value of `1`.

`MYSQLI_ASSOC` (int)

  Columns are returned into the array having the fieldname as the array index.

`MYSQLI_NUM` (int)

  Columns are returned into the array having an enumerated index.

`MYSQLI_BOTH` (int)

  Columns are returned into the array having both a numerical index and the fieldname as the associative index.

`MYSQLI_NOT_NULL_FLAG` (int)

  Indicates that a field is defined as `NOT NULL`.

`MYSQLI_PRI_KEY_FLAG` (int)

  Field is part of a primary index.

`MYSQLI_UNIQUE_KEY_FLAG` (int)

  Field is part of a unique index.

`MYSQLI_MULTIPLE_KEY_FLAG` (int)

  Field is part of an index.

`MYSQLI_BLOB_FLAG` (int)

  Field is defined as `BLOB`.

`MYSQLI_UNSIGNED_FLAG` (int)

  Field is defined as `UNSIGNED`.

`MYSQLI_ZEROFILL_FLAG` (int)

  Field is defined as `ZEROFILL`.

`MYSQLI_AUTO_INCREMENT_FLAG` (int)

  Field is defined as `AUTO_INCREMENT`.

`MYSQLI_TIMESTAMP_FLAG` (int)

  Field is defined as `TIMESTAMP`.

`MYSQLI_SET_FLAG` (int)

  Field is defined as `SET`.

`MYSQLI_NUM_FLAG` (int)

  Field is defined as `NUMERIC`.

`MYSQLI_PART_KEY_FLAG` (int)

  Field is part of an multi-index.

`MYSQLI_GROUP_FLAG` (int)

  Field is part of `GROUP BY`.

`MYSQLI_NO_DEFAULT_VALUE_FLAG` (int)
  A column has no `DEFAULT` clause in its definition. This does not apply to `NULL` or to `AUTO_INCREMENT` columns because such columns have a default value of `NULL` and an implied default value respectively.
`MYSQLI_TYPE_DECIMAL` (int)

  Field is defined as `DECIMAL`.

`MYSQLI_TYPE_NEWDECIMAL` (int)

  Precision math `DECIMAL` or `NUMERIC` field.

`MYSQLI_TYPE_BIT` (int)

  Field is defined as `BIT`.

`MYSQLI_TYPE_TINY` (int)

  Field is defined as `TINYINT`.

`MYSQLI_TYPE_SHORT` (int)

  Field is defined as `SMALLINT`.

`MYSQLI_TYPE_LONG` (int)

  Field is defined as `INT`.

`MYSQLI_TYPE_FLOAT` (int)

  Field is defined as `FLOAT`.

`MYSQLI_TYPE_DOUBLE` (int)

  Field is defined as `DOUBLE`.

`MYSQLI_TYPE_NULL` (int)

  Field is defined as `DEFAULT NULL`.

`MYSQLI_TYPE_TIMESTAMP` (int)

  Field is defined as `TIMESTAMP`.

`MYSQLI_TYPE_LONGLONG` (int)

  Field is defined as `BIGINT`.

`MYSQLI_TYPE_INT24` (int)

  Field is defined as `MEDIUMINT`.

`MYSQLI_TYPE_DATE` (int)

  Field is defined as `DATE`.

`MYSQLI_TYPE_TIME` (int)

  Field is defined as `TIME`.

`MYSQLI_TYPE_DATETIME` (int)

  Field is defined as `DATETIME`.

`MYSQLI_TYPE_YEAR` (int)

  Field is defined as `YEAR`.

`MYSQLI_TYPE_NEWDATE` (int)

  Field is defined as `DATE`.

`MYSQLI_TYPE_INTERVAL` (int)

  Alias of `MYSQLI_TYPE_ENUM`. Removed as of PHP 8.4.0.

`MYSQLI_TYPE_ENUM` (int)

  Field is defined as `ENUM`.

`MYSQLI_TYPE_SET` (int)

  Field is defined as `SET`.

`MYSQLI_TYPE_TINY_BLOB` (int)

  Field is defined as `TINYBLOB`.

`MYSQLI_TYPE_MEDIUM_BLOB` (int)

  Field is defined as `MEDIUMBLOB`.

`MYSQLI_TYPE_LONG_BLOB` (int)

  Field is defined as `LONGBLOB`.

`MYSQLI_TYPE_BLOB` (int)

  Field is defined as `BLOB`.

`MYSQLI_TYPE_VAR_STRING` (int)

  Field is defined as `VARCHAR`.

`MYSQLI_TYPE_STRING` (int)

  Field is defined as `CHAR` or `BINARY`.

`MYSQLI_TYPE_CHAR` (int)

  Field is defined as `TINYINT`. For `CHAR`, see `MYSQLI_TYPE_STRING`.

`MYSQLI_TYPE_GEOMETRY` (int)

  Field is defined as `GEOMETRY`.

`MYSQLI_TYPE_JSON` (int)

  Field is defined as `JSON`. Only valid for mysqlnd and MySQL 5.7.8 and up.

`MYSQLI_TYPE_VECTOR` (int)

  Field is defined as `VECTOR`.

`MYSQLI_NEED_DATA`

  More data available for bind variable.

`MYSQLI_ENUM_FLAG` (int)

  Field is defined as `ENUM`.

`MYSQLI_BINARY_FLAG` (int)

  Field is defined as `BINARY`.

`MYSQLI_CURSOR_TYPE_FOR_UPDATE` (int)

  Removed as of PHP 8.4.0.

`MYSQLI_CURSOR_TYPE_NO_CURSOR` (int)

`MYSQLI_CURSOR_TYPE_READ_ONLY` (int)

`MYSQLI_CURSOR_TYPE_SCROLLABLE` (int)

  Removed as of PHP 8.4.0.

`MYSQLI_STMT_ATTR_CURSOR_TYPE` (int)

`MYSQLI_STMT_ATTR_PREFETCH_ROWS` (int)

  Removed as of PHP 8.4.0.

`MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH` (int)

`MYSQLI_SET_CHARSET_NAME` (int)

`MYSQLI_REPORT_INDEX` (int)

  Report if no index or bad index was used in a query.

`MYSQLI_REPORT_ERROR` (int)

  Report errors from mysqli function calls.

`MYSQLI_REPORT_STRICT` (int)

  Throw a `mysqli_sql_exception` for errors instead of warnings.

`MYSQLI_REPORT_ALL` (int)

  Set all options on (report all).

`MYSQLI_REPORT_OFF` (int)

  Turns reporting off.

`MYSQLI_DEBUG_TRACE_ENABLED` (int)

  Is set to 1 if mysqli_debug() functionality is enabled.

`MYSQLI_SERVER_PUBLIC_KEY` (int)

`MYSQLI_REFRESH_GRANT` (int)

  Refreshes the grant tables. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_LOG` (int)

  Flushes the logs, like executing the `FLUSH LOGS` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_TABLES` (int)

  Flushes the table cache, like executing the `FLUSH TABLES` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_HOSTS` (int)

  Flushes the host cache, like executing the `FLUSH HOSTS` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_REPLICA` (int)

  Alias of `MYSQLI_REFRESH_SLAVE` constant. Available as of PHP 8.1.0. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_STATUS` (int)

  Reset the status variables, like executing the `FLUSH STATUS` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_THREADS` (int)

  Flushes the thread cache. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_SLAVE` (int)

  On a slave replication server: resets the master server information, and restarts the slave. Like executing the `RESET SLAVE` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_MASTER` (int)

  On a master replication server: removes the binary log files listed in the binary log index, and truncates the index file. Like executing the `RESET MASTER` SQL statement. Deprecated as of PHP 8.4.0.

`MYSQLI_REFRESH_BACKUP_LOG` (int)
  Closes and reopens the backup log files. Deprecated as of PHP 8.4.0.
`MYSQLI_TRANS_COR_AND_CHAIN` (int)

  Appends "AND CHAIN" to mysqli_commit() or mysqli_rollback().

`MYSQLI_TRANS_COR_AND_NO_CHAIN` (int)

  Appends "AND NO CHAIN" to mysqli_commit() or mysqli_rollback().

`MYSQLI_TRANS_COR_RELEASE` (int)

  Appends "RELEASE" to mysqli_commit() or mysqli_rollback().

`MYSQLI_TRANS_COR_NO_RELEASE` (int)

  Appends "NO RELEASE" to mysqli_commit() or mysqli_rollback().

`MYSQLI_TRANS_START_READ_ONLY` (int)

  Start the transaction as "START TRANSACTION READ ONLY" with mysqli_begin_transaction().

`MYSQLI_TRANS_START_READ_WRITE` (int)

  Start the transaction as "START TRANSACTION READ WRITE" with mysqli_begin_transaction().

`MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT` (int)

  Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

`MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT` (int)

  Requires MySQL 5.6.5 and up.

`MYSQLI_IS_MARIADB` (bool)

  Whether the mysqli extension has been built against a MariaDB client library. Available as of PHP 8.1.2.

`MYSQLI_ASYNC` (int)
  The query is performed asynchronously and no result set is immediately returned. Available with `mysqlnd` only.
`MYSQLI_ON_UPDATE_NOW_FLAG` (int)
  If a field is updated it will get the current time value.

# Notes

Some implementation notes:

1. Support was added for `MYSQL_TYPE_GEOMETRY` to the MySQLi extension in PHP 5.3.

2. Note there are different internal implementations within `libmysqlclient` and `mysqlnd` for handling columns of type `MYSQL_TYPE_GEOMETRY`. Generally speaking, `mysqlnd` will allocate significantly less memory. For example, if there is a `POINT` column in a result set, `libmysqlclient` may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a `POINT` column in memory. Memory allocation is much lower, less than 50 bytes, if using `mysqlnd`.

# The MySQLi Extension Function Summary

Summary of mysqli methods
mysqli Class
OOP Interface | Procedural Interface | Alias (Do not use) | Description
--- | --- | --- | ---
Properties
$mysqli::affected_rows | mysqli_affected_rows() | N/A | Gets the number of affected rows in a previous MySQL operation
$mysqli::client_info | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
$mysqli::client_version | mysqli_get_client_version() | N/A | Returns MySQL client version info as an integer
$mysqli::connect_errno | mysqli_connect_errno() | N/A | Returns the error code from last connect call
$mysqli::connect_error | mysqli_connect_error() | N/A | Returns a string description of the last connect error
$mysqli::errno | mysqli_errno() | N/A | Returns the error code for the most recent function call
$mysqli::error | mysqli_error() | N/A | Returns a string description of the last error
$mysqli::field_count | mysqli_field_count() | N/A | Returns the number of columns for the most recent query
$mysqli::host_info | mysqli_get_host_info() | N/A | Returns a string representing the type of connection used
$mysqli::protocol_version | mysqli_get_proto_info() | N/A | Returns the version of the MySQL protocol used
$mysqli::server_info | mysqli_get_server_info() | N/A | Returns the version of the MySQL server
$mysqli::server_version | mysqli_get_server_version() | N/A | Returns the version of the MySQL server as an integer
$mysqli::info | mysqli_info() | N/A | Retrieves information about the most recently executed query
$mysqli::insert_id | mysqli_insert_id() | N/A | Returns the auto generated id used in the last query
$mysqli::sqlstate | mysqli_sqlstate() | N/A | Returns the SQLSTATE error from previous MySQL operation
$mysqli::warning_count | mysqli_warning_count() | N/A | Returns the number of warnings from the last query for the given link
Methods
mysqli::autocommit() | mysqli_autocommit() | N/A | Turns on or off auto-committing database modifications
mysqli::change_user() | mysqli_change_user() | N/A | Changes the user of the specified database connection
mysqli::character_set_name() | mysqli_character_set_name() | N/A | Returns the default character set for the database connection
mysqli::close() | mysqli_close() | N/A | Closes a previously opened database connection
mysqli::commit() | mysqli_commit() | N/A | Commits the current transaction
mysqli::__construct() | mysqli_connect() | N/A | Open a new connection to the MySQL server [Note: static (i.e. class) method]
mysqli::debug() | mysqli_debug() | N/A | Performs debugging operations
mysqli::dump_debug_info() | mysqli_dump_debug_info() | N/A | Dump debugging information into the log
mysqli::get_charset() | mysqli_get_charset() | N/A | Returns a character set object
mysqli::get_connection_stats() | mysqli_get_connection_stats() | N/A | Returns client connection statistics. Available only with mysqlnd.
mysqli::get_client_info() | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
N/A | mysqli_get_client_stats() | N/A | Returns client per-process statistics. Available only with mysqlnd.
mysqli::get_server_info() | mysqli_get_server_info() | N/A | Returns a string representing the version of the MySQL server that the MySQLi extension is connected to
mysqli::get_warnings() | mysqli_get_warnings() | N/A | NOT DOCUMENTED
mysqli::init() | mysqli_init() | N/A | Initializes MySQLi and returns an object for use with mysqli_real_connect.
mysqli::kill() | mysqli_kill() | N/A | Asks the server to kill a MySQL thread
mysqli::more_results() | mysqli_more_results() | N/A | Check if there are any more query results from a multi query
mysqli::multi_query() | mysqli_multi_query() | N/A | Performs a query on the database
mysqli::next_result() | mysqli_next_result() | N/A | Prepare next result from multi_query
mysqli::options() | mysqli_options() | mysqli_set_opt() | Set options
mysqli::ping() | mysqli_ping() | N/A | Pings a server connection, or tries to reconnect if the connection has gone down
mysqli::prepare() | mysqli_prepare() | N/A | Prepare an SQL statement for execution
mysqli::query() | mysqli_query() | N/A | Performs a query on the database
mysqli::real_connect() | mysqli_real_connect() | N/A | Opens a connection to a mysql server
mysqli::real_escape_string(), mysqli::escape_string() | mysqli_real_escape_string() | mysqli_escape_string() | Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
mysqli::real_query() | mysqli_real_query() | N/A | Execute an SQL query
mysqli::refresh() | mysqli_refresh() | N/A | Flushes tables or caches, or resets the replication server information
mysqli::rollback() | mysqli_rollback() | N/A | Rolls back current transaction
mysqli::select_db() | mysqli_select_db() | N/A | Selects the default database for database queries
mysqli::set_charset() | mysqli_set_charset() | N/A | Sets the default client character set
mysqli::ssl_set() | mysqli_ssl_set() | N/A | Used for establishing secure connections using SSL
mysqli::stat() | mysqli_stat() | N/A | Gets the current system status
mysqli::stmt_init() | mysqli_stmt_init() | N/A | Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli::store_result() | mysqli_store_result() | N/A | Transfers a result set from the last query
mysqli::thread_id() | mysqli_thread_id() | N/A | Returns the thread ID for the current connection
mysqli::thread_safe() | mysqli_thread_safe() | N/A | Returns whether thread safety is given or not
mysqli::use_result() | mysqli_use_result() | N/A | Initiate a result set retrieval

Summary of mysqli_stmt methods
MySQL_STMT
OOP Interface | Procedural Interface | Alias (Do not use) | Description
--- | --- | --- | ---
Properties
$mysqli_stmt::affected_rows | mysqli_stmt_affected_rows() | N/A | Returns the total number of rows changed, deleted, or inserted by the last executed statement
$mysqli_stmt::errno | mysqli_stmt_errno() | N/A | Returns the error code for the most recent statement call
$mysqli_stmt::error | mysqli_stmt_error() | N/A | Returns a string description for last statement error
$mysqli_stmt::field_count | mysqli_stmt_field_count() | N/A | Returns the number of field in the given statement - not documented
$mysqli_stmt::insert_id | mysqli_stmt_insert_id() | N/A | Get the ID generated from the previous INSERT operation
$mysqli_stmt::num_rows | mysqli_stmt_num_rows() | N/A | Return the number of rows in statements result set
$mysqli_stmt::param_count | mysqli_stmt_param_count() | N/A | Returns the number of parameter for the given statement
$mysqli_stmt::sqlstate | mysqli_stmt_sqlstate() | N/A | Returns SQLSTATE error from previous statement operation
Methods
mysqli_stmt::attr_get() | mysqli_stmt_attr_get() | N/A | Used to get the current value of a statement attribute
mysqli_stmt::attr_set() | mysqli_stmt_attr_set() | N/A | Used to modify the behavior of a prepared statement
mysqli_stmt::bind_param() | mysqli_stmt_bind_param() | N/A | Binds variables to a prepared statement as parameters
mysqli_stmt::bind_result() | mysqli_stmt_bind_result() | N/A | Binds variables to a prepared statement for result storage
mysqli_stmt::close() | mysqli_stmt_close() | N/A | Closes a prepared statement
mysqli_stmt::data_seek() | mysqli_stmt_data_seek() | N/A | Seeks to an arbitrary row in statement result set
mysqli_stmt::execute() | mysqli_stmt_execute() | mysqli_execute() | Executes a prepared Query
mysqli_stmt::fetch() | mysqli_stmt_fetch() | N/A | Fetch results from a prepared statement into the bound variables
mysqli_stmt::free_result() | mysqli_stmt_free_result() | N/A | Frees stored result memory for the given statement handle
mysqli_stmt::get_result() | mysqli_stmt_get_result() | N/A | Gets a result set from a prepared statement. Available only with mysqlnd.
mysqli_stmt::get_warnings() | mysqli_stmt_get_warnings() | N/A | NOT DOCUMENTED
mysqli_stmt::more_results() | mysqli_stmt_more_results() | N/A | Checks if there are more query results from a multiple query
mysqli_stmt::next_result() | mysqli_stmt_next_result() | N/A | Reads the next result from a multiple query
mysqli_stmt::num_rows() | mysqli_stmt_num_rows() | N/A | See also property $mysqli_stmt::num_rows
mysqli_stmt::prepare() | mysqli_stmt_prepare() | N/A | Prepare an SQL statement for execution
mysqli_stmt::reset() | mysqli_stmt_reset() | N/A | Resets a prepared statement
mysqli_stmt::result_metadata() | mysqli_stmt_result_metadata() | N/A | Returns result set metadata from a prepared statement
mysqli_stmt::send_long_data() | mysqli_stmt_send_long_data() | N/A | Send data in blocks
mysqli_stmt::store_result() | mysqli_stmt_store_result() | N/A | Transfers a result set from a prepared statement

Summary of mysqli_result methods
mysqli_result
OOP Interface | Procedural Interface | Alias (Do not use) | Description
--- | --- | --- | ---
Properties
$mysqli_result::current_field | mysqli_field_tell() | N/A | Get current field offset of a result pointer
$mysqli_result::field_count | mysqli_num_fields() | N/A | Get the number of fields in a result
$mysqli_result::lengths | mysqli_fetch_lengths() | N/A | Returns the lengths of the columns of the current row in the result set
$mysqli_result::num_rows | mysqli_num_rows() | N/A | Gets the number of rows in a result
Methods
mysqli_result::data_seek() | mysqli_data_seek() | N/A | Adjusts the result pointer to an arbitrary row in the result
mysqli_result::fetch_all() | mysqli_fetch_all() | N/A | Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd.
mysqli_result::fetch_array() | mysqli_fetch_array() | N/A | Fetch a result row as an associative, a numeric array, or both
mysqli_result::fetch_assoc() | mysqli_fetch_assoc() | N/A | Fetch a result row as an associative array
mysqli_result::fetch_column() | mysqli_fetch_column() | N/A | Fetch a single column from the next row of a result set
mysqli_result::fetch_field_direct() | mysqli_fetch_field_direct() | N/A | Fetch meta-data for a single field
mysqli_result::fetch_field() | mysqli_fetch_field() | N/A | Returns the next field in the result set
mysqli_result::fetch_fields() | mysqli_fetch_fields() | N/A | Returns an array of objects representing the fields in a result set
mysqli_result::fetch_object() | mysqli_fetch_object() | N/A | Returns the current row of a result set as an object
mysqli_result::fetch_row() | mysqli_fetch_row() | N/A | Get a result row as an enumerated array
mysqli_result::field_seek() | mysqli_field_seek() | N/A | Set result pointer to a specified field offset
mysqli_result::free(), mysqli_result::close, mysqli_result::free_result | mysqli_free_result() | N/A | Frees the memory associated with a result

Summary of mysqli_driver methods
MySQL_Driver
OOP Interface | Procedural Interface | Alias (Do not use) | Description
--- | --- | --- | ---
Properties
$mysqli_driver::mysqli_report | mysqli_report() | N/A | Sets mysqli error reporting mode
Methods
mysqli_driver::embedded_server_end() | mysqli_embedded_server_end() | N/A | NOT DOCUMENTED
mysqli_driver::embedded_server_start() | mysqli_embedded_server_start() | N/A | NOT DOCUMENTED

> Note:

> Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

# The mysqli class

(PHP 5, PHP 7, PHP 8)

## Introduction

Represents a connection between PHP and a MySQL database.

## Class synopsis

class mysqli {
/* Properties */
public readonly int|string $affected_rows;
public readonly string $client_info;
public readonly int $client_version;
public readonly int $connect_errno;
public readonly ?string $connect_error;
public readonly int $errno;
public readonly string $error;
public readonly array $error_list;
public readonly int $field_count;
public readonly string $host_info;
public readonly ?string $info;
public readonly int|string $insert_id;
public readonly string $server_info;
public readonly int $server_version;
public readonly string $sqlstate;
public readonly int $protocol_version;
public readonly int $thread_id;
public readonly int $warning_count;
/* Methods */
public __construct(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`
)
public autocommit(bool `$enable`): bool
public begin_transaction(int `$flags` = 0, ?string `$name` = `null`): bool
public change_user(string `$username`, #[\SensitiveParameter] string `$password`, ?string `$database`): bool
public character_set_name(): string
public close(): true
public commit(int `$flags` = 0, ?string `$name` = `null`): bool
public connect(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`
): bool
public debug(string `$options`): true
public dump_debug_info(): bool
public execute_query(string `$query`, ?array `$params` = `null`): mysqli_result|bool
public get_charset(): ?object
#[\Deprecated]
public get_client_info(): string
public get_connection_stats(): array
public get_server_info(): string
public get_warnings(): mysqli_warning|false
#[\Deprecated]
public init(): ?bool
#[\Deprecated]
public kill(int `$process_id`): bool
public more_results(): bool
public multi_query(string `$query`): bool
public next_result(): bool
public options(int `$option`, string|int `$value`): bool
#[\Deprecated]
public ping(): bool
public static poll(
?array `&$read`,
?array `&$error`,
array `&$reject`,
int `$seconds`,
int `$microseconds` = 0
): int|false
public prepare(string `$query`): mysqli_stmt|false
public query(string `$query`, int `$result_mode` = `MYSQLI_STORE_RESULT`): mysqli_result|bool
public real_connect(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`,
int `$flags` = 0
): bool
public real_escape_string(string `$string`): string
public real_query(string `$query`): bool
public reap_async_query(): mysqli_result|bool
#[\Deprecated]
public refresh(int `$flags`): bool
public release_savepoint(string `$name`): bool
public rollback(int `$flags` = 0, ?string `$name` = `null`): bool
public savepoint(string `$name`): bool
public select_db(string `$database`): bool
public set_charset(string `$charset`): bool
public ssl_set(
?string `$key`,
?string `$certificate`,
?string `$ca_certificate`,
?string `$ca_path`,
?string `$cipher_algos`
): true
public stat(): string|false
public stmt_init(): mysqli_stmt|false
public store_result(int `$mode` = 0): mysqli_result|false
public thread_safe(): bool
public use_result(): mysqli_result|false
}

# mysqli::$affected_rows

# mysqli_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

### Description

Object-oriented style

int|string $mysqli->affected_rows;

Procedural style

mysqli_affected_rows(mysqli `$mysql`): int|string

Returns the number of rows affected by the last `INSERT`, `UPDATE`, `REPLACE` or `DELETE` query. Works like mysqli_num_rows() for `SELECT` statements.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an `UPDATE` statement, no rows matched the `WHERE` clause in the query or that no query has yet been executed. `-1` indicates that the query returned an error or that mysqli_affected_rows() was called for an unbuffered `SELECT` query.

> Note:

> If the number of affected rows is greater than the maximum int value (`PHP_INT_MAX`), the number of affected rows will be returned as a string.

### Examples

Example #1 $mysqli->affected_rows example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
/* Delete table Language */
$mysqli->query("DROP TABLE Language");`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");
/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");`

The above examples will output:

    Affected rows (INSERT): 984
    Affected rows (UPDATE): 168
    Affected rows (DELETE): 815
    Affected rows (SELECT): 169

### See Also

- mysqli_num_rows() - Gets the number of rows in the result set
- mysqli_info() - Retrieves information about the most recently executed query

# mysqli::autocommit

# mysqli_autocommit

(PHP 5, PHP 7, PHP 8)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-committing database modifications

### Description

Object-oriented style

public mysqli::autocommit(bool `$enable`): bool

Procedural style

mysqli_autocommit(mysqli `$mysql`, bool `$enable`): bool

Turns on or off auto-commit mode on queries for the database connection.

To determine the current state of autocommit use the SQL command `SELECT @@autocommit`.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`enable`

  Whether to turn on auto-commit or not.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::autocommit() example

Object-oriented style

`<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Turn autocommit off */
$mysqli->autocommit(false);
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
try {
/* Prepare insert statement */
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
$stmt->execute();
$language_code = 'FR';
$native_speakers = 40_546_321;
$stmt->execute();
/* Commit the data in the database. This doesn't set autocommit=true */
$mysqli->commit();
print "Committed 2 rows in the database\n";
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
$stmt->execute();
$language_code = 'DK';
$native_speakers = 5_222_444;
$stmt->execute();
/* Setting autocommit=true will trigger a commit */
$mysqli->autocommit(true);
print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}`

Procedural style

`<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Turn autocommit off */
mysqli_autocommit($mysqli, false);
$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);
try {
/* Prepare insert statement */
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
mysqli_stmt_execute($stmt);
$language_code = 'FR';
$native_speakers = 40_546_321;
mysqli_stmt_execute($stmt);
/* Commit the data in the database. This doesn't set autocommit=true */
mysqli_commit($mysqli);
print "Committed 2 rows in the database\n";
$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);
/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
mysqli_stmt_execute($stmt);
$language_code = 'DK';
$native_speakers = 5_222_444;
mysqli_stmt_execute($stmt);
/* Setting autocommit=true will trigger a commit */
mysqli_autocommit($mysqli, true);
print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);
throw $exception;
}`

The above examples will output:

    Autocommit is 0
    Committed 2 rows in the database
    Autocommit is 0
    Committed 2 row in the database
    Autocommit is 0
    Committed 2 rows in the database
    Autocommit is 0
    Committed 2 row in the database

### Notes

> Note:

> This function does not work with non transactional table types (like MyISAM or ISAM).

### See Also

- mysqli_begin_transaction() - Starts a transaction
- mysqli_commit() - Commits the current transaction
- mysqli_rollback() - Rolls back current transaction

# mysqli::begin_transaction

# mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::begin_transaction -- mysqli_begin_transaction — Starts a transaction

### Description

Object-oriented style

public mysqli::begin_transaction(int `$flags` = 0, ?string `$name` = `null`): bool

Procedural style:

mysqli_begin_transaction(mysqli `$mysql`, int `$flags` = 0, ?string `$name` = `null`): bool

Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see » http://dev.mysql.com/doc/mysql/en/commit.html.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`flags`

  Valid flags are:

  - `MYSQLI_TRANS_START_READ_ONLY`: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above.

  - `MYSQLI_TRANS_START_READ_WRITE`: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above.

  - `MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT`: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

`name`

  Savepoint name for the transaction.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `name` is now nullable.

### Examples

Example #1 mysqli::begin_transaction() example

Object-oriented style

`<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
$mysqli->begin_transaction();
try {
/* Insert some values */
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();
/* If code reaches this point without errors then commit the data in the database */
$mysqli->commit();
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}`

Procedural style

`<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
mysqli_begin_transaction($mysqli);
try {
/* Insert some values */
mysqli_query($mysqli, "INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
mysqli_stmt_execute($stmt);
/* If code reaches this point without errors then commit the data in the database */
mysqli_commit($mysqli);
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);
throw $exception;
}`

### Notes

> Note:

> This function does not work with non transactional table types (like MyISAM or ISAM).

### See Also

- mysqli_autocommit() - Turns on or off auto-committing database modifications
- mysqli_commit() - Commits the current transaction
- mysqli_rollback() - Rolls back current transaction

# mysqli::change_user

# mysqli_change_user

(PHP 5, PHP 7, PHP 8)

mysqli::change_user -- mysqli_change_user — Changes the user of the database connection

### Description

Object-oriented style

public mysqli::change_user(string `$username`, #[\SensitiveParameter] string `$password`, ?string `$database`): bool

Procedural style

mysqli_change_user(
mysqli `$mysql`,
string `$username`,
#[\SensitiveParameter] string `$password`,
?string `$database`
): bool

Attempts to connect to the specified database using the provided credentials.

In comparison to mysqli::connect(), this method will not disconnect the current connection if the new connection cannot be opened.

In order to successfully change users a valid `username` and `password` parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`username`

  The MySQL user name.

`password`

  The MySQL password.

`database`

  The database name. If `null` or an empty string is passed, the connection to the server will be opened with no default database.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Resetting the connection session

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query("SET @a:=1");
$mysqli->change_user("my_user", "my_password", "world");
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
$result = $mysqli->query("SELECT @a");
$row = $result->fetch_row();
if ($row[0] === null) {
printf("Value of variable a is NULL\n");
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "SET @a:=1");
mysqli_change_user($link, "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database: %s\n", $row[0]);
$result = mysqli_query($link, "SELECT @a");
$row = mysqli_fetch_row($result);
if ($row[0] === null) {
printf("Value of variable a is NULL\n");
}`

The above examples will output:

    Default database: world
    Value of variable a is NULL

Example #2 If `database` is `null` the connection is opened without selecting any default database

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->change_user("my_user", "my_password", null);
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);`

The above examples will output:

    Default database:

### Notes

> Note:

> Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

### See Also

- mysqli_connect() - Alias of mysqli::__construct
- mysqli_select_db() - Selects the default database for database queries

# mysqli::character_set_name

# mysqli_character_set_name

(PHP 5, PHP 7, PHP 8)

mysqli::character_set_name -- mysqli_character_set_name — Returns the current character set of the database connection

### Description

Object-oriented style

public mysqli::character_set_name(): string

Procedural style

mysqli_character_set_name(mysqli `$mysql`): string

Returns the current character set of the database connection.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

The current character set of the connection

### Examples

Example #1 mysqli::character_set_name() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Set the default character set */
$mysqli->set_charset('utf8mb4');
/* Print current character set */
$charset = $mysqli->character_set_name();
printf("Current character set is %s\n", $charset);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Set the default character set */
mysqli_set_charset($mysqli, 'utf8mb4');
/* Print current character set */
$charset = mysqli_character_set_name($mysqli);
printf("Current character set is %s\n", $charset);`

The above examples will output:

    Current character set is utf8mb4

### See Also

- mysqli_set_charset() - Sets the client character set
- mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

# mysqli::close

# mysqli_close

(PHP 5, PHP 7, PHP 8)

mysqli::close -- mysqli_close — Closes a previously opened database connection

### Description

Object-oriented style

public mysqli::close(): true

Procedural style

mysqli_close(mysqli `$mysql`): true

Closes a previously opened database connection.

Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function now always returns `true`. Previously it returned `false` on failure.

### Examples

Example #1 mysqli::close() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* Close the connection as soon as it's no longer needed */
$mysqli->close();
foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* Close the connection as soon as it's no longer needed */
mysqli_close($mysqli);
foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}`

### Notes

> Note:

> mysqli_close() will not close persistent connections. For additional details, see the manual page on persistent connections.

### See Also

- mysqli::__construct() - Open a new connection to the MySQL server
- mysqli_init() - Initializes MySQLi and returns an object for use with mysqli_real_connect()
- mysqli_real_connect() - Opens a connection to the MySQL server
- mysqli_free_result() - Frees the memory associated with a result

# mysqli::commit

# mysqli_commit

(PHP 5, PHP 7, PHP 8)

mysqli::commit -- mysqli_commit — Commits the current transaction

### Description

Object-oriented style

public mysqli::commit(int `$flags` = 0, ?string `$name` = `null`): bool

Procedural style

mysqli_commit(mysqli `$mysql`, int `$flags` = 0, ?string `$name` = `null`): bool

Commits the current transaction for the database connection.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`flags`

  A bitmask of `MYSQLI_TRANS_COR_*` constants.

`name`

  If provided then `COMMIT/*name*/` is executed.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.0.0 | `name` is now nullable.

### Examples

See the mysqli::begin_transaction() example.

### Notes

> Note:

> This function does not work with non transactional table types (like MyISAM or ISAM).

### See Also

- mysqli_autocommit() - Turns on or off auto-committing database modifications
- mysqli_begin_transaction() - Starts a transaction
- mysqli_rollback() - Rolls back current transaction
- mysqli_savepoint() - Set a named transaction savepoint

# mysqli::$connect_errno

# mysqli_connect_errno

(PHP 5, PHP 7, PHP 8)

mysqli::$connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

### Description

Object-oriented style

int $mysqli->connect_errno;

Procedural style

mysqli_connect_errno(): int

Returns the error code from the last connection attempt.

### Parameters

This function has no parameters.

### Return Values

An error code for the last connection attempt, if it failed. Zero means no error occurred.

Returns the last connection error code regardless of the instance on which it is called.

### Examples

Example #1 $mysqli->connect_errno example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_errno) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_errno);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_errno());
}`

### See Also

- mysqli_connect() - Alias of mysqli::__construct
- mysqli_connect_error() - Returns a description of the last connection error
- mysqli_errno() - Returns the error code for the most recent function call
- mysqli_error() - Returns a string description of the last error
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

# mysqli::$connect_error

# mysqli_connect_error

(PHP 5, PHP 7, PHP 8)

mysqli::$connect_error -- mysqli_connect_error — Returns a description of the last connection error

### Description

Object-oriented style

?string $mysqli->connect_error;

Procedural style

mysqli_connect_error(): ?string

Returns the error message from the last connection attempt.

### Parameters

This function has no parameters.

### Return Values

A string that describes the error. `null` is returned if no error occurred.

Returns the last connection error regardless of the instance on which it is called.

### Examples

Example #1 $mysqli->connect_error example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_error) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_error);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_error());
}`

### See Also

- mysqli_connect() - Alias of mysqli::__construct
- mysqli_connect_errno() - Returns the error code from last connect call
- mysqli_errno() - Returns the error code for the most recent function call
- mysqli_error() - Returns a string description of the last error
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

# mysqli::__construct

# mysqli::connect

# mysqli_connect

(PHP 5, PHP 7, PHP 8)

mysqli::__construct -- mysqli::connect -- mysqli_connect — Open a new connection to the MySQL server

### Description

Object-oriented style

public mysqli::__construct(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`
)
public mysqli::connect(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`
): bool

Procedural style

mysqli_connect(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`
): mysqli|false

Opens a connection to the MySQL Server.

### Parameters

`hostname`

  Can be either a host name or an IP address. When passing `null`, the value is retrieved from mysqli.default_host. When possible, pipes will be used instead of the TCP/IP protocol. The TCP/IP protocol is used if a host name and port number are provided together e.g. `localhost:3308`.

  Prepending host by `p:` opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

`username`

  The MySQL username or `null` to assume the username based on the mysqli.default_user ini option.

`password`

  The MySQL password or `null` to assume the password based on the mysqli.default_pw ini option.

`database`

  The default database to be used when performing queries or `null`.

`port`

  The port number to attempt to connect to the MySQL server or `null` to assume the port based on the mysqli.default_port ini option.

`socket`

  The socket or named pipe that should be used or `null` to assume the socket based on the mysqli.default_socket ini option.

  > Note:

  > Specifying the `socket` parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the `hostname` parameter.

### Return Values

mysqli::__construct() always returns an object which represents the connection to a MySQL Server, regardless of it being successful or not.

mysqli_connect() returns an object which represents the connection to a MySQL Server, or `false` on failure.

mysqli::connect() returns `true` on success or `false` on failure. Prior to PHP 8.1.0, returns `null` on success.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.1.0 | mysqli::connect() now returns `true` instead of `null` on success.
7.4.0 | All parameters are now nullable.

### Examples

Example #1 mysqli::__construct() example

Object-oriented style

`<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
printf("Success... %s\n", $mysqli->host_info);`

Procedural style

`<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));`

The above examples will output something similar to:

    Success... localhost via TCP/IP

Example #2 Extending mysqli class

`<?php
class FooMysqli extends mysqli {
public function __construct($host, $user, $pass, $db, $port, $socket, $charset) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $user, $pass, $db, $port, $socket);
$this->set_charset($charset);
}
}
$db = new FooMysqli('localhost', 'my_user', 'my_password', 'my_db', 3306, null, 'utf8mb4');`

Example #3 Manual error handling

If error reporting is disabled, the developer is responsible for checking and handling failures

Object-oriented style

`<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
throw new RuntimeException('mysqli connection error: ' . $mysqli->connect_error);
}
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
if ($mysqli->errno) {
throw new RuntimeException('mysqli error: ' . $mysqli->error);
}`

Procedural style

`<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (mysqli_connect_errno()) {
throw new RuntimeException('mysqli connection error: ' . mysqli_connect_error());
}
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
if (mysqli_errno($mysqli)) {
throw new RuntimeException('mysqli error: ' . mysqli_error($mysqli));
}`

### Notes

> Note:

> MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

> Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

> Note:

> Object-oriented style only: If the connection fails, an object is still returned. To check whether the connection failed, use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.

> Note:

> If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

> Note:

> Calling the constructor with no parameters is the same as calling mysqli_init().

> Note:

> Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character `E`. On Windows, if the environment is not copied the `SYSTEMROOT` environment variable won't be available and PHP will have problems loading Winsock.

### See Also

- mysqli_real_connect() - Opens a connection to the MySQL server
- mysqli_options() - Set options
- mysqli_connect_errno() - Returns the error code from last connect call
- mysqli_connect_error() - Returns a description of the last connection error
- mysqli_close() - Closes a previously opened database connection

# mysqli::debug

# mysqli_debug

(PHP 5, PHP 7, PHP 8)

mysqli::debug -- mysqli_debug — Performs debugging operations

### Description

Object-oriented style

public mysqli::debug(string `$options`): true

Procedural style

mysqli_debug(string `$options`): true

Performs debugging operations using the Fred Fish debugging library.

### Parameters

`options`

  A string representing the debugging operation to perform

  The debug control string is a sequence of colon separated fields as follows: ``

      <field_1>:<field_2>:<field_N>

  Each field consists of a mandatory flag character followed by an optional `,` and comma separated list of modifiers: `flag[,modifier,modifier,...,modifier]`

  Recognized Flag Characters
  `options` character | Description
  --- | ---
  O | `MYSQLND_DEBUG_FLUSH`
  A/a | `MYSQLND_DEBUG_APPEND`
  F | `MYSQLND_DEBUG_DUMP_FILE`
  i | `MYSQLND_DEBUG_DUMP_PID`
  L | `MYSQLND_DEBUG_DUMP_LINE`
  m | `MYSQLND_DEBUG_TRACE_MEMORY_CALLS`
  n | `MYSQLND_DEBUG_DUMP_LEVEL`
  o | output to file
  T | `MYSQLND_DEBUG_DUMP_TIME`
  t | `MYSQLND_DEBUG_DUMP_TRACE`
  x | `MYSQLND_DEBUG_PROFILE_CALLS`

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function now always returns `true`. Previously it returned `false` on failure.

### Examples

Example #1 Generating a Trace File

`<?php
/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");
?>`

### Notes

> Note:

> To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

### See Also

- mysqli_dump_debug_info() - Dump debugging information into the log
- mysqli_report() - Alias of mysqli_driver->report_mode

# mysqli::dump_debug_info

# mysqli_dump_debug_info

(PHP 5, PHP 7, PHP 8)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

### Description

Object-oriented style

public mysqli::dump_debug_info(): bool

Procedural style

mysqli_dump_debug_info(mysqli `$mysql`): bool

This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mysqli_debug() - Performs debugging operations

# mysqli::$errno

# mysqli_errno

(PHP 5, PHP 7, PHP 8)

mysqli::$errno -- mysqli_errno — Returns the error code for the most recent function call

### Description

Object-oriented style

int $mysqli->errno;

Procedural style

mysqli_errno(mysqli `$mysql`): int

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

An error code value for the last call, if it failed. zero means no error occurred.

### Examples

Example #1 $mysqli->errno example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Errorcode: %d\n", $mysqli->errno);
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
printf("Errorcode: %d\n", mysqli_errno($link));
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Errorcode: 1193

### See Also

- mysqli_connect_errno() - Returns the error code from last connect call
- mysqli_connect_error() - Returns a description of the last connection error
- mysqli_error() - Returns a string description of the last error
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

# mysqli::$error

# mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$error -- mysqli_error — Returns a string description of the last error

### Description

Object-oriented style

string $mysqli->error;

Procedural style

mysqli_error(mysqli `$mysql`): string

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A string that describes the error. An empty string if no error occurred.

### Examples

Example #1 $mysqli->error example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Error message: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
printf("Error message: %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error message: Unknown system variable 'a'

### See Also

- mysqli_connect_errno() - Returns the error code from last connect call
- mysqli_connect_error() - Returns a description of the last connection error
- mysqli_errno() - Returns the error code for the most recent function call
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

# mysqli::$error_list

# mysqli_error_list

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

mysqli::$error_list -- mysqli_error_list — Returns a list of errors from the last command executed

### Description

Object-oriented style

array $mysqli->error_list;

Procedural style

mysqli_error_list(mysqli `$mysql`): array

Returns an array of errors for the most recent MySQLi function call that can succeed or fail.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A list of errors, each as an associative array containing the errno, error, and sqlstate.

### Examples

Example #1 $mysqli->error_list example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "nobody", "");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->query("SET a=1")) {
print_r($mysqli->error_list);
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
print_r(mysqli_error_list($link));
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Array
    (
        [0] => Array
            (
                [errno] => 1193
                [sqlstate] => HY000
                [error] => Unknown system variable 'a'
            )

    )

### See Also

- mysqli_connect_errno() - Returns the error code from last connect call
- mysqli_connect_error() - Returns a description of the last connection error
- mysqli_error() - Returns a string description of the last error
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

# mysqli::execute_query

# mysqli_execute_query

(PHP 8 >= 8.2.0)

mysqli::execute_query -- mysqli_execute_query — Prepares, binds parameters, and executes SQL statement

### Description

Object-oriented style

public mysqli::execute_query(string `$query`, ?array `$params` = `null`): mysqli_result|bool

Procedural style

mysqli_execute_query(mysqli `$mysql`, string `$query`, ?array `$params` = `null`): mysqli_result|bool

Prepares the SQL query, binds parameters, and executes it. The mysqli::execute_query() method is a shortcut for mysqli::prepare(), mysqli_stmt::bind_param(), mysqli_stmt::execute(), and mysqli_stmt::get_result().

The statement template can contain zero or more question mark (`?`) parameter markers⁠—also called placeholders. The parameter values must be provided as an array using `params` parameter.

A prepared statement is created under the hood but it's never exposed outside of the function. It's impossible to access properties of the statement as one would do with the mysqli_stmt object. Due to this limitation, the status information is copied to the mysqli object and is available using its methods, e.g. mysqli_affected_rows() or mysqli_error().

> Note:

> In the case where a statement is passed to mysqli_execute_query() that is longer than `max_allowed_packet` of the server, the returned error codes are different depending on the operating system. The behavior is as follows:

> - On Linux returns an error code of 1153. The error message means got a packet bigger than `max_allowed_packet` bytes.

> - On Windows returns an error code 2006. This error message means server has gone away.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`query`

  The query, as a string. It must consist of a single SQL statement.

  The SQL statement may contain zero or more parameter markers represented by question mark (`?`) characters at the appropriate positions.

  > Note:

  > The markers are legal only in certain places in SQL statements. For example, they are permitted in the `VALUES()` list of an `INSERT` statement (to specify column values for a row), or in a comparison with a column in a `WHERE` clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

`params`

  An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string.

### Return Values

Returns `false` on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, returns a mysqli_result object. For other successful queries, returns `true`.

### Examples

Example #1 mysqli::execute_query() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = $mysqli->execute_query($query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = mysqli_execute_query($link, $query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}`

The above examples will output something similar to:

    Aachen (Nordrhein-Westfalen)
    Augsburg (Baijeri)
    Bergisch Gladbach (Nordrhein-Westfalen)
    Berlin (Berliini)
    Bielefeld (Nordrhein-Westfalen)

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_execute() - Executes a prepared statement
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object

# mysqli::$field_count

# mysqli_field_count

(PHP 5, PHP 7, PHP 8)

mysqli::$field_count -- mysqli_field_count — Returns the number of columns for the most recent query

### Description

Object-oriented style

int $mysqli->field_count;

Procedural style

mysqli_field_count(mysqli `$mysql`): int

Returns the number of columns for the most recent query on the connection represented by the `mysql` parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

An integer representing the number of fields in a result set.

### Examples

Example #1 $mysqli->field_count example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$mysqli->real_query("SELECT * FROM friends");
if ($mysqli->field_count) {
/* this was a select/show or describe query */
$result = $mysqli->store_result();
/* process resultset */
$row = $result->fetch_row();
/* free resultset */
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
mysqli_real_query($link, "SELECT * FROM friends");
if (mysqli_field_count($link)) {
/* this was a select/show or describe query */
$result = mysqli_store_result($link);
/* process resultset */
$row = mysqli_fetch_row($result);
/* free resultset */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

# mysqli::get_charset

# mysqli_get_charset

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

### Description

Object-oriented style

public mysqli::get_charset(): ?object

Procedural style

mysqli_get_charset(mysqli `$mysql`): ?object

Returns a character set object providing several properties of the current active character set.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

The function returns a character set object with the following properties:

`charset`

  Character set name

`collation`

  Collation name

`dir`

  Directory the character set description was fetched from or "" for built-in character sets

`min_length`

  Minimum character length in bytes

`max_length`

  Maximum character length in bytes

`number`

  Internal character set number

`state`

  As of PHP 8.2.0, it is always `1`

### Examples

Example #1 mysqli::get_charset() example

Object-oriented style

`<?php
$db = mysqli_init();
$db->real_connect("localhost","root","","test");
$db->set_charset('latin1');
var_dump($db->get_charset());
?>`

Procedural style

`<?php
$db = mysqli_init();
mysqli_real_connect($db, "localhost","root","","test");
mysqli_set_charset($db, 'latin1');
var_dump(mysqli_get_charset($db));
?>`

The above examples will output:

    object(stdClass)#2 (7) {
      ["charset"]=>
      string(6) "latin1"
      ["collation"]=>
      string(17) "latin1_swedish_ci"
      ["dir"]=>
      string(0) ""
      ["min_length"]=>
      int(1)
      ["max_length"]=>
      int(1)
      ["number"]=>
      int(8)
      ["state"]=>
      int(1)
    }

### See Also

- mysqli_character_set_name() - Returns the current character set of the database connection
- mysqli_set_charset() - Sets the client character set

# mysqli::$client_info

# mysqli::get_client_info

# mysqli_get_client_info

(PHP 5, PHP 7, PHP 8)

mysqli::$client_info -- mysqli::get_client_info -- mysqli_get_client_info — Get MySQL client info

### Description

Object-oriented style

string $mysqli->client_info;
#[\Deprecated]
public mysqli::get_client_info(): string

Procedural style

mysqli_get_client_info(?mysqli `$mysql` = `null`): string

Returns a string that represents the MySQL client library version.

### Parameters

This function has no parameters.

### Return Values

A string that represents the MySQL client library version.

### Changelog

Version | Description
--- | ---
8.1.0 | Calling mysqli_get_client_info() with the `mysql` argument has been deprecated. This function never required a parameter, but incorrectly allowed it as an optional parameter.
8.1.0 | The object-oriented style mysqli::get_client_info() has been deprecated.

### Examples

Example #1 mysqli_get_client_info

`<?php
/* We don't need a connection to determine
the version of mysql client library */
printf("Client library version: %s\n", mysqli_get_client_info());
?>`

### See Also

- mysqli_get_client_version() - Returns the MySQL client version as an integer
- mysqli_get_server_info() - Returns the version of the MySQL server
- mysqli_get_server_version() - Returns the version of the MySQL server as an integer

# mysqli::$client_version

# mysqli_get_client_version

(PHP 5, PHP 7, PHP 8)

mysqli::$client_version -- mysqli_get_client_version — Returns the MySQL client version as an integer

### Description

Object-oriented style

int $mysqli->client_version;

Procedural style

mysqli_get_client_version(): int

Returns client version number as an integer.

### Parameters

This function has no parameters.

### Return Values

A number that represents the MySQL client library version in format: `main_version*10000 + minor_version *100 + sub_version`. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exists.

### Examples

Example #1 mysqli_get_client_version

`<?php
/* We don't need a connection to determine
the version of mysql client library */
printf("Client library version: %d\n", mysqli_get_client_version());
?>`

### See Also

- mysqli_get_client_info() - Get MySQL client info
- mysqli_get_server_info() - Returns the version of the MySQL server
- mysqli_get_server_version() - Returns the version of the MySQL server as an integer

# mysqli::get_connection_stats

# mysqli_get_connection_stats

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

### Description

Object-oriented style

public mysqli::get_connection_stats(): array

Procedural style

mysqli_get_connection_stats(mysqli `$mysql`): array

Returns statistics about the client connection.

> Note:

> Available only with mysqlnd.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns an array with connection stats.

### Examples

Example #1 A mysqli_get_connection_stats() example

`<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>`

The above example will output something similar to:

    Array
    (
        [bytes_sent] => 43
        [bytes_received] => 80
        [packets_sent] => 1
        [packets_received] => 2
        [protocol_overhead_in] => 8
        [protocol_overhead_out] => 4
        [bytes_received_ok_packet] => 11
        [bytes_received_eof_packet] => 0
        [bytes_received_rset_header_packet] => 0
        [bytes_received_rset_field_meta_packet] => 0
        [bytes_received_rset_row_packet] => 0
        [bytes_received_prepare_response_packet] => 0
        [bytes_received_change_user_packet] => 0
        [packets_sent_command] => 0
        [packets_received_ok] => 1
        [packets_received_eof] => 0
        [packets_received_rset_header] => 0
        [packets_received_rset_field_meta] => 0
        [packets_received_rset_row] => 0
        [packets_received_prepare_response] => 0
        [packets_received_change_user] => 0
        [result_set_queries] => 0
        [non_result_set_queries] => 0
        [no_index_used] => 0
        [bad_index_used] => 0
        [slow_queries] => 0
        [buffered_sets] => 0
        [unbuffered_sets] => 0
        [ps_buffered_sets] => 0
        [ps_unbuffered_sets] => 0
        [flushed_normal_sets] => 0
        [flushed_ps_sets] => 0
        [ps_prepared_never_executed] => 0
        [ps_prepared_once_executed] => 0
        [rows_fetched_from_server_normal] => 0
        [rows_fetched_from_server_ps] => 0
        [rows_buffered_from_client_normal] => 0
        [rows_buffered_from_client_ps] => 0
        [rows_fetched_from_client_normal_buffered] => 0
        [rows_fetched_from_client_normal_unbuffered] => 0
        [rows_fetched_from_client_ps_buffered] => 0
        [rows_fetched_from_client_ps_unbuffered] => 0
        [rows_fetched_from_client_ps_cursor] => 0
        [rows_skipped_normal] => 0
        [rows_skipped_ps] => 0
        [copy_on_write_saved] => 0
        [copy_on_write_performed] => 0
        [command_buffer_too_small] => 0
        [connect_success] => 1
        [connect_failure] => 0
        [connection_reused] => 0
        [reconnect] => 0
        [pconnect_success] => 0
        [active_connections] => 1
        [active_persistent_connections] => 0
        [explicit_close] => 0
        [implicit_close] => 0
        [disconnect_close] => 0
        [in_middle_of_command_close] => 0
        [explicit_free_result] => 0
        [implicit_free_result] => 0
        [explicit_stmt_close] => 0
        [implicit_stmt_close] => 0
        [mem_emalloc_count] => 0
        [mem_emalloc_ammount] => 0
        [mem_ecalloc_count] => 0
        [mem_ecalloc_ammount] => 0
        [mem_erealloc_count] => 0
        [mem_erealloc_ammount] => 0
        [mem_efree_count] => 0
        [mem_malloc_count] => 0
        [mem_malloc_ammount] => 0
        [mem_calloc_count] => 0
        [mem_calloc_ammount] => 0
        [mem_realloc_count] => 0
        [mem_realloc_ammount] => 0
        [mem_free_count] => 0
        [proto_text_fetched_null] => 0
        [proto_text_fetched_bit] => 0
        [proto_text_fetched_tinyint] => 0
        [proto_text_fetched_short] => 0
        [proto_text_fetched_int24] => 0
        [proto_text_fetched_int] => 0
        [proto_text_fetched_bigint] => 0
        [proto_text_fetched_decimal] => 0
        [proto_text_fetched_float] => 0
        [proto_text_fetched_double] => 0
        [proto_text_fetched_date] => 0
        [proto_text_fetched_year] => 0
        [proto_text_fetched_time] => 0
        [proto_text_fetched_datetime] => 0
        [proto_text_fetched_timestamp] => 0
        [proto_text_fetched_string] => 0
        [proto_text_fetched_blob] => 0
        [proto_text_fetched_enum] => 0
        [proto_text_fetched_set] => 0
        [proto_text_fetched_geometry] => 0
        [proto_text_fetched_other] => 0
        [proto_binary_fetched_null] => 0
        [proto_binary_fetched_bit] => 0
        [proto_binary_fetched_tinyint] => 0
        [proto_binary_fetched_short] => 0
        [proto_binary_fetched_int24] => 0
        [proto_binary_fetched_int] => 0
        [proto_binary_fetched_bigint] => 0
        [proto_binary_fetched_decimal] => 0
        [proto_binary_fetched_float] => 0
        [proto_binary_fetched_double] => 0
        [proto_binary_fetched_date] => 0
        [proto_binary_fetched_year] => 0
        [proto_binary_fetched_time] => 0
        [proto_binary_fetched_datetime] => 0
        [proto_binary_fetched_timestamp] => 0
        [proto_binary_fetched_string] => 0
        [proto_binary_fetched_blob] => 0
        [proto_binary_fetched_enum] => 0
        [proto_binary_fetched_set] => 0
        [proto_binary_fetched_geometry] => 0
        [proto_binary_fetched_other] => 0
    )

### See Also

- Stats description

# mysqli::$host_info

# mysqli_get_host_info

(PHP 5, PHP 7, PHP 8)

mysqli::$host_info -- mysqli_get_host_info — Returns a string representing the type of connection used

### Description

Object-oriented style

string $mysqli->host_info;

Procedural style

mysqli_get_host_info(mysqli `$mysql`): string

Returns a string describing the connection represented by the `mysql` parameter (including the server host name).

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A character string representing the server hostname and the connection type.

### Examples

Example #1 $mysqli->host_info example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* print host information */
printf("Host info: %s\n", $mysqli->host_info);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));`

The above examples will output:

    Host info: Localhost via UNIX socket

### See Also

- mysqli_get_proto_info() - Returns the version of the MySQL protocol used

# mysqli::$protocol_version

# mysqli_get_proto_info

(PHP 5, PHP 7, PHP 8)

mysqli::$protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

### Description

Object-oriented style

int $mysqli->protocol_version;

Procedural style

mysqli_get_proto_info(mysqli `$mysql`): int

Returns an integer representing the MySQL protocol version used by the connection represented by the `mysql` parameter.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns an integer representing the protocol version.

### Examples

Example #1 $mysqli->protocol_version example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));`

The above examples will output:

    Protocol version: 10

### See Also

- mysqli_get_host_info() - Returns a string representing the type of connection used

# mysqli::$server_info

# mysqli::get_server_info

# mysqli_get_server_info

(PHP 5, PHP 7, PHP 8)

mysqli::$server_info -- mysqli::get_server_info -- mysqli_get_server_info — Returns the version of the MySQL server

### Description

Object-oriented style

string $mysqli->server_info;
public mysqli::get_server_info(): string

Procedural style

mysqli_get_server_info(mysqli `$mysql`): string

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A character string representing the server version.

### Examples

Example #1 $mysqli->server_info example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %s\n", $mysqli->server_info);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));`

The above examples will output something similar to:

    Server version: 8.0.21

### See Also

- mysqli_get_client_info() - Get MySQL client info
- mysqli_get_client_version() - Returns the MySQL client version as an integer
- mysqli_get_server_version() - Returns the version of the MySQL server as an integer

# mysqli::$server_version

# mysqli_get_server_version

(PHP 5, PHP 7, PHP 8)

mysqli::$server_version -- mysqli_get_server_version — Returns the version of the MySQL server as an integer

### Description

Object-oriented style

int $mysqli->server_version;

Procedural style

mysqli_get_server_version(mysqli `$mysql`): int

The mysqli_get_server_version() function returns the version of the server connected to (represented by the `mysql` parameter) as an integer.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

An integer representing the server version.

The form of this version number is `main_version * 10000 + minor_version * 100 + sub_version` (i.e. version 4.1.0 is 40100).

### Examples

Example #1 $mysqli->server_version example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %d\n", $mysqli->server_version);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));`

The above examples will output something similar to:

    Server version: 80021

### See Also

- mysqli_get_client_info() - Get MySQL client info
- mysqli_get_client_version() - Returns the MySQL client version as an integer
- mysqli_get_server_info() - Returns the version of the MySQL server

# mysqli::get_warnings

# mysqli_get_warnings

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

### Description

Object-oriented style

public mysqli::get_warnings(): mysqli_warning|false

Procedural style

mysqli_get_warnings(mysqli `$mysql`): mysqli_warning|false

Returns a singly linked list comprised of mysqli_warning or `false` if there are no warnings. Each object in the list corresponds to a single line from the result of `SHOW WARNINGS`. Calling mysqli_warning::next() will refill the object with the values from the next row.

> Note: To retrieve warning messages, it is recommended to use the SQL command `SHOW WARNINGS [limit row_count]` instead of this function.

Warning

The linked list cannot be rewound or retrieved again.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns a singly linked list comprised of mysqli_warning or `false` if there are no warnings.

### Examples

Example #1 Traversing the linked list to fetch all warnings

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("SELECT 1/0, CAST('NULL' AS UNSIGNED)");
if ($mysqli->warning_count > 0) {
$warning = $mysqli->get_warnings();
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "user", "password", "test");
mysqli_query($link, "SELECT 1/0, CAST('NULL' AS UNSIGNED)");
if (mysqli_warning_count($link) > 0) {
$warning = mysqli_get_warnings($link);
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}`

The above examples will output:

    Error number: 1365
    Message: Division by 0
    Error number: 1292
    Message: Truncated incorrect INTEGER value: 'NULL'

# mysqli::$info

# mysqli_info

(PHP 5, PHP 7, PHP 8)

mysqli::$info -- mysqli_info — Retrieves information about the most recently executed query

### Description

Object-oriented style

?string $mysqli->info;

Procedural style

mysqli_info(mysqli `$mysql`): ?string

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible mysqli_info return values
Query type | Example result string
--- | ---
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

> Note:

> Queries which do not fall into one of the preceding formats are not supported. In these situations, mysqli_info() will return an empty string.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A character string representing additional information about the most recently executed query.

### Examples

Example #1 $mysqli->info example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");
/* INSERT INTO ... SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");
/* INSERT INTO ... SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));`

The above examples will output:

    Records: 150  Duplicates: 0  Warnings: 0

### See Also

- mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
- mysqli_warning_count() - Returns the number of warnings generated by the most recently executed query
- mysqli_num_rows() - Gets the number of rows in the result set

# mysqli::init

# mysqli_init

(PHP 5, PHP 7, PHP 8)

mysqli::init -- mysqli_init — Initializes MySQLi and returns an object for use with mysqli_real_connect()

### Description

Object-oriented style

#[\Deprecated]
public mysqli::init(): ?bool

Procedural style

mysqli_init(): mysqli|false

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

> Note:

> Any subsequent calls to any mysqli function (except mysqli_options() and mysqli_ssl_set()) will fail until mysqli_real_connect() was called.

### Parameters

This function has no parameters.

### Return Values

mysqli::init() returns `null` on success, or `false` on failure. mysqli_init() returns an object on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The object-oriented style mysqli::init() method has been deprecated. Replace calls to parent::init() with parent::__construct().

### Examples

See mysqli_real_connect().

### See Also

- mysqli_options() - Set options
- mysqli_close() - Closes a previously opened database connection
- mysqli_real_connect() - Opens a connection to the MySQL server
- mysqli_connect() - Alias of mysqli::__construct

# mysqli::$insert_id

# mysqli_insert_id

(PHP 5, PHP 7, PHP 8)

mysqli::$insert_id -- mysqli_insert_id — Returns the value generated for an AUTO_INCREMENT column by the last query

### Description

Object-oriented style

int|string $mysqli->insert_id;

Procedural style

mysqli_insert_id(mysqli `$mysql`): int|string

Returns the ID generated by an `INSERT` or `UPDATE` query on a table with a column having the `AUTO_INCREMENT` attribute. In the case of a multiple-row `INSERT` statement, it returns the first automatically generated value that was successfully inserted.

Performing an `INSERT` or `UPDATE` statement using the `LAST_INSERT_ID()` MySQL function will also modify the value returned by mysqli_insert_id(). If `LAST_INSERT_ID(expr)` was used to generate the value of `AUTO_INCREMENT`, it returns the value of the last `expr` instead of the generated `AUTO_INCREMENT` value.

Returns `0` if the previous statement did not change an `AUTO_INCREMENT` value. mysqli_insert_id() must be called immediately after the statement that generated the value.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

The value of the `AUTO_INCREMENT` field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an `AUTO_INCREMENT` value.

Only statements issued using the current connection affect the return value. The value is not affected by statements issued using other connections or clients.

> Note:

> If the number is greater than the maximum int value, it will be returned as a string.

### Examples

Example #1 $mysqli->insert_id example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf("New record has ID %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);
printf("New record has ID %d.\n", mysqli_insert_id($link));
/* drop table */
mysqli_query($link, "DROP TABLE myCity");`

The above examples will output:

    New record has ID 1.

# mysqli::kill

# mysqli_kill

(PHP 5, PHP 7, PHP 8)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Warning

This function has been DEPRECATED as of PHP 8.4.0. Relying on this function is highly discouraged.

### Description

Object-oriented style

#[\Deprecated]
public mysqli::kill(int `$process_id`): bool

Procedural style

#[\Deprecated]
mysqli_kill(mysqli `$mysql`, int `$process_id`): bool

This function is used to ask the server to kill a MySQL thread specified by the `process_id` parameter. This value must be retrieved by calling the mysqli_thread_id() function.

To stop a running query you should use the SQL command `KILL QUERY processid`.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.4.0 | Both mysqli::kill() and mysqli_kill() are now deprecated. Use the `KILL` SQL command instead.

### Examples

Example #1 mysqli::kill() example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = $mysqli->thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = mysqli_thread_id($link);
/* Kill connection */
mysqli_kill($link, $thread_id);
/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error: MySQL server has gone away

### See Also

- mysqli_thread_id() - Returns the thread ID for the current connection

# mysqli::more_results

# mysqli_more_results

(PHP 5, PHP 7, PHP 8)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

### Description

Object-oriented style

public mysqli::more_results(): bool

Procedural style

mysqli_more_results(mysqli `$mysql`): bool

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `true` if one or more result sets (including errors) are available from a previous call to mysqli_multi_query(), otherwise `false`.

### Examples

See mysqli_multi_query().

### See Also

- mysqli_multi_query() - Performs one or more queries on the database
- mysqli_next_result() - Prepare next result from multi_query
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli::multi_query

# mysqli_multi_query

(PHP 5, PHP 7, PHP 8)

mysqli::multi_query -- mysqli_multi_query — Performs one or more queries on the database

### Description

Object-oriented style

public mysqli::multi_query(string `$query`): bool

Procedural style

mysqli_multi_query(mysqli `$mysql`, string `$query`): bool

Executes one or multiple queries which are concatenated by a semicolon.

Warning

# Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

Queries are sent in a single call to the database and processed sequentially. mysqli_multi_query() waits for the first query to complete before returning control to PHP. In the meantime, the MySQL server will continue processing the remaining queries asynchronously of PHP and make the results available for fetching.

It is recommended to use do-while to process multiple queries. The connection will be busy until all queries have completed and their results are fetched to PHP. No other statement can be issued on the same connection until all queries are processed. To proceed to the next query in the sequence, use mysqli_next_result(). If the next result is not ready yet, mysqli will wait for the response from the MySQL server. To check if there are more results, use mysqli_more_results().

For queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, mysqli_use_result() or mysqli_store_result() can be used to retrieve the result set. For queries which do not produce a result set, the same functions can be used to retrieve information such as the number of affected rows.

Tip

Executing `CALL` statements for stored procedures can produce multiple result sets. If the stored procedure contains `SELECT` statements, the result sets are returned in the order that they are produced as the procedure executes. In general, the caller cannot know how many result sets a procedure will return and must be prepared to retrieve multiple results. The final result from the procedure is a status result that includes no result set. The status indicates whether the procedure succeeded or an error occurred.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`query`

  A string containing the queries to be executed. Multiple queries must be separated by a semicolon.

### Return Values

Returns `false` if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::multi_query() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
$mysqli->multi_query($query);
do {
/* store the result set in PHP */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
mysqli_multi_query($link, $query);
do {
/* store the result set in PHP */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));`

The above examples will output something similar to:

    my_user@localhost
    -----------------
    Amersfoort
    Maastricht
    Dordrecht
    Leiden
    Haarlemmermeer

### See Also

- mysqli_query() - Performs a query on the database
- mysqli_use_result() - Initiate a result set retrieval
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_next_result() - Prepare next result from multi_query
- mysqli_more_results() - Check if there are any more query results from a multi query

# mysqli::next_result

# mysqli_next_result

(PHP 5, PHP 7, PHP 8)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

### Description

Object-oriented style

public mysqli::next_result(): bool

Procedural style

mysqli_next_result(mysqli `$mysql`): bool

Prepares next result set from a previous call to mysqli_multi_query() which can be retrieved by mysqli_store_result() or mysqli_use_result().

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `true` on success or `false` on failure. Also returns `false` if the next statement resulted in an error, unlike mysqli_more_results().

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

See mysqli_multi_query().

### See Also

- mysqli_multi_query() - Performs one or more queries on the database
- mysqli_more_results() - Check if there are any more query results from a multi query
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli::options

# mysqli_options

(PHP 5, PHP 7, PHP 8)

mysqli::options -- mysqli_options — Set options

### Description

Object-oriented style

public mysqli::options(int `$option`, string|int `$value`): bool

Procedural style

mysqli_options(mysqli `$mysql`, int `$option`, string|int `$value`): bool

Used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

mysqli_options() should be called after mysqli_init() and before mysqli_real_connect().

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`option`

  The option that you want to set. It can be one of the following values:

  Valid options
  Name | Description
  --- | ---
  `MYSQLI_OPT_CONNECT_TIMEOUT` | Connection timeout in seconds
  `MYSQLI_OPT_READ_TIMEOUT` | Command execution result timeout in seconds. Available as of PHP 7.2.0.
  `MYSQLI_OPT_LOCAL_INFILE` | Enable/disable use of `LOAD LOCAL INFILE`
  `MYSQLI_OPT_LOAD_DATA_LOCAL_DIR` | Directory to be used for `LOAD DATA LOCAL INFILE`.
  `MYSQLI_INIT_COMMAND` | Command to execute after when connecting to MySQL server
  `MYSQLI_SET_CHARSET_NAME` | The charset to be set as default.
  `MYSQLI_READ_DEFAULT_FILE` | Read options from named option file instead of my.cnf Not supported by mysqlnd.
  `MYSQLI_READ_DEFAULT_GROUP` | Read options from the named group from my.cnf or the file specified with `MYSQL_READ_DEFAULT_FILE`. Not supported by mysqlnd.
  `MYSQLI_SERVER_PUBLIC_KEY` | RSA public key file used with the SHA-256 based authentication.
  `MYSQLI_OPT_NET_CMD_BUFFER_SIZE` | The size of the internal command/network buffer. Only valid for mysqlnd.
  `MYSQLI_OPT_NET_READ_BUFFER_SIZE` | Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.
  `MYSQLI_OPT_INT_AND_FLOAT_NATIVE` | Convert integer and float columns back to PHP numbers when using non-prepared statements. Only valid for mysqlnd.
  `MYSQLI_OPT_SSL_VERIFY_SERVER_CERT` | Whether to verify server certificate or not.
  `MYSQLI_OPT_CAN_HANDLE_EXPIRED_PASSWORDS` | Whether the client should accept expired passwords.
  `1` | Whether to use network communication compression.

`value`

  The value for the option.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

See mysqli_real_connect().

### Notes

> Note:

> MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

> Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

### See Also

- mysqli_init() - Initializes MySQLi and returns an object for use with mysqli_real_connect()
- mysqli_real_connect() - Opens a connection to the MySQL server

# mysqli::ping

# mysqli_ping

(PHP 5, PHP 7, PHP 8)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Warning

This function has been DEPRECATED as of PHP 8.4.0. Relying on this function is highly discouraged.

### Description

Object-oriented style

#[\Deprecated]
public mysqli::ping(): bool

Procedural style

#[\Deprecated]
mysqli_ping(mysqli `$mysql`): bool

Checks whether the connection to the server is working. If it has gone down and global option mysqli.reconnect is enabled, an automatic reconnection is attempted.

> Note: The php.ini setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.4.0 | Both mysqli::ping() and mysqli_ping() are now deprecated. The `reconnect` feature has not been available as of PHP 8.2.0, making this function obsolete.

### Examples

Example #1 mysqli::ping() example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* check if server is alive */
if ($mysqli->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Our connection is ok!

# mysqli::poll

# mysqli_poll

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::poll -- mysqli_poll — Poll connections

### Description

Object-oriented style

public static mysqli::poll(
?array `&$read`,
?array `&$error`,
array `&$reject`,
int `$seconds`,
int `$microseconds` = 0
): int|false

Procedural style

mysqli_poll(
?array `&$read`,
?array `&$error`,
array `&$reject`,
int `$seconds`,
int `$microseconds` = 0
): int|false

Poll connections. The method can be used as static.

> Note:

> Available only with mysqlnd.

### Parameters

`read`

  List of connections to check for outstanding results that can be read.

`error`

  List of connections on which an error occurred, for example, query failure or lost connection.

`reject`

  List of connections rejected because no asynchronous query has been run on for which the function could poll results.

`seconds`

  Maximum number of seconds to wait, must be non-negative.

`microseconds`

  Maximum number of microseconds to wait, must be non-negative.

### Return Values

Returns number of ready connections upon success, `false` otherwise.

### Errors/Exceptions

A ValueError is thrown when neither the `read` nor `error` arguments are passed.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a ValueError exception when neither the `read` nor `error` arguments are passed.

### Examples

Example #1 A mysqli_poll() example

`<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
$links = $errors = $reject = array();
foreach ($all_links as $link) {
$links[] = $errors[] = $reject[] = $link;
}
if (!mysqli_poll($links, $errors, $reject, 1)) {
continue;
}
foreach ($links as $link) {
if ($result = $link->reap_async_query()) {
print_r($result->fetch_row());
if (is_object($result))
mysqli_free_result($result);
} else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
$processed++;
}
} while ($processed < count($all_links));
?>`

The above example will output:

    Array
    (
        [0] => test
    )

### See Also

- mysqli_query() - Performs a query on the database
- mysqli_reap_async_query() - Get result from async query

# mysqli::prepare

# mysqli_prepare

(PHP 5, PHP 7, PHP 8)

mysqli::prepare -- mysqli_prepare — Prepares an SQL statement for execution

### Description

Object-oriented style

public mysqli::prepare(string `$query`): mysqli_stmt|false

Procedural style

mysqli_prepare(mysqli `$mysql`, string `$query`): mysqli_stmt|false

Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

The statement template can contain zero or more question mark (`?`) parameter markers⁠—also called placeholders. The parameter markers must be bound to application variables using mysqli_stmt_bind_param() before executing the statement.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`query`

  The query, as a string. It must consist of a single SQL statement.

  The SQL statement may contain zero or more parameter markers represented by question mark (`?`) characters at the appropriate positions.

  > Note:

  > The markers are legal only in certain places in SQL statements. For example, they are permitted in the `VALUES()` list of an `INSERT` statement (to specify column values for a row), or in a comparison with a column in a `WHERE` clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

### Return Values

mysqli_prepare() returns a statement object or `false` if an error occurred.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::prepare() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is in district %s\n", $city, $district);`

The above examples will output:

    Amersfoort is in district Utrecht

### See Also

- mysqli_stmt_execute() - Executes a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
- mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
- mysqli_stmt_close() - Closes a prepared statement

# mysqli::query

# mysqli_query

(PHP 5, PHP 7, PHP 8)

mysqli::query -- mysqli_query — Performs a query on the database

### Description

Object-oriented style

public mysqli::query(string `$query`, int `$result_mode` = `MYSQLI_STORE_RESULT`): mysqli_result|bool

Procedural style

mysqli_query(mysqli `$mysql`, string `$query`, int `$result_mode` = `MYSQLI_STORE_RESULT`): mysqli_result|bool

Performs a `query` against the database.

Warning

# Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling mysqli_real_query() followed by either mysqli_use_result() or mysqli_store_result().

> Note:

> In the case where a statement is passed to mysqli_query() that is longer than `max_allowed_packet` of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (`mysqlnd`) or MySQL Client Library (`libmysqlclient`). The behavior is as follows:

> - `mysqlnd` on Linux returns an error code of 1153. The error message means got a packet bigger than `max_allowed_packet` bytes.

> - `mysqlnd` on Windows returns an error code 2006. This error message means server has gone away.

> - `libmysqlclient` on all platforms returns an error code 2006. This error message means server has gone away.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`query`

  The query string.

`result_mode`

  The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server.

  `MYSQLI_STORE_RESULT` (default) - returns a mysqli_result object with buffered result set.

  `MYSQLI_USE_RESULT` - returns a mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error `Commands out of sync`. To avoid the error all records must be fetched from the server or the result set must be discarded by calling mysqli_free_result().

  `MYSQLI_ASYNC` (available with mysqlnd) - the query is performed asynchronously and no result set is immediately returned. mysqli_poll() is then used to get results from such queries. Used in combination with either `MYSQLI_STORE_RESULT` or `MYSQLI_USE_RESULT` constant.

### Return Values

Returns `false` on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return `true`.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::query() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Create table doesn't return a resultset */
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");
/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", $result->num_rows);
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT);
/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
$mysqli->query("SET @a:='this will not work'");`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Create table doesn't return a resultset */
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");
/* Select queries return a resultset */
$result = mysqli_query($link, "SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT);
/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
mysqli_query($link, "SET @a:='this will not work'");`

The above examples will output something similar to:

    Table myCity successfully created.
    Select returned 10 rows.

    Fatal error: Uncaught mysqli_sql_exception: Commands out of sync; you can't run this command now in...

### See Also

- mysqli_execute_query() - Prepares, binds parameters, and executes SQL statement
- mysqli_real_query() - Execute an SQL query
- mysqli_multi_query() - Performs one or more queries on the database
- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_free_result() - Frees the memory associated with a result

# mysqli::real_connect

# mysqli_real_connect

(PHP 5, PHP 7, PHP 8)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to the MySQL server

### Description

Object-oriented style

public mysqli::real_connect(
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`,
int `$flags` = 0
): bool

Procedural style

mysqli_real_connect(
mysqli `$mysql`,
?string `$hostname` = `null`,
?string `$username` = `null`,
#[\SensitiveParameter] ?string `$password` = `null`,
?string `$database` = `null`,
?int `$port` = `null`,
?string `$socket` = `null`,
int `$flags` = 0
): bool

Opens a connection to the MySQL database server with optional connection options.

This function differs from mysqli_connect():

- mysqli_real_connect() needs a valid object which has to be created by mysqli_init().

- There is a `flags` parameter.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`hostname`

  Can be either a host name or an IP address. When passing `null`, the value is retrieved from mysqli.default_host. When possible, pipes will be used instead of the TCP/IP protocol. The TCP/IP protocol is used if a host name and port number are provided together e.g. `localhost:3308`.

`username`

  The MySQL username or `null` to assume the username based on the mysqli.default_user ini option.

`password`

  The MySQL password or `null` to assume the password based on the mysqli.default_pw ini option.

`database`

  The default database to be used when performing queries or `null`.

`port`

  The port number to attempt to connect to the MySQL server or `null` to assume the port based on the mysqli.default_port ini option.

`socket`

  The socket or named pipe that should be used or `null` to assume the socket based on the mysqli.default_socket ini option.

  > Note:

  > Specifying the `socket` parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the `hostname` parameter.

`flags`

  With the parameter `flags` you can set different connection options:

  Supported flags
  Name | Description
  --- | ---
  `MYSQLI_CLIENT_COMPRESS` | Use compression protocol
  `MYSQLI_CLIENT_FOUND_ROWS` | Return the number of matched rows, not the number of affected rows
  `MYSQLI_CLIENT_IGNORE_SPACE` | Allow spaces after function names. Makes all function names reserved words.
  `MYSQLI_CLIENT_INTERACTIVE` | Allow `interactive_timeout` seconds (instead of `wait_timeout` seconds) of inactivity before closing the connection
  `MYSQLI_CLIENT_SSL` | Use SSL (encryption)
  `MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT` | Like `MYSQLI_CLIENT_SSL`, but disables validation of the provided SSL certificate. This is only for installations using MySQL Native Driver and MySQL 5.6 or later.

  > Note:

  > For security reasons the `MULTI_STATEMENT` flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
7.4.0 | All parameters are now nullable.

### Examples

Example #1 mysqli::real_connect() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db', null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
echo 'Success... ' . $mysqli->host_info . "\n";`

Object-oriented style when extending mysqli class

`<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db)
{
parent::__construct();
parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
parent::real_connect($host, $user, $pass, $db, null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
}
}
$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');
echo 'Success... ' . $db->host_info . "\n";`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db', null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
echo 'Success... ' . mysqli_get_host_info($link) . "\n";`

The above examples will output:

    Success... MySQL host info: localhost via TCP/IP

### Notes

> Note:

> MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

> Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

### See Also

- mysqli_connect() - Alias of mysqli::__construct
- mysqli_init() - Initializes MySQLi and returns an object for use with mysqli_real_connect()
- mysqli_options() - Set options
- mysqli_ssl_set() - Used for establishing secure connections using SSL
- mysqli_close() - Closes a previously opened database connection

# mysqli::real_escape_string

# mysqli_real_escape_string

(PHP 5, PHP 7, PHP 8)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

### Description

Object-oriented style

public mysqli::real_escape_string(string `$string`): string

Procedural style

mysqli_real_escape_string(mysqli `$mysql`, string `$string`): string

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to produce an escaped SQL string, taking into account the current character set of the connection.

Caution

# Security: the default character set

The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`string`

  The string to be escaped.

  Characters encoded are `NUL (ASCII 0)`, `\n`, `\r`, `\`, `'`, `"`, and ``CTRL`+`Z``.

### Return Values

Returns an escaped string.

### Examples

Example #1 mysqli::real_escape_string() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
$mysqli->real_escape_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
mysqli_real_escape_string($mysqli, $city));
$result = mysqli_query($mysqli, $query);
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = mysqli_query($mysqli, $query);`

The above examples will output something similar to:

    Select returned 1 rows.

    Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in...

### See Also

- mysqli_set_charset() - Sets the client character set

# mysqli::real_query

# mysqli_real_query

(PHP 5, PHP 7, PHP 8)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

### Description

Object-oriented style

public mysqli::real_query(string `$query`): bool

Procedural style

mysqli_real_query(mysqli `$mysql`, string `$query`): bool

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.

Warning

# Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

In order to determine if a given query should return a result set or not, see mysqli_field_count().

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`query`

  The query string.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### See Also

- mysqli_query() - Performs a query on the database
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli::reap_async_query

# mysqli_reap_async_query

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

### Description

Object-oriented style

public mysqli::reap_async_query(): mysqli_result|bool

Procedural style

mysqli_reap_async_query(mysqli `$mysql`): mysqli_result|bool

Get result from async query.

> Note:

> Available only with mysqlnd.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns `false` on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, mysqli_reap_async_query() will return a mysqli_result object. For other successful queries, mysqli_reap_async_query() will return `true`.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### See Also

- mysqli_poll() - Poll connections

# mysqli::refresh

# mysqli_refresh

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::refresh -- mysqli_refresh — Refreshes

Warning

This function has been DEPRECATED as of PHP 8.4.0. Relying on this function is highly discouraged.

### Description

Object-oriented style

#[\Deprecated]
public mysqli::refresh(int `$flags`): bool

Procedural style

#[\Deprecated]
mysqli_refresh(mysqli `$mysql`, int `$flags`): bool

Flushes tables or caches, or resets the replication server information.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`flags`

  The options to refresh, using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation.

  See also the official » MySQL Refresh documentation.

### Return Values

`true` if the refresh was a success, otherwise `false`

### Changelog

Version | Description
--- | ---
8.4.0 | Both mysqli::refresh() and mysqli_refresh() are now deprecated. Use `FLUSH` SQL commands instead.

### See Also

- mysqli_poll() - Poll connections

# mysqli::release_savepoint

# mysqli_release_savepoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::release_savepoint -- mysqli_release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction

### Description

Object-oriented style

public mysqli::release_savepoint(string `$name`): bool

Procedural style:

mysqli_release_savepoint(mysqli `$mysql`, string `$name`): bool

This function is identical to executing `$mysqli->query("RELEASE SAVEPOINT `$name`");`. This function does not trigger commit or rollback.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`name`

  The identifier of the savepoint.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mysqli_savepoint() - Set a named transaction savepoint

# mysqli::rollback

# mysqli_rollback

(PHP 5, PHP 7, PHP 8)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

### Description

Object-oriented style

public mysqli::rollback(int `$flags` = 0, ?string `$name` = `null`): bool

Procedural style

mysqli_rollback(mysqli `$mysql`, int `$flags` = 0, ?string `$name` = `null`): bool

Rollbacks the current transaction for the database.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`flags`

  A bitmask of `MYSQLI_TRANS_COR_*` constants.

`name`

  If provided then `ROLLBACK/*name*/` is executed.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.0.0 | `name` is now nullable.

### Examples

See the mysqli::begin_transaction() example.

### Notes

> Note:

> This function does not work with non transactional table types (like MyISAM or ISAM).

### See Also

- mysqli_begin_transaction() - Starts a transaction
- mysqli_commit() - Commits the current transaction
- mysqli_autocommit() - Turns on or off auto-committing database modifications
- mysqli_release_savepoint() - Removes the named savepoint from the set of savepoints of the current transaction

# mysqli::savepoint

# mysqli_savepoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::savepoint -- mysqli_savepoint — Set a named transaction savepoint

### Description

Object-oriented style

public mysqli::savepoint(string `$name`): bool

Procedural style:

mysqli_savepoint(mysqli `$mysql`, string `$name`): bool

This function is identical to executing `$mysqli->query("SAVEPOINT `$name`");`

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`name`

  The identifier of the savepoint.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mysqli_release_savepoint() - Removes the named savepoint from the set of savepoints of the current transaction

# mysqli::select_db

# mysqli_select_db

(PHP 5, PHP 7, PHP 8)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

### Description

Object-oriented style

public mysqli::select_db(string `$database`): bool

Procedural style

mysqli_select_db(mysqli `$mysql`, string `$database`): bool

Selects the default database to be used when performing queries against the database connection.

> Note:

> This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`database`

  The database name.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::select_db() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
/* change default database to "world" */
$mysqli->select_db("world");
/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
/* change default database to "world" */
mysqli_select_db($link, "world");
/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);`

The above examples will output:

    Default database is test.
    Default database is world.

### See Also

- mysqli_connect() - Alias of mysqli::__construct
- mysqli_real_connect() - Opens a connection to the MySQL server

# mysqli::set_charset

# mysqli_set_charset

(PHP 5 >= 5.0.5, PHP 7, PHP 8)

mysqli::set_charset -- mysqli_set_charset — Sets the client character set

### Description

Object-oriented style

public mysqli::set_charset(string `$charset`): bool

Procedural style

mysqli_set_charset(mysqli `$mysql`, string `$charset`): bool

Sets the character set to be used when sending data from and to the database server.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`charset`

  The desired character set.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::set_charset() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8mb4 */
$mysqli->set_charset("utf8mb4");
printf("Current character set: %s\n", $mysqli->character_set_name());`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');
printf("Initial character set: %s\n", mysqli_character_set_name($link));
/* change character set to utf8mb4 */
mysqli_set_charset($link, "utf8mb4");
printf("Current character set: %s\n", mysqli_character_set_name($link));`

The above examples will output something similar to:

    Initial character set: latin1
    Current character set: utf8mb4

### Notes

> Note:

> This is the preferred way to change the charset. Using mysqli_query() to set it (such as `SET NAMES utf8`) is not recommended. See the MySQL character set concepts section for more information.

### See Also

- mysqli_character_set_name() - Returns the current character set of the database connection
- mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
- MySQL character set concepts
- » List of character sets that MySQL supports

# mysqli::$sqlstate

# mysqli_sqlstate

(PHP 5, PHP 7, PHP 8)

mysqli::$sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

### Description

Object-oriented style

string $mysqli->sqlstate;

Procedural style

mysqli_sqlstate(mysqli `$mysql`): string

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. `'00000'` means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

> Note:

> Note that not all MySQL errors are yet mapped to SQLSTATE's. The value `HY000` (general error) is used for unmapped errors.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. `'00000'` means no error.

### Examples

Example #1 $mysqli->sqlstate example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Table City already exists, so we should get an error */
try {
$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Table City already exists, so we should get an error */
try {
mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}`

The above examples will output:

    Error - SQLSTATE 42S01.

### See Also

- mysqli_errno() - Returns the error code for the most recent function call
- mysqli_error() - Returns a string description of the last error

# mysqli::ssl_set

# mysqli_ssl_set

(PHP 5, PHP 7, PHP 8)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

### Description

Object-oriented style

public mysqli::ssl_set(
?string `$key`,
?string `$certificate`,
?string `$ca_certificate`,
?string `$ca_path`,
?string `$cipher_algos`
): true

Procedural style

mysqli_ssl_set(
mysqli `$mysql`,
?string `$key`,
?string `$certificate`,
?string `$ca_certificate`,
?string `$ca_path`,
?string `$cipher_algos`
): true

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`key`

  The path name to the key file.

`certificate`

  The path name to the certificate file.

`ca_certificate`

  The path name to the certificate authority file.

`ca_path`

  The pathname to a directory that contains trusted SSL CA certificates in PEM format.

`cipher_algos`

  A list of allowable ciphers to use for SSL encryption.

### Return Values

Always returns `true`. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

### See Also

- mysqli_options() - Set options
- mysqli_real_connect() - Opens a connection to the MySQL server

# mysqli::stat

# mysqli_stat

(PHP 5, PHP 7, PHP 8)

mysqli::stat -- mysqli_stat — Gets the current system status

### Description

Object-oriented style

public mysqli::stat(): string|false

Procedural style

mysqli_stat(mysqli `$mysql`): string|false

mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

A string describing the server status. `false` if an error occurred.

### Examples

Example #1 mysqli::stat() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
printf("System status: %s\n", $mysqli->stat());`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
printf("System status: %s\n", mysqli_stat($link));`

The above examples will output:

    System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
    Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
    Memory in use: 8496K  Max memory used: 8560K

### See Also

- mysqli_get_server_info() - Returns the version of the MySQL server

# mysqli::stmt_init

# mysqli_stmt_init

(PHP 5, PHP 7, PHP 8)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

### Description

Object-oriented style

public mysqli::stmt_init(): mysqli_stmt|false

Procedural style

mysqli_stmt_init(mysqli `$mysql`): mysqli_stmt|false

Allocates and initializes a statement object suitable for mysqli_stmt_prepare().

> Note:

> Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns an object.

### See Also

- mysqli_stmt_prepare() - Prepares an SQL statement for execution

# mysqli::store_result

# mysqli_store_result

(PHP 5, PHP 7, PHP 8)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

### Description

Object-oriented style

public mysqli::store_result(int `$mode` = 0): mysqli_result|false

Procedural style

mysqli_store_result(mysqli `$mysql`, int `$mode` = 0): mysqli_result|false

Transfers the result set from the last query on the database connection represented by the `mysql` parameter to be used with the mysqli_data_seek() function.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`mode`

  The option that you want to set. As of PHP 8.1, this parameter has no effect. It can be one of the following values:

  Valid options
  Name | Description
  --- | ---
  `MYSQLI_STORE_RESULT_COPY_DATA` | Copy results from the internal mysqlnd buffer into the PHP variables fetched. By default, mysqlnd will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier (available with mysqlnd only)

### Return Values

Returns a buffered result object or `false` if an error occurred.

> Note:

> mysqli_store_result() returns `false` in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns `false` if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning `false` after successful call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.4.0 | Passing the `mode` parameter is now deprecated. The parameter has had no effect as of PHP 8.1.0.

### Examples

See mysqli_multi_query().

### Notes

> Note:

> Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transferring large result sets using the mysqli_store_result() this becomes particularly important.

### See Also

- mysqli_real_query() - Execute an SQL query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli::$thread_id

# mysqli_thread_id

(PHP 5, PHP 7, PHP 8)

mysqli::$thread_id -- mysqli_thread_id — Returns the thread ID for the current connection

### Description

Object-oriented style

int $mysqli->thread_id;

Procedural style

mysqli_thread_id(mysqli `$mysql`): int

The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be different. Therefore you should get the thread ID only when you need it.

> Note:

> The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

> To kill a running query you can use the SQL command `KILL QUERY processid`.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Returns the Thread ID for the current connection.

### Examples

Example #1 $mysqli->thread_id example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = $mysqli->thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = mysqli_thread_id($link);
/* Kill connection */
mysqli_kill($link, $thread_id);
/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error: MySQL server has gone away

### See Also

- mysqli_kill() - Asks the server to kill a MySQL thread

# mysqli::thread_safe

# mysqli_thread_safe

(PHP 5, PHP 7, PHP 8)

mysqli::thread_safe -- mysqli_thread_safe — Returns whether thread safety is given or not

### Description

Object-oriented style

public mysqli::thread_safe(): bool

Procedural style

mysqli_thread_safe(): bool

Tells whether the client library is compiled as thread-safe.

### Parameters

This function has no parameters.

### Return Values

`true` if the client library is thread-safe, otherwise `false`.

# mysqli::use_result

# mysqli_use_result

(PHP 5, PHP 7, PHP 8)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

### Description

Object-oriented style

public mysqli::use_result(): mysqli_result|false

Procedural style

mysqli_use_result(mysqli `$mysql`): mysqli_result|false

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection.

Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

> Note:

> The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

### Parameters

This function has no parameters.

### Return Values

Returns an unbuffered result object or `false` if an error occurred.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli::use_result() example

Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>`

Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_use_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    my_user@localhost
    -----------------
    Amersfoort
    Maastricht
    Dordrecht
    Leiden
    Haarlemmermeer

### See Also

- mysqli_real_query() - Execute an SQL query
- mysqli_store_result() - Transfers a result set from the last query

# mysqli::$warning_count

# mysqli_warning_count

(PHP 5, PHP 7, PHP 8)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings generated by the most recently executed query

### Description

Object-oriented style

int $mysqli->warning_count;

Procedural style

mysqli_warning_count(mysqli `$mysql`): int

Returns the number of warnings generated by the most recently executed query.

> Note: For retrieving warning messages the following SQL command can be used: `SHOW WARNINGS [limit row_count]`.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

### Return Values

Number of warnings or zero if there are no warnings.

### Examples

Example #1 $mysqli->warning_count example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("SELECT 42/0");
if ($mysqli->warning_count > 0) {
$result = $mysqli->query("SHOW WARNINGS");
$row = $result->fetch_row();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "SELECT 42/0");
if (mysqli_warning_count($link) > 0) {
$result = mysqli_query($link, "SHOW WARNINGS");
$row = mysqli_fetch_row($result);
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}`

The above examples will output:

    Warning (1365): Division by 0

### See Also

- mysqli_errno() - Returns the error code for the most recent function call
- mysqli_error() - Returns a string description of the last error
- mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

## Table of Contents

- mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
- mysqli::autocommit — Turns on or off auto-committing database modifications
- mysqli::begin_transaction — Starts a transaction
- mysqli::change_user — Changes the user of the database connection
- mysqli::character_set_name — Returns the current character set of the database connection
- mysqli::close — Closes a previously opened database connection
- mysqli::commit — Commits the current transaction
- mysqli::$connect_errno — Returns the error code from last connect call
- mysqli::$connect_error — Returns a description of the last connection error
- mysqli::__construct — Open a new connection to the MySQL server
- mysqli::debug — Performs debugging operations
- mysqli::dump_debug_info — Dump debugging information into the log
- mysqli::$errno — Returns the error code for the most recent function call
- mysqli::$error — Returns a string description of the last error
- mysqli::$error_list — Returns a list of errors from the last command executed
- mysqli::execute_query — Prepares, binds parameters, and executes SQL statement
- mysqli::$field_count — Returns the number of columns for the most recent query
- mysqli::get_charset — Returns a character set object
- mysqli::$client_info — Get MySQL client info
- mysqli::$client_version — Returns the MySQL client version as an integer
- mysqli::get_connection_stats — Returns statistics about the client connection
- mysqli::$host_info — Returns a string representing the type of connection used
- mysqli::$protocol_version — Returns the version of the MySQL protocol used
- mysqli::$server_info — Returns the version of the MySQL server
- mysqli::$server_version — Returns the version of the MySQL server as an integer
- mysqli::get_warnings — Get result of SHOW WARNINGS
- mysqli::$info — Retrieves information about the most recently executed query
- mysqli::init — Initializes MySQLi and returns an object for use with mysqli_real_connect()
- mysqli::$insert_id — Returns the value generated for an AUTO_INCREMENT column by the last query
- mysqli::kill — Asks the server to kill a MySQL thread
- mysqli::more_results — Check if there are any more query results from a multi query
- mysqli::multi_query — Performs one or more queries on the database
- mysqli::next_result — Prepare next result from multi_query
- mysqli::options — Set options
- mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
- mysqli::poll — Poll connections
- mysqli::prepare — Prepares an SQL statement for execution
- mysqli::query — Performs a query on the database
- mysqli::real_connect — Opens a connection to the MySQL server
- mysqli::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
- mysqli::real_query — Execute an SQL query
- mysqli::reap_async_query — Get result from async query
- mysqli::refresh — Refreshes
- mysqli::release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction
- mysqli::rollback — Rolls back current transaction
- mysqli::savepoint — Set a named transaction savepoint
- mysqli::select_db — Selects the default database for database queries
- mysqli::set_charset — Sets the client character set
- mysqli::$sqlstate — Returns the SQLSTATE error from previous MySQL operation
- mysqli::ssl_set — Used for establishing secure connections using SSL
- mysqli::stat — Gets the current system status
- mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
- mysqli::store_result — Transfers a result set from the last query
- mysqli::$thread_id — Returns the thread ID for the current connection
- mysqli::thread_safe — Returns whether thread safety is given or not
- mysqli::use_result — Initiate a result set retrieval
- mysqli::$warning_count — Returns the number of warnings generated by the most recently executed query

# The mysqli_stmt class

(PHP 5, PHP 7, PHP 8)

## Introduction

Represents a prepared statement.

## Class synopsis

class mysqli_stmt {
/* Properties */
public readonly int|string $affected_rows;
public readonly int|string $insert_id;
public readonly int|string $num_rows;
public readonly int $param_count;
public readonly int $field_count;
public readonly int $errno;
public readonly string $error;
public readonly array $error_list;
public readonly string $sqlstate;
public int $id;
/* Methods */
public __construct(mysqli `$mysql`, ?string `$query` = `null`)
public attr_get(int `$attribute`): int
public attr_set(int `$attribute`, int `$value`): bool
public bind_param(string `$types`, mixed `&$var`, mixed `&...$vars`): bool
public bind_result(mixed `&$var`, mixed `&...$vars`): bool
public close(): true
public data_seek(int `$offset`): void
public execute(?array `$params` = `null`): bool
public fetch(): ?bool
public free_result(): void
public get_result(): mysqli_result|false
public get_warnings(): mysqli_warning|false
public more_results(): bool
public next_result(): bool
public num_rows(): int|string
public prepare(string `$query`): bool
public reset(): bool
public result_metadata(): mysqli_result|false
public send_long_data(int `$param_num`, string `$data`): bool
public store_result(): bool
}

## Properties

id

  Stores the statement ID.

# mysqli_stmt::$affected_rows

# mysqli_stmt_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed

### Description

Object-oriented style

int|string $mysqli_stmt->affected_rows;

Procedural style

mysqli_stmt_affected_rows(mysqli_stmt `$statement`): int|string

Returns the number of rows affected by `INSERT`, `UPDATE`, or `DELETE` query. Works like mysqli_stmt_num_rows() for `SELECT` statements.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an `UPDATE` statement, no rows matched the `WHERE` clause in the query or that no query has yet been executed. `-1` indicates that the query returned an error or that, for a `SELECT` query, mysqli_stmt_affected_rows() was called prior to calling mysqli_stmt_store_result().

> Note:

> If the number of affected rows is greater than maximum PHP int value, the number of affected rows will be returned as a string value.

### Examples

Example #1 mysqli_stmt_affected_rows() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = $mysqli->prepare($query);
/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("Rows inserted: %d\n", $stmt->affected_rows);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = mysqli_prepare($link, $query);
/* Bind variable for placeholder */
$code = 'A%';
mysqli_stmt_bind_param($stmt, "s", $code);
/* execute statement */
mysqli_stmt_execute($stmt);
printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));`

The above examples will output:

    Rows inserted: 17

### See Also

- mysqli_stmt_num_rows() - Returns the number of rows fetched from the server
- mysqli_stmt_store_result() - Stores a result set in an internal buffer

# mysqli_stmt::attr_get

# mysqli_stmt_attr_get

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

### Description

Object-oriented style

public mysqli_stmt::attr_get(int `$attribute`): int

Procedural style

mysqli_stmt_attr_get(mysqli_stmt `$statement`, int `$attribute`): int

Gets the current value of a statement attribute.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`attribute`

  The attribute that you want to get.

### Return Values

Returns the value of the attribute.

# mysqli_stmt::attr_set

# mysqli_stmt_attr_set

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

### Description

Object-oriented style

public mysqli_stmt::attr_set(int `$attribute`, int `$value`): bool

Procedural style

mysqli_stmt_attr_set(mysqli_stmt `$statement`, int `$attribute`, int `$value`): bool

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`attribute`

  The attribute that you want to set. It can have one of the following values:

  Attribute values
  Character | Description
  --- | ---
  MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | Setting to `true` causes mysqli_stmt_store_result() to update the metadata `MYSQL_FIELD->max_length` value.
  MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute() is invoked. `value` can be `MYSQLI_CURSOR_TYPE_NO_CURSOR` (the default) or `MYSQLI_CURSOR_TYPE_READ_ONLY`.
  MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. `value` can be in the range from 1 to the maximum value of unsigned long. The default is 1. Removed as of PHP 8.4.0.

  If you use the `MYSQLI_STMT_ATTR_CURSOR_TYPE` option with `MYSQLI_CURSOR_TYPE_READ_ONLY`, a cursor is opened for the statement when you invoke mysqli_stmt_execute(). If there is already an open cursor from a previous mysqli_stmt_execute() call, it closes the cursor before opening a new one. mysqli_stmt_reset() also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result() closes any open cursor.

  If you open a cursor for a prepared statement, mysqli_stmt_store_result() is unnecessary.

`value`

  The value to assign to the attribute.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### See Also

- » Connector/MySQL mysql_stmt_attr_set()

# mysqli_stmt::bind_param

# mysqli_stmt_bind_param

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

### Description

Object-oriented style

public mysqli_stmt::bind_param(string `$types`, mixed `&$var`, mixed `&...$vars`): bool

Procedural style

mysqli_stmt_bind_param(
mysqli_stmt `$statement`,
string `$types`,
mixed `&$var`,
mixed `&...$vars`
): bool

Bind variables for the parameter markers in the SQL statement prepared by mysqli_prepare() or mysqli_stmt_prepare().

> Note:

> If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify `b` in `types` and use mysqli_stmt_send_long_data() to send the data in packets.

> Note:

> Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`types`

  A string that contains one or more characters which specify the types for the corresponding bind variables:

  Type specification chars
  Character | Description
  --- | ---
  i | corresponding variable has type int
  d | corresponding variable has type float
  s | corresponding variable has type string
  b | corresponding variable is a blob and will be sent in packets

`var`
`vars`

  The number of variables and length of string `types` must match the parameters in the statement.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli_stmt::bind_param() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
$stmt->execute();
printf("%d row inserted.\n", $stmt->affected_rows);
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", $mysqli->affected_rows);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
mysqli_stmt_execute($stmt);
printf("%d row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", mysqli_affected_rows($link));`

The above examples will output:

    1 row inserted.
    1 row deleted.

Example #2 Using `...` to provide arguments

The `...` operator can be used to provide variable-length argument list, e.g. in a `WHERE IN` clause.

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("SELECT Language FROM CountryLanguage WHERE CountryCode IN (?, ?)");
/* Using ... to provide arguments */
$stmt->bind_param('ss', ...['DEU', 'POL']);
$stmt->execute();
$stmt->store_result();
printf("%d rows found.\n", $stmt->num_rows());`

The above examples will output:

    10 rows found.

### See Also

- mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
- mysqli_stmt_execute() - Executes a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_send_long_data() - Send data in blocks
- mysqli_stmt_errno() - Returns the error code for the most recent statement call
- mysqli_stmt_error() - Returns a string description for last statement error

# mysqli_stmt::bind_result

# mysqli_stmt_bind_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

### Description

Object-oriented style

public mysqli_stmt::bind_result(mixed `&$var`, mixed `&...$vars`): bool

Procedural style

mysqli_stmt_bind_result(mysqli_stmt `$statement`, mixed `&$var`, mixed `&...$vars`): bool

Binds columns in the result set to variables.

When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables `var`/`vars`.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

> Note:

> All columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().

> Note:

> Depending on column types bound variables can silently change to the corresponding PHP type.

Tip

This function is useful for simple results. To retrieve iterable result set, or fetch each row as an array or object, use mysqli_stmt_get_result().

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`var`

  The first variable to be bound.

`vars`

  Further variables to be bound.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* prepare statement */
$stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* prepare statement */
$stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
mysqli_stmt_execute($stmt);
/* bind variables to prepared statement */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf("%s %s\n", $col1, $col2);
}`

The above examples will output something similar to:

    AFG Afghanistan
    ALB Albania
    DZA Algeria
    ASM American Samoa
    AND Andorra

### See Also

- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
- mysqli_stmt_execute() - Executes a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_prepare() - Prepares an SQL statement for execution

# mysqli_stmt::close

# mysqli_stmt_close

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

### Description

Object-oriented style

public mysqli_stmt::close(): true

Procedural style

mysqli_stmt_close(mysqli_stmt `$statement`): true

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function now always returns `true`. Previously it returned `false` on failure.

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution

# mysqli_stmt::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::__construct — Constructs a new mysqli_stmt object

### Description

public mysqli_stmt::__construct(mysqli `$mysql`, ?string `$query` = `null`)

This method constructs a new mysqli_stmt object.

### Parameters

`link`

  A valid mysqli object.

`query`

  The query, as a string. If this parameter is `null`, then the constructor behaves identically to mysqli_stmt_init(), otherwise it behaves as per mysqli_prepare().

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.0.0 | `query` is now nullable.

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare

# mysqli_stmt::data_seek

# mysqli_stmt_data_seek

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Adjusts the result pointer to an arbitrary row in the buffered result

### Description

Object-oriented style

public mysqli_stmt::data_seek(int `$offset`): void

Procedural style

mysqli_stmt_data_seek(mysqli_stmt `$statement`, int `$offset`): void

This function moves the result set pointer of the buffered result set to an arbitrary row specified by the `offset` parameter.

This function works only on the buffered internal result set. mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`offset`

  Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

### Return Values

No value is returned.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($name, $code);
$stmt->store_result();
/* seek to row no. 400 */
$stmt->data_seek(399);
$stmt->fetch();
printf("City: %s Countrycode: %s\n", $name, $code);`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $code);
mysqli_stmt_store_result($stmt);
/* seek to row no. 400 */
mysqli_stmt_data_seek($stmt, 399);
mysqli_stmt_fetch($stmt);
printf("City: %s Countrycode: %s\n", $name, $code);`

The above examples will output:

    City: Benin City  Countrycode: NGA

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_store_result() - Stores a result set in an internal buffer
- mysqli_stmt_num_rows() - Returns the number of rows fetched from the server
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_stmt::$errno

# mysqli_stmt_errno

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

### Description

Object-oriented style

int $mysqli_stmt->errno;

Procedural style

mysqli_stmt_errno(mysqli_stmt `$statement`): int

Returns the error code for the most recently invoked statement function that can succeed or fail.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

An error code value. Zero means no error occurred.

### Examples

Example #1 Object-oriented style

`<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %d.\n", $stmt->errno);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %d.\n", mysqli_stmt_errno($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error: 1146.

### See Also

- mysqli_stmt_error() - Returns a string description for last statement error
- mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

# mysqli_stmt::$error

# mysqli_stmt_error

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$error -- mysqli_stmt_error — Returns a string description for last statement error

### Description

Object-oriented style

string $mysqli_stmt->error;

Procedural style

mysqli_stmt_error(mysqli_stmt `$statement`): string

Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

A string that describes the error. An empty string if no error occurred.

### Examples

Example #1 Object-oriented style

`<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->error);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", mysqli_stmt_error($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error: Table 'world.myCountry' doesn't exist.

### See Also

- mysqli_stmt_errno() - Returns the error code for the most recent statement call
- mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

# mysqli_stmt::$error_list

# mysqli_stmt_error_list

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

mysqli_stmt::$error_list -- mysqli_stmt_error_list — Returns a list of errors from the last statement executed

### Description

Object-oriented style

array $mysqli_stmt->error_list;

Procedural style

mysqli_stmt_error_list(mysqli_stmt `$statement`): array

Returns an array of errors for the most recently invoked statement function that can succeed or fail.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

A list of errors, each as an associative array containing the errno, error, and sqlstate.

### Examples

Example #1 Object-oriented style

`<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
echo "Error:\n";
print_r($stmt->error_list);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
echo "Error:\n";
print_r(mysql_stmt_error_list($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error:
    Array
    (
        [0] => Array
            (
                [errno] => 1146
                [sqlstate] => 42S02
                [error] => Table 'world.myCountry' doesn't exist
            )

    )

### See Also

- mysqli_stmt_error() - Returns a string description for last statement error
- mysqli_stmt_errno() - Returns the error code for the most recent statement call
- mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

# mysqli_stmt::execute

# mysqli_stmt_execute

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared statement

### Description

Object-oriented style

public mysqli_stmt::execute(?array `$params` = `null`): bool

Procedural style

mysqli_stmt_execute(mysqli_stmt `$statement`, ?array `$params` = `null`): bool

Executes previously prepared statement. The statement must be successfully prepared prior to execution, using either the mysqli_prepare() or mysqli_stmt_prepare() function, or by passing the second argument to mysqli_stmt::__construct().

If the statement is `UPDATE`, `DELETE`, or `INSERT`, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. If the query yields a result set, it can be fetched using mysqli_stmt_get_result() function or by fetching it row by row directly from the statement using mysqli_stmt_fetch() function.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`params`

  An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.1.0 | The optional `params` parameter has been added.

### Examples

Example #1 Execute a prepared statement with bound variables

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
/* Prepare an insert statement */
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");
/* Bind variables to parameters */
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
/* Prepare an insert statement */
$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");
/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
mysqli_stmt_execute($stmt);
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
mysqli_stmt_execute($stmt);
/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}`

The above examples will output:

    Stuttgart (DEU,Baden-Wuerttemberg)
    Bordeaux (FRA,Aquitaine)

Example #2 Execute a prepared statement with an array of values

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$mysqli->query('CREATE TEMPORARY TABLE myCity LIKE City');
/* Prepare an insert statement */
$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');
/* Execute the statement */
$stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);
/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
mysqli_query($link, 'CREATE TEMPORARY TABLE myCity LIKE City');
/* Prepare an insert statement */
$stmt = mysqli_prepare($link, 'INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');
/* Execute the statement */
mysqli_stmt_execute($stmt, ['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);
/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}`

The above examples will output:

    Stuttgart (DEU,Baden-Wuerttemberg)

### See Also

- mysqli_execute_query() - Prepares, binds parameters, and executes SQL statement
- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object

# mysqli_stmt::fetch

# mysqli_stmt_fetch

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

### Description

Object-oriented style

public mysqli_stmt::fetch(): ?bool

Procedural style

mysqli_stmt_fetch(mysqli_stmt `$statement`): ?bool

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

> Note:

> Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

> Note:

> Data is transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Return Values
Value | Description
--- | ---
`true` | Success. Data has been fetched
`false` | Error occurred
`null` | No more rows/data exists or data truncation occurred

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = mysqli_prepare($link, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $code);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Rockford (USA)
    Tallahassee (USA)
    Salinas (USA)
    Santa Clarita (USA)
    Springfield (USA)

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_errno() - Returns the error code for the most recent statement call
- mysqli_stmt_error() - Returns a string description for last statement error
- mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

# mysqli_stmt::$field_count

# mysqli_stmt_field_count

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of columns in the given statement

### Description

Object-oriented style

int $mysqli_stmt->field_count;

Procedural style

mysqli_stmt_field_count(mysqli_stmt `$statement`): int

Returns the number of columns in the prepared statement.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns an integer representing the number of columns.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$code = 'FR';
$stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Code=?");
$stmt->bind_param('s', $code);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
for ($i = 0; $i < $stmt->field_count; $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$code = 'FR';
$stmt = mysqli_prepare($mysqli, "SELECT Name FROM Country WHERE Code=?");
mysqli_stmt_bind_param($stmt, 's', $code);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_row($result);
for ($i = 0; $i < mysqli_stmt_field_count($stmt); $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}`

The above examples will output something similar to:

    Value of column number 0 is France

### See Also

- mysqli_stmt_num_rows() - Returns the number of rows fetched from the server

# mysqli_stmt::free_result

# mysqli_stmt_free_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

### Description

Object-oriented style

public mysqli_stmt::free_result(): void

Procedural style

mysqli_stmt_free_result(mysqli_stmt `$statement`): void

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

No value is returned.

### See Also

- mysqli_stmt_store_result() - Stores a result set in an internal buffer

# mysqli_stmt::get_result

# mysqli_stmt_get_result

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement as a mysqli_result object

### Description

Object-oriented style

public mysqli_stmt::get_result(): mysqli_result|false

Procedural style

mysqli_stmt_get_result(mysqli_stmt `$statement`): mysqli_result|false

Retrieves a result set from a prepared statement as a mysqli_result object. The data will be fetched from the MySQL server to PHP. This method should be called only for queries which produce a result set.

> Note:

> Available only with mysqlnd.

> Note:

> This function cannot be used together with mysqli_stmt_store_result(). Both of these functions retrieve the full result set from the MySQL server.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns `false` on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, mysqli_stmt_get_result() will return a mysqli_result object. For other successful queries, mysqli_stmt_get_result() will return `false`. The mysqli_stmt_errno() function can be used to distinguish between the two reasons for `false`; due to a bug, prior to PHP 7.4.13, mysqli_errno() had to be used for this purpose.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $continent);
$continentList = array('Europe', 'Africa', 'Asia', 'North America');
foreach ($continentList as $continent) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "s", $continent);
$continentList= array('Europe', 'Africa', 'Asia', 'North America');
foreach ($continentList as $continent) {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}`

The above examples will output something similar to:

    Albania 3401200 Europe
    Algeria 31471000 Africa
    Afghanistan 22720000 Asia
    Anguilla 8000 North America

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_stmt_store_result() - Stores a result set in an internal buffer

# mysqli_stmt::get_warnings

# mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

### Description

Object-oriented style

public mysqli_stmt::get_warnings(): mysqli_warning|false

Procedural style

mysqli_stmt_get_warnings(mysqli_stmt `$statement`): mysqli_warning|false
Warning

This function is currently not documented; only its argument list is available.

# mysqli_stmt::$insert_id

# mysqli_stmt_insert_id

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

### Description

Object-oriented style

int|string $mysqli_stmt->insert_id;

Procedural style

mysqli_stmt_insert_id(mysqli_stmt `$statement`): int|string
Warning

This function is currently not documented; only its argument list is available.

# mysqli_stmt::more_results

# mysqli_stmt_more_results

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::more_results -- mysqli_stmt_more_results — Check if there are more query results from a multiple query

### Description

Object-oriented style

public mysqli_stmt::more_results(): bool

Procedural style:

mysqli_stmt_more_results(mysqli_stmt `$statement`): bool

Checks if there are more query results from a multiple query.

> Note:

> Available only with mysqlnd.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns `true` if more results exist, otherwise `false`.

### See Also

- mysqli_stmt::next_result() - Reads the next result from a multiple query
- mysqli::multi_query() - Performs one or more queries on the database

# mysqli_stmt::next_result

# mysqli_stmt_next_result

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::next_result -- mysqli_stmt_next_result — Reads the next result from a multiple query

### Description

Object-oriented style

public mysqli_stmt::next_result(): bool

Procedural style:

mysqli_stmt_next_result(mysqli_stmt `$statement`): bool

Reads the next result from a multiple query.

> Note:

> Prior to PHP 8.1.0, available only with mysqlnd.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Changelog

Version | Description
--- | ---
8.1.0 | Now also available when linking against libmysqlclient.

### See Also

- mysqli_stmt::more_results() - Check if there are more query results from a multiple query
- mysqli::multi_query() - Performs one or more queries on the database

# mysqli_stmt::$num_rows

# mysqli_stmt::num_rows

# mysqli_stmt_num_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$num_rows -- mysqli_stmt::num_rows -- mysqli_stmt_num_rows — Returns the number of rows fetched from the server

### Description

Object-oriented style

int|string $mysqli_stmt->num_rows;
public mysqli_stmt::num_rows(): int|string

Procedural style

mysqli_stmt_num_rows(mysqli_stmt `$statement`): int|string

Returns the number of rows buffered in the statement. This function will only work after mysqli_stmt_store_result() is called to buffer the entire result set in the statement handle.

This function returns `0` unless all rows have been fetched from the server.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

An int representing the number of buffered rows. Returns `0` in unbuffered mode unless all rows have been fetched from the server.

> Note:

> If the number of rows is greater than `PHP_INT_MAX`, the number will be returned as a string.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));`

The above examples will output:

    Number of rows: 20.

### See Also

- mysqli_stmt_store_result() - Stores a result set in an internal buffer
- mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
- mysqli_prepare() - Prepares an SQL statement for execution

# mysqli_stmt::$param_count

# mysqli_stmt_param_count

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameters for the given statement

### Description

Object-oriented style

int $mysqli_stmt->param_count;

Procedural style

mysqli_stmt_param_count(mysqli_stmt `$statement`): int

Returns the number of parameter markers present in the prepared statement.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns an integer representing the number of parameters.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {
$marker = $stmt->param_count;
printf("Statement has %d markers.\n", $marker);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {
$marker = mysqli_stmt_param_count($stmt);
printf("Statement has %d markers.\n", $marker);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Statement has 2 markers.

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution

# mysqli_stmt::prepare

# mysqli_stmt_prepare

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepares an SQL statement for execution

### Description

Object-oriented style

public mysqli_stmt::prepare(string `$query`): bool

Procedural style

mysqli_stmt_prepare(mysqli_stmt `$statement`, string `$query`): bool

Prepares a statement for execution. The query must consist of a single SQL statement.

The statement template can contain zero or more question mark (`?`) parameter markers⁠—also called placeholders. The parameter markers must be bound to application variables using mysqli_stmt_bind_param() before executing the statement.

> Note:

> In the case where a statement is passed to mysqli_stmt_prepare() that is longer than `max_allowed_packet` of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (`mysqlnd`) or MySQL Client Library (`libmysqlclient`). The behavior is as follows:

> - `mysqlnd` on Linux returns an error code of 1153. The error message means got a packet bigger than `max_allowed_packet` bytes.

> - `mysqlnd` on Windows returns an error code 2006. This error message means server has gone away.

> - `libmysqlclient` on all platforms returns an error code 2006. This error message means server has gone away.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`query`

  The query, as a string. It must consist of a single SQL statement.

  The SQL statement may contain zero or more parameter markers represented by question mark (`?`) characters at the appropriate positions.

  > Note:

  > The markers are legal only in certain places in SQL statements. For example, they are permitted in the `VALUES()` list of an `INSERT` statement (to specify column values for a row), or in a comparison with a column in a `WHERE` clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 mysqli_stmt::prepare() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
$stmt->prepare("SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is in district %s\n", $city, $district);`

The above examples will output:

    Amersfoort is in district Utrecht

### See Also

- mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
- mysqli_stmt_execute() - Executes a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
- mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
- mysqli_stmt_close() - Closes a prepared statement

# mysqli_stmt::reset

# mysqli_stmt_reset

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

### Description

Object-oriented style

public mysqli_stmt::reset(): bool

Procedural style

mysqli_stmt_reset(mysqli_stmt `$statement`): bool

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data(), unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare().

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution

# mysqli_stmt::result_metadata

# mysqli_stmt_result_metadata

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

### Description

Object-oriented style

public mysqli_stmt::result_metadata(): mysqli_result|false

Procedural style

mysqli_stmt_result_metadata(mysqli_stmt `$statement`): mysqli_result|false

If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.

This function returns an empty mysqli_result object which can be used to access metadata information from the prepared statement without having to fetch the actual rows of data. There is no need to use this function when using mysqli_stmt_get_result() to retrieve the entire result set from a prepared statement as a result object.

> Note:

> This result set object can be passed as an argument only to the field-based functions that process result set metadata, such as:

> - mysqli_num_fields()

> - mysqli_fetch_field()

> - mysqli_fetch_field_direct()

> - mysqli_fetch_fields()

> - mysqli_field_count()

> - mysqli_field_seek()

> - mysqli_field_tell()

> - mysqli_free_result()

> Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by calling mysqli_stmt_get_result() on the statement handle or with mysqli_stmt_fetch().

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns a result object or `false` if an error occurred. If the statement does not produce a result set, `false` is returned as well.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();
/* get resultset for metadata */
$result = $stmt->result_metadata();
/* retrieve field information from metadata result set */
$field = $result->fetch_field();
printf("Fieldname: %s\n", $field->name);
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);
/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);
/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);
printf("Fieldname: %s\n", $field->name);
?>`

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_free_result() - Frees the memory associated with a result
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object

# mysqli_stmt::send_long_data

# mysqli_stmt_send_long_data

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

### Description

Object-oriented style

public mysqli_stmt::send_long_data(int `$param_num`, string `$data`): bool

Procedural style

mysqli_stmt_send_long_data(mysqli_stmt `$statement`, int `$param_num`, string `$data`): bool

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of `max_allowed_packet`. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

`param_num`

  Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

`data`

  A string containing data to be sent.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Object-oriented style

`<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>`

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

# mysqli_stmt::$sqlstate

# mysqli_stmt_sqlstate

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

### Description

Object-oriented style

string $mysqli_stmt->sqlstate;

Procedural style

mysqli_stmt_sqlstate(mysqli_stmt `$statement`): string

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. `'00000'` means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. `'00000'` means no error.

### Examples

Example #1 Object-oriented style

`<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->sqlstate);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Error: 42S02.

### Notes

> Note:

> Note that not all MySQL errors are yet mapped to SQLSTATE's. The value `HY000` (general error) is used for unmapped errors.

### See Also

- mysqli_stmt_errno() - Returns the error code for the most recent statement call
- mysqli_stmt_error() - Returns a string description for last statement error

# mysqli_stmt::store_result

# mysqli_stmt_store_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Stores a result set in an internal buffer

### Description

Object-oriented style

public mysqli_stmt::store_result(): bool

Procedural style

mysqli_stmt_store_result(mysqli_stmt `$statement`): bool

This function should be called for queries that successfully produce a result set (e.g. `SELECT, SHOW, DESCRIBE, EXPLAIN`) only if the complete result set needs to be buffered in PHP. Each subsequent mysqli_stmt_fetch() call will return buffered data.

> Note:

> It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance loss in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns `false`.

### Parameters

`statement`

  Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init().

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));`

The above examples will output:

    Number of rows: 20.

### See Also

- mysqli_prepare() - Prepares an SQL statement for execution
- mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
- mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

## Table of Contents

- mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
- mysqli_stmt::attr_get — Used to get the current value of a statement attribute
- mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
- mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
- mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
- mysqli_stmt::close — Closes a prepared statement
- mysqli_stmt::__construct — Constructs a new mysqli_stmt object
- mysqli_stmt::data_seek — Adjusts the result pointer to an arbitrary row in the buffered result
- mysqli_stmt::$errno — Returns the error code for the most recent statement call
- mysqli_stmt::$error — Returns a string description for last statement error
- mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
- mysqli_stmt::execute — Executes a prepared statement
- mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
- mysqli_stmt::$field_count — Returns the number of columns in the given statement
- mysqli_stmt::free_result — Frees stored result memory for the given statement handle
- mysqli_stmt::get_result — Gets a result set from a prepared statement as a mysqli_result object
- mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
- mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
- mysqli_stmt::more_results — Check if there are more query results from a multiple query
- mysqli_stmt::next_result — Reads the next result from a multiple query
- mysqli_stmt::$num_rows — Returns the number of rows fetched from the server
- mysqli_stmt::$param_count — Returns the number of parameters for the given statement
- mysqli_stmt::prepare — Prepares an SQL statement for execution
- mysqli_stmt::reset — Resets a prepared statement
- mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
- mysqli_stmt::send_long_data — Send data in blocks
- mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
- mysqli_stmt::store_result — Stores a result set in an internal buffer

# The mysqli_result class

(PHP 5, PHP 7, PHP 8)

## Introduction

Represents the result set obtained from a query against the database.

## Class synopsis

class mysqli_result implements IteratorAggregate {
/* Properties */
public readonly int $current_field;
public readonly int $field_count;
public readonly ?array $lengths;
public readonly int|string $num_rows;
public int $type;
/* Methods */
public __construct(mysqli `$mysql`, int `$result_mode` = `MYSQLI_STORE_RESULT`)
public data_seek(int `$offset`): bool
public fetch_all(int `$mode` = `MYSQLI_NUM`): array
public fetch_array(int `$mode` = `MYSQLI_BOTH`): array|null|false
public fetch_assoc(): array|null|false
public fetch_column(int `$column` = 0): null|int|float|string|false
public fetch_field(): object|false
public fetch_field_direct(int `$index`): object|false
public fetch_fields(): array
public fetch_object(string `$class` = "stdClass", array `$constructor_args` = []): object|null|false
public fetch_row(): array|null|false
public field_seek(int `$index`): true
public free(): void
public close(): void
public free_result(): void
public getIterator(): Iterator
}

## Properties

type

  Stores whether the result is buffered or unbuffered as an int (`MYSQLI_STORE_RESULT` or `MYSQLI_USE_RESULT`, respectively).

## Changelog

Version | Description
--- | ---
8.0.0 | mysqli_result implements IteratorAggregate now. Previously, Traversable was implemented instead.

# mysqli_result::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_result::__construct — Constructs a mysqli_result object

### Description

public mysqli_result::__construct(mysqli `$mysql`, int `$result_mode` = `MYSQLI_STORE_RESULT`)

This method constructs a new mysqli_result object.

It can be used to create the mysqli_result object after calling the mysqli_real_query() or mysqli_multi_query() function. Constructing the object manually is equivalent to calling the mysqli_store_result() or mysqli_use_result() function.

### Parameters

`mysql`

  Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

`result_mode`

  The result mode can be one of 2 constants indicating how the result will be returned from the MySQL server.

  `MYSQLI_STORE_RESULT` (default) - creates a mysqli_result object with buffered result set.

  `MYSQLI_USE_RESULT` - creates a mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error `Commands out of sync`. To avoid the error all records must be fetched from the server or the result set must be discarded by calling mysqli_free_result(). The connection must remain open for the rows to be fetched.

### Errors/Exceptions

If mysqli error reporting is enabled (`MYSQLI_REPORT_ERROR`) and the requested operation fails, a warning is generated. If, in addition, the mode is set to `MYSQLI_REPORT_STRICT`, a mysqli_sql_exception is thrown instead.

### Examples

Example #1 Creation of a mysqli_result object

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Select queries return a result set */
$mysqli->real_query("SELECT Name FROM City LIMIT 10");
$result = new mysqli_result($mysqli);
printf("Select returned %d rows.\n", $result->num_rows);`

The above examples will output something similar to:

    Select returned 10 rows.

### See Also

- mysqli_multi_query() - Performs one or more queries on the database
- mysqli_real_query() - Execute an SQL query
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli_result::$current_field

# mysqli_field_tell

(PHP 5, PHP 7, PHP 8)

mysqli_result::$current_field -- mysqli_field_tell — Get current field offset of a result pointer

### Description

Object-oriented style

int $mysqli_result->current_field;

Procedural style

mysqli_field_tell(mysqli_result `$result`): int

Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

Returns current offset of field cursor.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
/* get fieldpointer offset */
$currentfield = $result->current_field;
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {
/* get fieldpointer offset */
$currentfield = mysqli_field_tell($result);
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Column 1:
    Name:     Name
    Table:    Country
    max. Len: 11
    Flags:    1
    Type:     254

    Column 2:
    Name:     SurfaceArea
    Table:    Country
    max. Len: 10
    Flags:    32769
    Type:     4

### See Also

- mysqli_fetch_field() - Returns the next field in the result set
- mysqli_field_seek() - Set result pointer to a specified field offset

# mysqli_result::data_seek

# mysqli_data_seek

(PHP 5, PHP 7, PHP 8)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitrary row in the result

### Description

Object-oriented style

public mysqli_result::data_seek(int `$offset`): bool

Procedural style

mysqli_data_seek(mysqli_result `$result`, int `$offset`): bool

The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the `offset` in the result set.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`offset`

  The row offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysqli::data_seek() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$result = $mysqli->query($query);
/* Seek to row no. 401 */
$result->data_seek(400);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$result = mysqli_query($link, $query);
/* Seek to row no. 401 */
mysqli_data_seek($result, 400);
/* Fetch single row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);`

The above examples will output:

    City: Benin City  Countrycode: NGA

Example #2 Adjusting the result pointer when iterating

This function can be useful when iterating over the result set to impose a custom order or rewind the result set when iterating multiple times.

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 15,4";
$result = $mysqli->query($query);
/* Iterate the result set in reverse order */
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}
/* Reset pointer to the beginning of the result set */
$result->data_seek(0);
print "\n";
/* Iterate the same result set again */
while ($row = $result->fetch_row()) {
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}`

The above examples will output:

    City: Acmbaro  Countrycode: MEX
    City: Abuja  Countrycode: NGA
    City: Abu Dhabi  Countrycode: ARE
    City: Abottabad  Countrycode: PAK

    City: Abottabad  Countrycode: PAK
    City: Abu Dhabi  Countrycode: ARE
    City: Abuja  Countrycode: NGA
    City: Acmbaro  Countrycode: MEX

### Notes

> Note:

> This function can only be used with buffered results attained from the use of the mysqli_store_result(), mysqli_query() or mysqli_stmt_get_result() functions.

### See Also

- mysqli_store_result() - Transfers a result set from the last query
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_query() - Performs a query on the database
- mysqli_num_rows() - Gets the number of rows in the result set

# mysqli_result::fetch_all

# mysqli_fetch_all

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetch all result rows as an associative array, a numeric array, or both

### Description

Object-oriented style

public mysqli_result::fetch_all(int `$mode` = `MYSQLI_NUM`): array

Procedural style

mysqli_fetch_all(mysqli_result `$result`, int `$mode` = `MYSQLI_NUM`): array

Returns a two-dimensional array of all result rows as an associative array, a numeric array, or both.

> Note:

> Prior to PHP 8.1.0, available only with mysqlnd.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`mode`

  This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants `MYSQLI_ASSOC`, `MYSQLI_NUM`, or `MYSQLI_BOTH`.

### Return Values

Returns an array of associative or numeric arrays holding result rows.

### Changelog

Version | Description
--- | ---
8.1.0 | Now also available when linking against libmysqlclient.

### Examples

Example #1 mysqli_result::fetch_all() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}`

The above examples will output:

    Kabul (AFG)
    Qandahar (AFG)
    Herat (AFG)

### See Also

- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_query() - Performs a query on the database

# mysqli_result::fetch_array

# mysqli_fetch_array

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both

### Description

Object-oriented style

public mysqli_result::fetch_array(int `$mode` = `MYSQLI_BOTH`): array|null|false

Procedural style

mysqli_fetch_array(mysqli_result `$result`, int `$mode` = `MYSQLI_BOTH`): array|null|false

Fetches one row of data from the result set and returns it as an array. Each subsequent call to this function will return the next row within the result set, or `null` if there are no more rows.

In addition to storing the data in the numeric indices of the result array, this function can also store the data in associative indices by using the field names of the result set as keys.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, the numerically indexed version of the row must be used.

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`mode`

  This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants `MYSQLI_ASSOC`, `MYSQLI_NUM`, or `MYSQLI_BOTH`.

  By using the `MYSQLI_ASSOC` constant this function will behave identically to the mysqli_fetch_assoc(), while `MYSQLI_NUM` will behave identically to the mysqli_fetch_row() function. The final option `MYSQLI_BOTH` will create a single array with the attributes of both.

### Return Values

Returns an array representing the fetched row, `null` if there are no more rows in the result set, or `false` on failure.

### Examples

Example #1 mysqli_result::fetch_array() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($mysqli, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);`

The above examples will output something similar to:

    Kabul (AFG)
    Qandahar (AFG)
    Herat (AFG)

### See Also

- mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_query() - Performs a query on the database
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_result::fetch_assoc

# mysqli_fetch_assoc

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch the next row of a result set as an associative array

### Description

Object-oriented style

public mysqli_result::fetch_assoc(): array|null|false

Procedural style

mysqli_fetch_assoc(mysqli_result `$result`): array|null|false

Fetches one row of data from the result set and returns it as an associative array. Each subsequent call to this function will return the next row within the result set, or `null` if there are no more rows.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, `null` if there are no more rows in the result set, or `false` on failure.

### Examples

Example #1 mysqli_result::fetch_assoc() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($mysqli, $query);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}`

The above examples will output something similar to:

    Pueblo (USA)
    Arvada (USA)
    Cape Coral (USA)
    Green Bay (USA)
    Santa Clara (USA)

Example #2 Comparison of mysqli_result iterator and mysqli_result::fetch_assoc() usage

mysqli_result can be iterated using `foreach`. The result set will always be iterated from the first row, regardless of the current position.

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = 'SELECT Name, CountryCode FROM City ORDER BY ID DESC';
// Using iterators
$result = $mysqli->query($query);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
echo "\n==================\n";
// Not using iterators
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}`

The above example will output something similar to:

    Pueblo (USA)
    Arvada (USA)
    Cape Coral (USA)
    Green Bay (USA)
    Santa Clara (USA)

    ==================
    Pueblo (USA)
    Arvada (USA)
    Cape Coral (USA)
    Green Bay (USA)
    Santa Clara (USA)

### See Also

- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_query() - Performs a query on the database
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_result::fetch_column

# mysqli_fetch_column

(PHP 8 >= 8.1.0)

mysqli_result::fetch_column -- mysqli_fetch_column — Fetch a single column from the next row of a result set

### Description

Object-oriented style

public mysqli_result::fetch_column(int `$column` = 0): null|int|float|string|false

Procedural style

mysqli_fetch_column(mysqli_result `$result`, int `$column` = 0): null|int|float|string|false

Fetches one row of data from the result set and returns the 0-indexed column. Each subsequent call to this function will return the value from the next row within the result set, or `false` if there are no more rows.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`column`

  0-indexed number of the column you wish to retrieve from the row. If no value is supplied, the first column will be returned.

### Return Values

Returns a single column from the next row of a result set or `false` if there are no more rows.

Warning

There is no way to return another column from the same row if you use this function to retrieve data.

### Examples

Example #1 mysqli_result::fetch_column() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";
$result = $mysqli->query($query);
/* fetch a single value from the second column */
while ($Name = $result->fetch_column(1)) {
printf("%s\n", $Name);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";
$result = mysqli_query($mysqli, $query);
/* fetch a single value from the second column */
while ($Name = mysqli_fetch_column($result, 1)) {
printf("%s\n", $Name);
}`

The above examples will output something similar to:

    Rafah
    Nablus
    Jabaliya
    Hebron
    Khan Yunis

### See Also

- mysqli_fetch_all() - Fetch all result rows as an associative array, a numeric array, or both
- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_result::fetch_field

# mysqli_fetch_field

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

### Description

Object-oriented style

public mysqli_result::fetch_field(): object|false

Procedural style

mysqli_fetch_field(mysqli_result `$result`): object|false

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

Returns an object which contains field definition information or `false` if no field information is available.

Object properties
Property | Description
--- | ---
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Unused. Always an empty string
db | The name of the database
catalog | Unused. Always `"def"`
max_length | The maximum width of the field for the result set. As of PHP 8.1, this value is always `0`.
length | The width of the field in bytes. For string columns, the length value varies on the connection character set. For example, if the character set is `latin1`, a single-byte character set, the length value for a `SELECT 'abc'` query is 3. If the character set is `utf8mb4`, a multibyte character set in which characters take up to 4 bytes, the length value is 12.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals for numeric fields, and the fractional seconds precision for temporal fields.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Name:     Name
    Table:    Country
    max. Len: 11
    Flags:    1
    Type:     254

    Name:     SurfaceArea
    Table:    Country
    max. Len: 10
    Flags:    32769
    Type:     4

### See Also

- mysqli_num_fields() - Gets the number of fields in the result set
- mysqli_fetch_field_direct() - Fetch meta-data for a single field
- mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set
- mysqli_field_seek() - Set result pointer to a specified field offset

# mysqli_result::fetch_field_direct

# mysqli_fetch_field_direct

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

### Description

Object-oriented style

public mysqli_result::fetch_field_direct(int `$index`): object|false

Procedural style

mysqli_fetch_field_direct(mysqli_result `$result`, int `$index`): object|false

Returns an object which contains field definition information from the specified result set.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`index`

  The field number. This value must be in the range from `0` to `number of fields - 1`.

### Return Values

Returns an object which contains field definition information or `false` if no field information for specified `index` is available.

Object properties
Property | Description
--- | ---
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Unused. Always an empty string
db | The name of the database
catalog | Unused. Always `"def"`
max_length | The maximum width of the field for the result set. As of PHP 8.1, this value is always `0`.
length | The width of the field in bytes. For string columns, the length value varies on the connection character set. For example, if the character set is `latin1`, a single-byte character set, the length value for a `SELECT 'abc'` query is 3. If the character set is `utf8mb4`, a multibyte character set in which characters take up to 4 bytes, the length value is 12.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals for numeric fields, and the fractional seconds precision for temporal fields.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = mysqli_fetch_field_direct($result, 1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Name:     SurfaceArea
    Table:    Country
    max. Len: 10
    Flags:    32769
    Type:     4

### See Also

- mysqli_num_fields() - Gets the number of fields in the result set
- mysqli_fetch_field() - Returns the next field in the result set
- mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set

# mysqli_result::fetch_fields

# mysqli_fetch_fields

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

### Description

Object-oriented style

public mysqli_result::fetch_fields(): array

Procedural style

mysqli_fetch_fields(mysqli_result `$result`): array

This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

Returns an array of objects containing field definition information.

Object properties
Property | Description
--- | ---
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Unused. Always an empty string
db | The name of the database
catalog | Unused. Always `"def"`
max_length | The maximum width of the field for the result set. As of PHP 8.1, this value is always `0`.
length | The width of the field in bytes. For string columns, the length value varies on the connection character set. For example, if the character set is `latin1`, a single-byte character set, the length value for a `SELECT 'abc'` query is 3. If the character set is `utf8mb4`, a multibyte character set in which characters take up to 4 bytes, the length value is 12.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals for numeric fields, and the fractional seconds precision for temporal fields.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
foreach (array('latin1', 'utf8') as $charset) {
// Set character set, to show its impact on some values (e.g., length in bytes)
$mysqli->set_charset($charset);
$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";
echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
$result->free();
}
}
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach (array('latin1', 'utf8') as $charset) {
// Set character set, to show its impact on some values (e.g., length in bytes)
mysqli_set_charset($link, $charset);
$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";
echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all columns */
$finfo = mysqli_fetch_fields($result);
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
mysqli_free_result($result);
}
}
mysqli_close($link);
?>`

The above examples will output:

    ======================
    Character Set: latin1
    ======================
    Name:      actor_id
    Table:     actor
    Max. Len:  3
    Length:    5
    charsetnr: 63
    Flags:     49699
    Type:      2

    Name:      last_name
    Table:     actor
    Max. Len:  12
    Length:    45
    charsetnr: 8
    Flags:     20489
    Type:      253

    ======================
    Character Set: utf8
    ======================
    Name:      actor_id
    Table:     actor
    Max. Len:  3
    Length:    5
    charsetnr: 63
    Flags:     49699
    Type:      2

    Name:      last_name
    Table:     actor
    Max. Len:  12
    Length:    135
    charsetnr: 33
    Flags:     20489

### See Also

- mysqli_num_fields() - Gets the number of fields in the result set
- mysqli_fetch_field_direct() - Fetch meta-data for a single field
- mysqli_fetch_field() - Returns the next field in the result set

# mysqli_result::fetch_object

# mysqli_fetch_object

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_object -- mysqli_fetch_object — Fetch the next row of a result set as an object

### Description

Object-oriented style

public mysqli_result::fetch_object(string `$class` = "stdClass", array `$constructor_args` = []): object|null|false

Procedural style

mysqli_fetch_object(mysqli_result `$result`, string `$class` = "stdClass", array `$constructor_args` = []): object|null|false

Fetches one row of data from the result set and returns it as an object, where each property represents the name of the result set's column. Each subsequent call to this function will return the next row within the result set, or `null` if there are no more rows.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.

> Note: This function sets the properties of the object before calling the object constructor.

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`class`

  The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

`constructor_args`

  An optional array of parameters to pass to the constructor for `class` objects.

### Return Values

Returns an object representing the fetched row, where each property represents the name of the result set's column, `null` if there are no more rows in the result set, or `false` on failure.

### Errors/Exceptions

A ValueError is thrown when the `constructor_args` is non-empty with the class not having constructor.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a ValueError exception when the `constructor_args` is non-empty with the class not having constructor; previously an Exception was thrown.
8.0.0 | `constructor_args` now accepts `[]` for constructors with 0 parameters; previously an exception was thrown.

### Examples

Example #1 mysqli_result::fetch_object() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
while ($obj = $result->fetch_object()) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($link, $query);
while ($obj = mysqli_fetch_object($result)) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}`

The above examples will output something similar to:

    Pueblo (USA)
    Arvada (USA)
    Cape Coral (USA)
    Green Bay (USA)
    Santa Clara (USA)

### See Also

- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_query() - Performs a query on the database
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_result::fetch_row

# mysqli_fetch_row

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_row -- mysqli_fetch_row — Fetch the next row of a result set as an enumerated array

### Description

Object-oriented style

public mysqli_result::fetch_row(): array|null|false

Procedural style

mysqli_fetch_row(mysqli_result `$result`): array|null|false

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or `null` if there are no more rows.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

Returns an enumerated array representing the fetched row, `null` if there are no more rows in the result set, or `false` on failure.

### Examples

Example #1 mysqli_result::fetch_row() example

Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
/* fetch object array */
while ($row = $result->fetch_row()) {
printf("%s (%s)\n", $row[0], $row[1]);
}`

Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($mysqli, $query);
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s)\n", $row[0], $row[1]);
}`

The above examples will output something similar to:

    Pueblo (USA)
    Arvada (USA)
    Cape Coral (USA)
    Green Bay (USA)
    Santa Clara (USA)

### See Also

- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_query() - Performs a query on the database
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

# mysqli_result::$field_count

# mysqli_num_fields

(PHP 5, PHP 7, PHP 8)

mysqli_result::$field_count -- mysqli_num_fields — Gets the number of fields in the result set

### Description

Object-oriented style

int $mysqli_result->field_count;

Procedural style

mysqli_num_fields(mysqli_result `$result`): int

Returns the number of fields in the result set.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

An int representing the number of fields.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");
/* Get the number of fields in the result set */
$field_cnt = $result->field_count;
printf("Result set has %d fields.\n", $field_cnt);`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");
/* Get the number of fields in the result set */
$field_cnt = mysqli_num_fields($result);
printf("Result set has %d fields.\n", $field_cnt);`

The above examples will output:

    Result set has 4 fields.

### See Also

- mysqli_fetch_field() - Returns the next field in the result set

# mysqli_result::field_seek

# mysqli_field_seek

(PHP 5, PHP 7, PHP 8)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

### Description

Object-oriented style

public mysqli_result::field_seek(int `$index`): true

Procedural style

mysqli_field_seek(mysqli_result `$result`, int `$index`): true

Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.

> Note:

> To seek to the beginning of a row, pass an offset value of zero.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

`index`

  The field number. This value must be in the range from `0` to `number of fields - 1`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function now always returns `true`. Previously it returned `false` on failure.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for 2nd column */
$result->field_seek(1);
$finfo = $result->fetch_field();
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for 2nd column */
mysqli_field_seek($result, 1);
$finfo = mysqli_fetch_field($result);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Name:     SurfaceArea
    Table:    Country
    max. Len: 10
    Flags:    32769
    Type:     4

### See Also

- mysqli_fetch_field() - Returns the next field in the result set

# mysqli_result::free

# mysqli_result::close

# mysqli_result::free_result

# mysqli_free_result

(PHP 5, PHP 7, PHP 8)

mysqli_result::free -- mysqli_result::close -- mysqli_result::free_result -- mysqli_free_result — Frees the memory associated with a result

### Description

Object-oriented style

public mysqli_result::free(): void
public mysqli_result::close(): void
public mysqli_result::free_result(): void

Procedural style

mysqli_free_result(mysqli_result `$result`): void

Frees the memory associated with the result.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

No value is returned.

### See Also

- mysqli_query() - Performs a query on the database
- mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval

# mysqli_result::getIterator

(PHP 8)

mysqli_result::getIterator — Retrieve an external iterator

### Description

public mysqli_result::getIterator(): Iterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# mysqli_result::$lengths

# mysqli_fetch_lengths

(PHP 5, PHP 7, PHP 8)

mysqli_result::$lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

### Description

Object-oriented style

?array $mysqli_result->lengths;

Procedural style

mysqli_fetch_lengths(mysqli_result `$result`): array|false

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

An array of integers representing the size of each column (not including any terminating null characters). `false` if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns `false` if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

### Examples

Example #1 Object-oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * from Country ORDER BY Code LIMIT 1";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_row();
/* display column lengths */
foreach ($result->lengths as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>`

Example #2 Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * from Country ORDER BY Code LIMIT 1";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_row($result);
/* display column lengths */
foreach (mysqli_fetch_lengths($result) as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>`

The above examples will output:

    Field  1 has Length  3
    Field  2 has Length  5
    Field  3 has Length 13
    Field  4 has Length  9
    Field  5 has Length  6
    Field  6 has Length  1
    Field  7 has Length  6
    Field  8 has Length  4
    Field  9 has Length  6
    Field 10 has Length  6
    Field 11 has Length  5
    Field 12 has Length 44
    Field 13 has Length  7
    Field 14 has Length  3
    Field 15 has Length  2

# mysqli_result::$num_rows

# mysqli_num_rows

(PHP 5, PHP 7, PHP 8)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in the result set

### Description

Object-oriented style

int|string $mysqli_result->num_rows;

Procedural style

mysqli_num_rows(mysqli_result `$result`): int|string

Returns the number of rows in the result set.

The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. This function returns `0` for unbuffered result sets unless all rows have been fetched from the server.

### Parameters

`result`

  Procedural style only: A mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

### Return Values

An int representing the number of fetched rows. Returns `0` in unbuffered mode unless all rows have been fetched from the server.

> Note:

> If the number of rows is greater than `PHP_INT_MAX`, the number will be returned as a string.

### Examples

Example #1 Object-oriented style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name");
/* Get the number of rows in the result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);`

Example #2 Procedural style

`<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name");
/* Get the number of rows in the result set */
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);`

The above examples will output:

    Result set has 239 rows.

### Notes

> Note:

> In contrast to the mysqli_stmt_num_rows() function, this function doesn't have object-oriented method variant. In the object-oriented style, use the getter property.

### See Also

- mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
- mysqli_store_result() - Transfers a result set from the last query
- mysqli_use_result() - Initiate a result set retrieval
- mysqli_query() - Performs a query on the database
- mysqli_stmt_num_rows() - Returns the number of rows fetched from the server

## Table of Contents

- mysqli_result::__construct — Constructs a mysqli_result object
- mysqli_result::$current_field — Get current field offset of a result pointer
- mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
- mysqli_result::fetch_all — Fetch all result rows as an associative array, a numeric array, or both
- mysqli_result::fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_result::fetch_assoc — Fetch the next row of a result set as an associative array
- mysqli_result::fetch_column — Fetch a single column from the next row of a result set
- mysqli_result::fetch_field — Returns the next field in the result set
- mysqli_result::fetch_field_direct — Fetch meta-data for a single field
- mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
- mysqli_result::fetch_object — Fetch the next row of a result set as an object
- mysqli_result::fetch_row — Fetch the next row of a result set as an enumerated array
- mysqli_result::$field_count — Gets the number of fields in the result set
- mysqli_result::field_seek — Set result pointer to a specified field offset
- mysqli_result::free — Frees the memory associated with a result
- mysqli_result::getIterator — Retrieve an external iterator
- mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
- mysqli_result::$num_rows — Gets the number of rows in the result set

# The mysqli_driver class

(PHP 5, PHP 7, PHP 8)

## Introduction

The mysqli_driver class is an instance of the monostate pattern, i.e. there is only one driver which can be accessed though an arbitrary amount of mysqli_driver instances.

## Class synopsis

final class mysqli_driver {
/* Properties */
public readonly string $client_info;
public readonly int $client_version;
public readonly int $driver_version;
public int $report_mode;
}

## Properties

client_info

  The Client API header version

client_version

  The Client version

driver_version

  The MySQLi Driver version

  Warning

  This property has been deprecated as of PHP 8.1.0. Relying on this property is highly discouraged.

embedded

  Whether MySQLi Embedded support is enabled

  Warning

  This property has been removed as of PHP 8.0.0.

reconnect

  Allow or prevent reconnect (see the mysqli.reconnect INI directive)

  Warning

  This property has been removed along with the mysqli.reconnect INI directive as of PHP 8.2.0.

report_mode

  Set to `MYSQLI_REPORT_OFF`, `MYSQLI_REPORT_ALL` or any combination of `MYSQLI_REPORT_STRICT` (throw Exceptions for errors), `MYSQLI_REPORT_ERROR` (report errors) and `MYSQLI_REPORT_INDEX` (errors regarding indexes). See also mysqli_report().

## Changelog

Version | Description
--- | ---
8.2.0 | mysqli_driver::$reconnect was removed.
8.1.0 | mysqli_driver::$driver_version has been deprecated.
8.0.0 | mysqli_driver::$embedded was removed.
7.4.0 | mysqli_driver::embedded_server_start() and mysqli_driver:embedded_server_end() were removed.

# mysqli_driver::embedded_server_end

# mysqli_embedded_server_end

(PHP 5 >= 5.1.0, PHP 7 < 7.4.0)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Warning

This function was REMOVED in PHP 7.4.0.

### Description

Object-oriented style

public mysqli_driver::embedded_server_end(): void

Procedural style

mysqli_embedded_server_end(): void
Warning

This function is currently not documented; only its argument list is available.

# mysqli_driver::embedded_server_start

# mysqli_embedded_server_start

(PHP 5 >= 5.1.0, PHP 7 < 7.4.0)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Warning

This function was REMOVED in PHP 7.4.0.

### Description

Object-oriented style

public mysqli_driver::embedded_server_start(int `$start`, array `$arguments`, array `$groups`): bool

Procedural style

mysqli_embedded_server_start(int `$start`, array `$arguments`, array `$groups`): bool
Warning

This function is currently not documented; only its argument list is available.

# mysqli_driver::$report_mode

# mysqli_report

(PHP 5, PHP 7, PHP 8)

mysqli_driver::$report_mode -- mysqli_report — Sets mysqli error reporting mode

### Description

Object-oriented style

int $mysqli_driver->report_mode;

Procedural style

mysqli_report(int `$flags`): true

Depending on the flags, it sets mysqli error reporting mode to exception, warning or none. When set to `MYSQLI_REPORT_ALL` or `MYSQLI_REPORT_INDEX` it will also inform about queries that don't use an index (or use a bad index).

As of PHP 8.1.0, the default setting is `MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT`. Previously, it was `MYSQLI_REPORT_OFF`.

### Parameters

`flags`

  Supported flags
  Name | Description
  --- | ---
  `MYSQLI_REPORT_OFF` | Turns reporting off
  `MYSQLI_REPORT_ERROR` | Report errors from mysqli function calls
  `MYSQLI_REPORT_STRICT` | Throw mysqli_sql_exception for errors instead of warnings
  `MYSQLI_REPORT_INDEX` | Report if no index or bad index was used in a query
  `MYSQLI_REPORT_ALL` | Set all options (report all)

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The default value is now `MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT`. Previously, it was `MYSQLI_REPORT_OFF`.

### Examples

Example #1 Object-oriented style

`<?php
/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}`

Example #2 Procedural style

`<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = mysqli_query($link, "SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}`

Example #3 Error reporting except bad index errors

`<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this WILL NOT report any errors even if index is not available */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}`

### See Also

- mysqli_sql_exception
- set_exception_handler() - Sets a user-defined exception handler function
- error_reporting() - Sets which PHP errors are reported

## Table of Contents

- mysqli_driver::embedded_server_end — Stop embedded server
- mysqli_driver::embedded_server_start — Initialize and start embedded server
- mysqli_driver::$report_mode — Sets mysqli error reporting mode

# The mysqli_warning class

(PHP 5, PHP 7, PHP 8)

## Introduction

Represents a MySQL warning.

## Class synopsis

final class mysqli_warning {
/* Properties */
public string $message;
public string $sqlstate;
public int $errno;
/* Methods */
private __construct()
public next(): bool
}

## Properties

message

  Message string

sqlstate

  SQL state

errno

  Error number

# mysqli_warning::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_warning::__construct — Private constructor to disallow direct instantiation

### Description

private mysqli_warning::__construct()

### Parameters

This function has no parameters.

# mysqli_warning::next

(PHP 5, PHP 7, PHP 8)

mysqli_warning::next — Fetch next warning

### Description

public mysqli_warning::next(): bool

Change warning information to the next warning if possible.

Once the warning has been set to the next warning, new values of properties `message`, `sqlstate` and `errno` of mysqli_warning are available.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if next warning was fetched successfully. If there are no more warnings, it will return `false`

## Table of Contents

- mysqli_warning::__construct — Private constructor to disallow direct instantiation
- mysqli_warning::next — Fetch next warning

# The mysqli_sql_exception class

(PHP 5, PHP 7, PHP 8)

## Introduction

The mysqli exception handling class.

## Class synopsis

final class mysqli_sql_exception extends RuntimeException {
/* Properties */
protected string $sqlstate = "00000";
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
public getSqlState(): string
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

## Properties

sqlstate

  The sql state with the error.

# mysqli_sql_exception::getSqlState

(PHP 8 >= 8.1.2)

mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code

### Description

public mysqli_sql_exception::getSqlState(): string

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

> Note:

> Note that not all MySQL errors are yet mapped to SQLSTATE's. The value `HY000` (general error) is used for unmapped errors.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.

## Table of Contents

- mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code

# Aliases and deprecated Mysqli Functions

# mysqli_connect

(PHP 5, PHP 7, PHP 8)

mysqli_connect — Alias of mysqli::__construct()

### Description

This function is an alias of: mysqli::__construct()

> Note:

> If mysqli exception mode is not enabled and a connection fails, then mysqli_connect() returns `false` instead of an object. The mysqli_connect_error() function can be used to fetch the connection error.

# mysqli::escape_string

# mysqli_escape_string

(PHP 5, PHP 7, PHP 8)

mysqli::escape_string -- mysqli_escape_string — Alias of mysqli_real_escape_string()

### Description

This function is an alias of: mysqli_real_escape_string().

# mysqli_execute

(PHP 5, PHP 7, PHP 8)

mysqli_execute — Alias of mysqli_stmt_execute()

### Description

This function is an alias of: mysqli_stmt_execute().

### Notes

> Note:

> mysqli_execute() is deprecated and will be removed.

### See Also

- mysqli_stmt_execute() - Executes a prepared statement

# mysqli_get_client_stats

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_get_client_stats — Returns client per-process statistics

### Description

mysqli_get_client_stats(): array

Returns client per-process statistics.

> Note:

> Available only with mysqlnd.

### Parameters

This function has no parameters.

### Return Values

Returns an array with client stats.

### Examples

Example #1 A mysqli_get_client_stats() example

`<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>`

The above example will output something similar to:

    Array
    (
        [bytes_sent] => 43
        [bytes_received] => 80
        [packets_sent] => 1
        [packets_received] => 2
        [protocol_overhead_in] => 8
        [protocol_overhead_out] => 4
        [bytes_received_ok_packet] => 11
        [bytes_received_eof_packet] => 0
        [bytes_received_rset_header_packet] => 0
        [bytes_received_rset_field_meta_packet] => 0
        [bytes_received_rset_row_packet] => 0
        [bytes_received_prepare_response_packet] => 0
        [bytes_received_change_user_packet] => 0
        [packets_sent_command] => 0
        [packets_received_ok] => 1
        [packets_received_eof] => 0
        [packets_received_rset_header] => 0
        [packets_received_rset_field_meta] => 0
        [packets_received_rset_row] => 0
        [packets_received_prepare_response] => 0
        [packets_received_change_user] => 0
        [result_set_queries] => 0
        [non_result_set_queries] => 0
        [no_index_used] => 0
        [bad_index_used] => 0
        [slow_queries] => 0
        [buffered_sets] => 0
        [unbuffered_sets] => 0
        [ps_buffered_sets] => 0
        [ps_unbuffered_sets] => 0
        [flushed_normal_sets] => 0
        [flushed_ps_sets] => 0
        [ps_prepared_never_executed] => 0
        [ps_prepared_once_executed] => 0
        [rows_fetched_from_server_normal] => 0
        [rows_fetched_from_server_ps] => 0
        [rows_buffered_from_client_normal] => 0
        [rows_buffered_from_client_ps] => 0
        [rows_fetched_from_client_normal_buffered] => 0
        [rows_fetched_from_client_normal_unbuffered] => 0
        [rows_fetched_from_client_ps_buffered] => 0
        [rows_fetched_from_client_ps_unbuffered] => 0
        [rows_fetched_from_client_ps_cursor] => 0
        [rows_skipped_normal] => 0
        [rows_skipped_ps] => 0
        [copy_on_write_saved] => 0
        [copy_on_write_performed] => 0
        [command_buffer_too_small] => 0
        [connect_success] => 1
        [connect_failure] => 0
        [connection_reused] => 0
        [reconnect] => 0
        [pconnect_success] => 0
        [active_connections] => 1
        [active_persistent_connections] => 0
        [explicit_close] => 0
        [implicit_close] => 0
        [disconnect_close] => 0
        [in_middle_of_command_close] => 0
        [explicit_free_result] => 0
        [implicit_free_result] => 0
        [explicit_stmt_close] => 0
        [implicit_stmt_close] => 0
        [mem_emalloc_count] => 0
        [mem_emalloc_ammount] => 0
        [mem_ecalloc_count] => 0
        [mem_ecalloc_ammount] => 0
        [mem_erealloc_count] => 0
        [mem_erealloc_ammount] => 0
        [mem_efree_count] => 0
        [mem_malloc_count] => 0
        [mem_malloc_ammount] => 0
        [mem_calloc_count] => 0
        [mem_calloc_ammount] => 0
        [mem_realloc_count] => 0
        [mem_realloc_ammount] => 0
        [mem_free_count] => 0
        [proto_text_fetched_null] => 0
        [proto_text_fetched_bit] => 0
        [proto_text_fetched_tinyint] => 0
        [proto_text_fetched_short] => 0
        [proto_text_fetched_int24] => 0
        [proto_text_fetched_int] => 0
        [proto_text_fetched_bigint] => 0
        [proto_text_fetched_decimal] => 0
        [proto_text_fetched_float] => 0
        [proto_text_fetched_double] => 0
        [proto_text_fetched_date] => 0
        [proto_text_fetched_year] => 0
        [proto_text_fetched_time] => 0
        [proto_text_fetched_datetime] => 0
        [proto_text_fetched_timestamp] => 0
        [proto_text_fetched_string] => 0
        [proto_text_fetched_blob] => 0
        [proto_text_fetched_enum] => 0
        [proto_text_fetched_set] => 0
        [proto_text_fetched_geometry] => 0
        [proto_text_fetched_other] => 0
        [proto_binary_fetched_null] => 0
        [proto_binary_fetched_bit] => 0
        [proto_binary_fetched_tinyint] => 0
        [proto_binary_fetched_short] => 0
        [proto_binary_fetched_int24] => 0
        [proto_binary_fetched_int] => 0
        [proto_binary_fetched_bigint] => 0
        [proto_binary_fetched_decimal] => 0
        [proto_binary_fetched_float] => 0
        [proto_binary_fetched_double] => 0
        [proto_binary_fetched_date] => 0
        [proto_binary_fetched_year] => 0
        [proto_binary_fetched_time] => 0
        [proto_binary_fetched_datetime] => 0
        [proto_binary_fetched_timestamp] => 0
        [proto_binary_fetched_string] => 0
        [proto_binary_fetched_blob] => 0
        [proto_binary_fetched_enum] => 0
        [proto_binary_fetched_set] => 0
        [proto_binary_fetched_geometry] => 0
        [proto_binary_fetched_other] => 0
    )

### See Also

- Stats description

# mysqli_get_links_stats

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

mysqli_get_links_stats — Return information about open and cached links

### Description

mysqli_get_links_stats(): array

mysqli_get_links_stats() returns information about open and cached MySQL links.

### Parameters

This function has no parameters.

### Return Values

mysqli_get_links_stats() returns an associative array with three elements, keyed as follows:

`total`

  An int indicating the total number of open links in any state.

`active_plinks`

  An int representing the number of active persistent connections.

`cached_plinks`

  An int representing the number of inactive persistent connections.

# mysqli_report

(PHP 5, PHP 7, PHP 8)

mysqli_report — Alias of mysqli_driver->report_mode

### Description

This function is an alias of: mysqli_driver->report_mode

# mysqli::set_opt

# mysqli_set_opt

(PHP 5, PHP 7, PHP 8)

mysqli::set_opt -- mysqli_set_opt — Alias of mysqli_options()

### Description

This function is an alias of: mysqli_options().

## Table of Contents

- mysqli_connect — Alias of mysqli::__construct
- mysqli::escape_string — Alias of mysqli_real_escape_string
- mysqli_execute — Alias of mysqli_stmt_execute
- mysqli_get_client_stats — Returns client per-process statistics
- mysqli_get_links_stats — Return information about open and cached links
- mysqli_report — Alias of mysqli_driver->report_mode
- mysqli::set_opt — Alias of mysqli_options

# Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
--- | --- | ---
8.4.0 | mysqli::kill | Both mysqli::kill and mysqli_kill are now deprecated. Use the KILL SQL command instead.
| mysqli::ping | Both mysqli::ping and mysqli_ping are now deprecated. The reconnect feature has not been available as of PHP 8.2.0, making this function obsolete.
| mysqli::refresh | Both mysqli::refresh and mysqli_refresh are now deprecated. Use FLUSH SQL commands instead.
| mysqli::store_result | Passing the mode parameter is now deprecated. The parameter has had no effect as of PHP 8.1.0.
8.3.0 | mysqli_result::fetch_object | Now throws a ValueError exception when the constructor_args is non-empty with the class not having constructor; previously an Exception was thrown.
| mysqli::poll | Now throws a ValueError exception when neither the read nor error arguments are passed.
8.1.0 | mysqli_driver::$report_mode | The default value is now MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Previously, it was MYSQLI_REPORT_OFF.
| mysqli_result::fetch_all | Now also available when linking against libmysqlclient.
| mysqli_stmt::execute | The optional params parameter has been added.
| mysqli_stmt::next_result | Now also available when linking against libmysqlclient.
| mysqli::__construct | mysqli::connect now returns true instead of null on success.
| mysqli::$client_info | Calling mysqli_get_client_info with the mysql argument has been deprecated. This function never required a parameter, but incorrectly allowed it as an optional parameter.
| mysqli::$client_info | The object-oriented style mysqli::get_client_info has been deprecated.
| mysqli::init | The object-oriented style mysqli::init method has been deprecated. Replace calls to parent::init with parent::__construct.
8.0.0 | mysqli_result::fetch_object | constructor_args now accepts [] for constructors with 0 parameters; previously an exception was thrown.
| mysqli_result::field_seek | This function now always returns true. Previously it returned false on failure.
| mysqli_stmt::close | This function now always returns true. Previously it returned false on failure.
| mysqli_stmt::__construct | query is now nullable.
| mysqli::begin_transaction | name is now nullable.
| mysqli::close | This function now always returns true. Previously it returned false on failure.
| mysqli::commit | name is now nullable.
| mysqli::debug | This function now always returns true. Previously it returned false on failure.
| mysqli::rollback | name is now nullable.
7.4.0 | mysqli::__construct | All parameters are now nullable.
| mysqli::real_connect | All parameters are now nullable.

- Overview
- Quick start guide
  - Dual procedural and object-oriented interface
  - Connections
  - Executing statements
  - Prepared Statements
  - Stored Procedures
  - Multiple Statements
  - API support for transactions
  - Metadata
- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- The mysqli Extension and Persistent Connections
- Predefined Constants
- Notes
- The MySQLi Extension Function Summary
- mysqli — The mysqli class
  - mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
  - mysqli::autocommit — Turns on or off auto-committing database modifications
  - mysqli::begin_transaction — Starts a transaction
  - mysqli::change_user — Changes the user of the database connection
  - mysqli::character_set_name — Returns the current character set of the database connection
  - mysqli::close — Closes a previously opened database connection
  - mysqli::commit — Commits the current transaction
  - mysqli::$connect_errno — Returns the error code from last connect call
  - mysqli::$connect_error — Returns a description of the last connection error
  - mysqli::__construct — Open a new connection to the MySQL server
  - mysqli::debug — Performs debugging operations
  - mysqli::dump_debug_info — Dump debugging information into the log
  - mysqli::$errno — Returns the error code for the most recent function call
  - mysqli::$error — Returns a string description of the last error
  - mysqli::$error_list — Returns a list of errors from the last command executed
  - mysqli::execute_query — Prepares, binds parameters, and executes SQL statement
  - mysqli::$field_count — Returns the number of columns for the most recent query
  - mysqli::get_charset — Returns a character set object
  - mysqli::$client_info — Get MySQL client info
  - mysqli::$client_version — Returns the MySQL client version as an integer
  - mysqli::get_connection_stats — Returns statistics about the client connection
  - mysqli::$host_info — Returns a string representing the type of connection used
  - mysqli::$protocol_version — Returns the version of the MySQL protocol used
  - mysqli::$server_info — Returns the version of the MySQL server
  - mysqli::$server_version — Returns the version of the MySQL server as an integer
  - mysqli::get_warnings — Get result of SHOW WARNINGS
  - mysqli::$info — Retrieves information about the most recently executed query
  - mysqli::init — Initializes MySQLi and returns an object for use with mysqli_real_connect()
  - mysqli::$insert_id — Returns the value generated for an AUTO_INCREMENT column by the last query
  - mysqli::kill — Asks the server to kill a MySQL thread
  - mysqli::more_results — Check if there are any more query results from a multi query
  - mysqli::multi_query — Performs one or more queries on the database
  - mysqli::next_result — Prepare next result from multi_query
  - mysqli::options — Set options
  - mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  - mysqli::poll — Poll connections
  - mysqli::prepare — Prepares an SQL statement for execution
  - mysqli::query — Performs a query on the database
  - mysqli::real_connect — Opens a connection to the MySQL server
  - mysqli::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  - mysqli::real_query — Execute an SQL query
  - mysqli::reap_async_query — Get result from async query
  - mysqli::refresh — Refreshes
  - mysqli::release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction
  - mysqli::rollback — Rolls back current transaction
  - mysqli::savepoint — Set a named transaction savepoint
  - mysqli::select_db — Selects the default database for database queries
  - mysqli::set_charset — Sets the client character set
  - mysqli::$sqlstate — Returns the SQLSTATE error from previous MySQL operation
  - mysqli::ssl_set — Used for establishing secure connections using SSL
  - mysqli::stat — Gets the current system status
  - mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
  - mysqli::store_result — Transfers a result set from the last query
  - mysqli::$thread_id — Returns the thread ID for the current connection
  - mysqli::thread_safe — Returns whether thread safety is given or not
  - mysqli::use_result — Initiate a result set retrieval
  - mysqli::$warning_count — Returns the number of warnings generated by the most recently executed query
- mysqli_stmt — The mysqli_stmt class
  - mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
  - mysqli_stmt::attr_get — Used to get the current value of a statement attribute
  - mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
  - mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
  - mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
  - mysqli_stmt::close — Closes a prepared statement
  - mysqli_stmt::__construct — Constructs a new mysqli_stmt object
  - mysqli_stmt::data_seek — Adjusts the result pointer to an arbitrary row in the buffered result
  - mysqli_stmt::$errno — Returns the error code for the most recent statement call
  - mysqli_stmt::$error — Returns a string description for last statement error
  - mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
  - mysqli_stmt::execute — Executes a prepared statement
  - mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
  - mysqli_stmt::$field_count — Returns the number of columns in the given statement
  - mysqli_stmt::free_result — Frees stored result memory for the given statement handle
  - mysqli_stmt::get_result — Gets a result set from a prepared statement as a mysqli_result object
  - mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
  - mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
  - mysqli_stmt::more_results — Check if there are more query results from a multiple query
  - mysqli_stmt::next_result — Reads the next result from a multiple query
  - mysqli_stmt::$num_rows — Returns the number of rows fetched from the server
  - mysqli_stmt::$param_count — Returns the number of parameters for the given statement
  - mysqli_stmt::prepare — Prepares an SQL statement for execution
  - mysqli_stmt::reset — Resets a prepared statement
  - mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
  - mysqli_stmt::send_long_data — Send data in blocks
  - mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
  - mysqli_stmt::store_result — Stores a result set in an internal buffer
- mysqli_result — The mysqli_result class
  - mysqli_result::__construct — Constructs a mysqli_result object
  - mysqli_result::$current_field — Get current field offset of a result pointer
  - mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
  - mysqli_result::fetch_all — Fetch all result rows as an associative array, a numeric array, or both
  - mysqli_result::fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both
  - mysqli_result::fetch_assoc — Fetch the next row of a result set as an associative array
  - mysqli_result::fetch_column — Fetch a single column from the next row of a result set
  - mysqli_result::fetch_field — Returns the next field in the result set
  - mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  - mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  - mysqli_result::fetch_object — Fetch the next row of a result set as an object
  - mysqli_result::fetch_row — Fetch the next row of a result set as an enumerated array
  - mysqli_result::$field_count — Gets the number of fields in the result set
  - mysqli_result::field_seek — Set result pointer to a specified field offset
  - mysqli_result::free — Frees the memory associated with a result
  - mysqli_result::getIterator — Retrieve an external iterator
  - mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
  - mysqli_result::$num_rows — Gets the number of rows in the result set
- mysqli_driver — The mysqli_driver class
  - mysqli_driver::embedded_server_end — Stop embedded server
  - mysqli_driver::embedded_server_start — Initialize and start embedded server
  - mysqli_driver::$report_mode — Sets mysqli error reporting mode
- mysqli_warning — The mysqli_warning class
  - mysqli_warning::__construct — Private constructor to disallow direct instantiation
  - mysqli_warning::next — Fetch next warning
- mysqli_sql_exception — The mysqli_sql_exception class
  - mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code
- Aliases and deprecated Mysqli Functions
  - mysqli_connect — Alias of mysqli::__construct
  - mysqli::escape_string — Alias of mysqli_real_escape_string
  - mysqli_execute — Alias of mysqli_stmt_execute
  - mysqli_get_client_stats — Returns client per-process statistics
  - mysqli_get_links_stats — Return information about open and cached links
  - mysqli_report — Alias of mysqli_driver->report_mode
  - mysqli::set_opt — Alias of mysqli_options
- Changelog

# Mysql_xdevapi

# Introduction

This extension provides access to the MySQL Document Store via the X DevAPI. The X DevAPI is a common API provided by multiple MySQL Connectors providing easy access to relational tables as well as collections of documents, which are represented in JSON, from a API with CRUD-style operations.

The X DevAPI uses the X Protocol, the new generation client-server protocol of the MySQL 8.0 server.

For general information about the MySQL Document Store, please refer to the » MySQL Document Store chapter in the MySQL manual.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Building / Compiling From Source

## Requirements

This extension requires a MySQL 8+ server with the X plugin enabled (default).

Prerequisite libraries for compiling this extension are: Boost (1.53.0 or higher), OpenSSL, and Protobuf.

## Installation

This » PECL extension is not bundled with PHP.

An example installation procedure on Ubuntu 18.04 with PHP 7.2:

    // Dependencies
    $ apt install build-essential libprotobuf-dev libboost-dev openssl protobuf-compiler liblz4-tool zstd

    // PHP with the desired extensions; php7.2-dev is required to compile
    $ apt install php7.2-cli php7.2-dev php7.2-mysql php7.2-pdo php7.2-xml

    // Compile the extension
    $ pecl install mysql_xdevapi

The `pecl install` command does not enable PHP extensions (by default) and enabling PHP extensions can be done in several ways. Another PHP 7.2 on Ubuntu 18.04 example:

    // Create its own ini file
    $ echo "extension=mysql_xdevapi.so" > /etc/php/7.2/mods-available/mysql_xdevapi.ini

    // Use the 'phpenmod' command (note: it's Debian/Ubuntu specific)
    $ phpenmod -v 7.2 -s ALL mysql_xdevapi

    // A 'phpenmod' alternative is to manually symlink it
    // $ ln -s /etc/php/7.2/mods-available/mysql_xdevapi.ini /etc/php/7.2/cli/conf.d/20-mysql_xdevapi.ini

    // Let's see which MySQL extensions are enabled now
    $ php -m |grep mysql

    mysql_xdevapi
    mysqli
    mysqlnd
    pdo_mysql

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: » https://pecl.php.net/package/mysql_xdevapi.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysql_xdevapi Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
xmysqlnd.collect_memory_statistics | 0 | `INI_SYSTEM` |
xmysqlnd.collect_statistics | 1 | `INI_ALL` |
xmysqlnd.debug |  | `INI_SYSTEM` |
xmysqlnd.mempool_default_size | 16000 | `INI_ALL` |
xmysqlnd.net_read_timeout | 31536000 | `INI_SYSTEM` |
xmysqlnd.trace_alloc |  | `INI_SYSTEM` |

Here's a short explanation of the configuration directives.

`xmysqlnd.collect_memory_statistics` int

`xmysqlnd.collect_statistics` int

`xmysqlnd.debug` string

`xmysqlnd.mempool_default_size` int

`xmysqlnd.net_read_timeout` int

`xmysqlnd.trace_alloc` string

## Building / Compiling From Source

Considerations for compiling this extension from source.

- The extension name is 'mysql_xdevapi', so use `--enable-mysql-xdevapi`.

- Boost: required, optionally use the --with-boost=DIR configure option or set the MYSQL_XDEVAPI_BOOST_ROOT environment variable. Only the boost header files are required; not the binaries.

- Google Protocol Buffers (protobuf): required, optionally use the --with-protobuf=DIR configure option or set the MYSQL_XDEVAPI_PROTOBUF_ROOT environment variable.

  Optionally use `make protobufs` to generate protobuf files (*.pb.cc/.h), and `make clean-protobufs` to delete generate protobuf files.

  Windows specific protobuf note: depending on your environment, the static library with a multi-threaded DLL runtime may be needed. To prepare, use the following options: -Dprotobuf_MSVC_STATIC_RUNTIME=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF

- Google Protocol Buffers / protocol compiler (protoc): required, ensure that proper 'protoc' is available in the PATH while building. It is especially important as Windows PHP SDK batch scripts may overwrite the environment.

- Bison: required, and available from the PATH.

  Windows specific bison note: we strongly recommended that bison delivered with the chosen PHP SDKis used else an error similar to "zend_globals_macros.h(39): error C2375: 'zendparse': redefinition; different linkage Zend/zend_language_parser.h(214): note: see declaration of 'zendparse'" may be the result. Also, Windows PHP SDK batch scripts may overwrite the environment.

- Windows Specific Notes: To prepare the environment, see the official Windows build documentation for » the current SDK.

  We recommend using the backslash '\\' instead of a slash '/' for all paths.

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

`MYSQLX_CLIENT_SSL` (int)
`MYSQLX_TYPE_DECIMAL` (int)
`MYSQLX_TYPE_TINY` (int)
`MYSQLX_TYPE_SHORT` (int)
`MYSQLX_TYPE_SMALLINT` (int)
`MYSQLX_TYPE_MEDIUMINT` (int)
`MYSQLX_TYPE_INT` (int)
`MYSQLX_TYPE_BIGINT` (int)
`MYSQLX_TYPE_LONG` (int)
`MYSQLX_TYPE_FLOAT` (int)
`MYSQLX_TYPE_DOUBLE` (int)
`MYSQLX_TYPE_NULL` (int)
`MYSQLX_TYPE_TIMESTAMP` (int)
`MYSQLX_TYPE_LONGLONG` (int)
`MYSQLX_TYPE_INT24` (int)
`MYSQLX_TYPE_DATE` (int)
`MYSQLX_TYPE_TIME` (int)
`MYSQLX_TYPE_DATETIME` (int)
`MYSQLX_TYPE_YEAR` (int)
`MYSQLX_TYPE_NEWDATE` (int)
`MYSQLX_TYPE_ENUM` (int)
`MYSQLX_TYPE_SET` (int)
`MYSQLX_TYPE_TINY_BLOB` (int)
`MYSQLX_TYPE_MEDIUM_BLOB` (int)
`MYSQLX_TYPE_LONG_BLOB` (int)
`MYSQLX_TYPE_BLOB` (int)
`MYSQLX_TYPE_VAR_STRING` (int)
`MYSQLX_TYPE_STRING` (int)
`MYSQLX_TYPE_CHAR` (int)
`MYSQLX_TYPE_BYTES` (int)
`MYSQLX_TYPE_INTERVAL` (int)
`MYSQLX_TYPE_GEOMETRY` (int)
`MYSQLX_TYPE_JSON` (int)
`MYSQLX_TYPE_NEWDECIMAL` (int)
`MYSQLX_TYPE_BIT` (int)
`MYSQLX_LOCK_DEFAULT` (int)
`MYSQLX_LOCK_NOWAIT` (int)
`MYSQLX_LOCK_SKIP_LOCKED` (int)

# Changelog

The following changes have been made to classes/functions/methods of this extension.

### General Changelog for the ext/mysql_xdevapi extension

This changelog references the ext/mysql_xdevapi extension.

### Global ext/mysql_xdevapi changes

Version | Description
--- | ---
8.0.28 | Removed TLSv1 and TLSv1.1 support. The values "TLSv1", "TLSv1.0", and "TLSv1.1" are now considered invalid for the "tls-versions" connection attribute.
8.0.26 | Deprecated TLSv1 and TLSv1.1 support.

# Examples

The central entry point to the X DevAPI is the mysql_xdevapi\getSession() function, which receives a URI to a MySQL 8.0 Server and returns a mysql_xdevapi\Session object.

Example #1 Connecting to a MySQL Server

`<?php
try {
$session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
die("Connection could not be established: " . $e->getMessage());
}
// ... use $session
?>`

The session provides full access to the API. For a new MySQL Server installation, the first step is to create a database schema with a collection to store data:

Example #2 Creating a Schema and Collection on the MySQL Server

`<?php
$schema = $session->createSchema("test");
$collection = $schema->createCollection("example");
?>`

When storing data, typically json_encode() is used to encode the data into JSON, which can then be stored inside a collection.

The following example stores data into the collection we created earlier, and then retrieve parts of it again.

Example #3 Storing and Retrieving Data

`<?php
$marco = [
"name" => "Marco",
"age" => 19,
"job" => "Programmer"
];
$mike = [
"name" => "Mike",
"age" => 39,
"job" => "Manager"
];
$schema = $session->getSchema("test");
$collection = $schema->getCollection("example");
$collection->add($marco, $mike)->execute();
var_dump($collection->find("name = 'Mike'")->execute()->fetchOne());
?>`

The above example will output something similar to:

    array(4) {
      ["_id"]=>
      string(28) "00005ad66aaf0000000000000003"
      ["age"]=>
      int(39)
      ["job"]=>
      string(7) "Manager"
      ["name"]=>
      string(4) "Mike"
    }

The example demonstrates that the MySQL Server adds an extra field named `_id`, which serves as primary key to the document.

The example also demonstrates that retrieved data is sorted alphabetically. That specific order comes from the efficient binary storage inside the MySQL server, but it should not be relied upon. Refer to the MySQL JSON datatype documentation for details.

Optionally use PHP's iterators to fetch multiple documents:

Example #4 Fetching and Iterating Multiple Documents

`<?php
$result = $collection->find()->execute();
foreach ($result as $doc) {
echo "{$doc["name"]} is a {$doc["job"]}.\n";
}
?>`

The above example will output something similar to:

    Marco is a Programmer.
    Mike is a Manager.

# Mysql_xdevapi Functions

# expression

(No version information available, might only be in Git)

expression — Bind prepared statement variables as parameters

### Description

mysql_xdevapi\expression(string `$expression`): object

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`expression`

### Return Values

### Examples

Example #1 mysql_xdevapi\Expression() example

`<?php
$expression = mysql_xdevapi\Expression("[age,job]");
$res = $coll->find("age > 30")->fields($expression)->limit(3)->execute();
$data = $res->fetchAll();
print_r($data);
?>`

The above example will output something similar to:

    <?php

# getSession

(No version information available, might only be in Git)

getSession — Connect to a MySQL server

### Description

mysql_xdevapi\getSession(string `$uri`): mysql_xdevapi\Session

Connects to the MySQL server.

### Parameters

`uri`

  The URI to the MySQL server, such as `mysqlx://user:password@host`.

  URI format:

  `scheme://[user[:[password]]@]target[:port][?attribute1=value1&attribute2=value2...`

  - `scheme`: required, the connection protocol

    In mysql_xdevapi it is always 'mysqlx' (for X Protocol)

  - `user`: optional, the MySQL user account for authentication

  - `password`: optional, the MySQL user's password for authentication

  - `target`: required, the server instance the connection refers to:

    * TCP connection (host name, IPv4 address, or IPv6 address)

    * Unix socket path (local file path)

    * Windows named-pipe (local file path)

  - `port`: optional, network port of MySQL server.

    by default port for X Protocol is 33060

  - `?attribute=value`: this element is optional and specifies a data dictionary that contains different options, including:

    - The `auth` (authentication mechanism) attribute as it relates to encrypted connections. For additional information, see » Command Options for Encrypted Connections. The following 'auth' values are supported: `plain`, `mysql41`, `external`, and `sha256_mem`.

    - The `connect-timeout` attribute affects the connection and not subsequent operations. It is set per connection whether on a single or multiple hosts.

      Pass in a positive integer to define the connection timeout in seconds, or pass in 0 (zero) to disable the timeout (infinite). Not defining connect-timeout uses the default value of 10.

      Related, the MYSQLX_CONNECTION_TIMEOUT (timeout in seconds) and MYSQLX_TEST_CONNECTION_TIMEOUT (used while running tests) environment variables can be set and used instead of connect-timeout in the URI. The connect-timeout URI option has precedence over these environment variables.

    - The optional `compression` attribute accepts these values: `preferred` (client negotiates with server to find a supported algorithm; connection is uncompressed if a mutually supported algorithm is not found), `required` (like "preferred", but connection is terminated if a mutually supported algorithm is not found), or `disabled` (connection is uncompressed). Defaults to `preferred`.

      This option was added in version 8.0.20.

    - The optional `compression-algorithms` attribute defines the desired compression algorithms (and their preferred usage order): `zstd_stream` (alias: zstd), `lz4_message` (alias: lz4), or `deflate_stream` (aliases: deflate or zlib). By default, the order used (depending on system availability) is lz4_message, zstd_stream, then deflate_stream. For example, passing in compression-algorithms=[lz4,zstd_stream] uses lz4 if it's available, otherwise zstd_stream is used. If both are unavailable then behavior depends on the compression value e.g., if compression=required then it'll fail with an error.

      This option was added in version 8.0.22.

  Example #1 URI examples

  `mysqlx://foobar
  mysqlx://root@localhost?socket=%2Ftmp%2Fmysqld.sock%2F
  mysqlx://foo:bar@localhost:33060
  mysqlx://foo:bar@localhost:33160?ssl-mode=disabled
  mysqlx://foo:bar@localhost:33260?ssl-mode=required
  mysqlx://foo:bar@localhost:33360?ssl-mode=required&auth=mysql41
  mysqlx://foo:bar@(/path/to/socket)
  mysqlx://foo:bar@(/path/to/socket)?auth=sha256_mem
  mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]
  mysqlx://foobar?ssl-ca=(/path/to/ca.pem)&ssl-crl=(/path/to/crl.pem)
  mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]?ssl-mode=disabled
  mysqlx://foo:bar@localhost:33160/?connect-timeout=0
  mysqlx://foo:bar@localhost:33160/?connect-timeout=10&compression=required
  mysqlx://foo:bar@localhost:33160/?connect-timeout=10&compression=required&compression-algorithms=[lz4,zstd_stream]`

  For related information, see MySQL Shell's » Connecting using a URI String.

### Return Values

A Session object.

### Errors/Exceptions

A connection failure throws an Exception.

### Examples

Example #2 mysql_xdevapi\getSession() example

`<?php
try {
$session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
die("Connection could not be established: " . $e->getMessage());
}
$schemas = $session->getSchemas();
print_r($schemas);
$mysql_version = $session->getServerVersion();
print_r($mysql_version);
var_dump($collection->find("name = 'Alfred'")->execute()->fetchOne());
?>`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\Schema Object
            (
                [name] => helloworld
            )
        [1] => mysql_xdevapi\Schema Object
            (
                [name] => information_schema
            )
        [2] => mysql_xdevapi\Schema Object
            (
                [name] => mysql
            )
        [3] => mysql_xdevapi\Schema Object
            (
                [name] => performance_schema
            )
        [4] => mysql_xdevapi\Schema Object
            (
                [name] => sys
            )
    )

    80012

    array(4) {
      ["_id"]=>
      string(28) "00005ad66abf0001000400000003"
      ["age"]=>
      int(42)
      ["job"]=>
      string(7) "Butler"
      ["name"]=>
      string(4) "Alfred"
    }

## Table of Contents

- expression — Bind prepared statement variables as parameters
- getSession — Connect to a MySQL server

# BaseResult interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\BaseResult {
/* Methods */
abstract public getWarnings(): array
abstract public getWarningsCount(): int
}

# BaseResult::getWarnings

(No version information available, might only be in Git)

BaseResult::getWarnings — Fetch warnings from last operation

### Description

abstract public mysql_xdevapi\BaseResult::getWarnings(): array

Fetches warnings generated by MySQL server's last operation.

### Parameters

This function has no parameters.

### Return Values

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarnings() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();
print_r($warnings);
?>`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
        [1] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
    )

# BaseResult::getWarningsCount

(No version information available, might only be in Git)

BaseResult::getWarningsCount — Fetch warning count from last operation

### Description

abstract public mysql_xdevapi\BaseResult::getWarningsCount(): int

Returns the number of warnings raised by the last operation. Specifically, these warnings are raised by the MySQL server.

### Parameters

This function has no parameters.

### Return Values

The number of warnings from the last operation.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
echo $res->getWarningsCount();
?>`

The above example will output something similar to:

    2

## Table of Contents

- BaseResult::getWarnings — Fetch warnings from last operation
- BaseResult::getWarningsCount — Fetch warning count from last operation

# Client class

(No version information available, might only be in Git)

## Introduction

Provides access to the connection pool.

## Class synopsis

class mysql_xdevapi\Client {
/* Methods */
public close(): bool
public getSession(): mysql_xdevapi\Session
}

# mysql_xdevapi\Client::close

(No version information available, might only be in Git)

mysql_xdevapi\Client::close — Close client

### Description

public mysql_xdevapi\Client::close(): bool

Close all client connections with the server.

### Parameters

This function has no parameters.

### Return Values

`true` if connections are closed.

# Client::__construct

(No version information available, might only be in Git)

Client::__construct — Client constructor

### Description

private mysql_xdevapi\Client::__construct()

Construct a client object.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Client::__construct() example

`<?php
$pooling_options = '{
"enabled": true,
"maxSize": 10,
"maxIdleTime": 3600,
"queueTimeOut": 1000
}';
$client = mysql_xdevapi\getClient($connection_uri, $pooling_options);
$session = $client->getSession();`

# Client::getClient

(No version information available, might only be in Git)

Client::getClient — Get client session

### Description

public mysql_xdevapi\Client::getSession(): mysql_xdevapi\Session

Get session associated with the client.

### Parameters

This function has no parameters.

### Return Values

A Session object.

## Table of Contents

- mysql_xdevapi\Client::close — Close client
- Client::__construct — Client constructor
- Client::getClient — Get client session

# Collection class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Collection implements mysql_xdevapi\SchemaObject {
/* Properties */
public $name;
/* Methods */
public add(mixed `$document`): mysql_xdevapi\CollectionAdd
public addOrReplaceOne(string `$id`, string `$doc`): mysql_xdevapi\Result
public count(): int
public createIndex(string `$index_name`, string `$index_desc_json`): void
public dropIndex(string `$index_name`): bool
public existsInDatabase(): bool
public find(string `$search_condition` = ?): mysql_xdevapi\CollectionFind
public getName(): string
public getOne(string `$id`): Document
public getSchema(): Schema Object
public getSession(): Session
public modify(string `$search_condition`): mysql_xdevapi\CollectionModify
public remove(string `$search_condition`): mysql_xdevapi\CollectionRemove
public removeOne(string `$id`): mysql_xdevapi\Result
public replaceOne(string `$id`, string `$doc`): mysql_xdevapi\Result
}

## Properties

name

# Collection::add

(No version information available, might only be in Git)

Collection::add — Add collection document

### Description

public mysql_xdevapi\Collection::add(mixed `$document`): mysql_xdevapi\CollectionAdd

Triggers the insertion of the given document(s) into the collection, and multiple variants of this method are supported. Options include:

1. Add a single document as a JSON string.

2. Add a single document as an array as: `[ 'field' => 'value', 'field2' => 'value2' ... ]`

3. A mix of both, and multiple documents can be added in the same operation.

### Parameters

`document`

  One or multiple documents, and this can be either JSON or an array of fields with their associated values. This cannot be an empty array.

  The MySQL server automatically generates unique `_id` values for each document (recommended), although this can be manually added as well. This value must be unique as otherwise the add operation will fail.

### Return Values

A CollectionAdd object. Use execute() to return a Result that can be used to query the number of affected items, the number warnings generated by the operation, or to fetch a list of generated IDs for the inserted documents.

### Examples

Example #1 mysql_xdevapi\Collection::add() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
// Add two documents
$collection->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
// Add two documents using a single JSON object
$result = $collection->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')->execute();
// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 00005b6b53610000000000000056
        [1] => 00005b6b53610000000000000057
    )

### Notes

> Note:

> A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

# Collection::addOrReplaceOne

(No version information available, might only be in Git)

Collection::addOrReplaceOne — Add or replace collection document

### Description

public mysql_xdevapi\Collection::addOrReplaceOne(string `$id`, string `$doc`): mysql_xdevapi\Result

Add a new document, or replace a document if it already exists.

Here are several scenarios for this method:

- If neither the id or any unique key values conflict with any document in the collection, then the document is added.

- If the id does not match any document but one or more unique key values conflict with a document in the collection, then an error is raised.

- If id matches an existing document and no unique keys are defined for the collection, then the document is replaced.

- If id matches an existing document, and either all unique keys in the replacement document match that same document or they don't conflict with any other documents in the collection, then the document is replaced.

- If id matches an existing document and one or more unique keys match a different document from the collection, then an error is raised.

### Parameters

`id`

  This is the filter id. If this id or any other field that has a unique index already exists in the collection, then it will update the matching document instead.

  By default, this id is automatically generated by MySQL Server when the record was added, and is referenced as a field named '_id'.

`doc`

  This is the document to add or replace, which is a JSON string.

### Return Values

A Result object.

### Examples

Example #1 mysql_xdevapi\Collection::addOrReplaceOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
// Using add()
$result = $collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
// Using addOrReplaceOne()
// Note: we're passing in a known _id value here
$result = $collection->addOrReplaceOne('00005b6b53610000000000000056', '{"name": "Fred", "age": 21, "job": "Construction"}');
?>`

# Collection::__construct

(No version information available, might only be in Git)

Collection::__construct — Collection constructor

### Description

private mysql_xdevapi\Collection::__construct()

Construct a Collection object.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Collection::getOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();
// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids = $result->getGeneratedIds();
$alfreds_id = $ids[0];
// ...
print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>`

The above example will output something similar to:

    00005b6b536100000000000000b1

    Array
    (
        [_id] => 00005b6b536100000000000000b1
        [age] => 42
        [job] => Butler
        [name] => Alfred
    )

# Collection::count

(No version information available, might only be in Git)

Collection::count — Get document count

### Description

public mysql_xdevapi\Collection::count(): int

This functionality is similar to a `SELECT COUNT(*)` SQL operation against the MySQL server for the current schema and collection. In other words, it counts the number of documents in the collection.

### Parameters

This function has no parameters.

### Return Values

The number of documents in the collection.

### Examples

Example #1 mysql_xdevapi\Collection::count() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [
{"title":"Cat Herder","Salary":42000},
{"title":"Father","Salary":0}
],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [
{"title":"Scientist","Salary":18000},
{"title":"Mother","Salary":0}
],
"hobbies": ["Walking","Making pies"]}')
->execute();
var_dump($collection->count());
?>`

The above example will output:

    int(2)

# Collection::createIndex

(No version information available, might only be in Git)

Collection::createIndex — Create collection index

### Description

public mysql_xdevapi\Collection::createIndex(string `$index_name`, string `$index_desc_json`): void

Creates an index on the collection.

An exception is thrown if an index with the same name already exists, or if index definition is not correctly formed.

### Parameters

`index_name`

  The name of the index that to create. This name must be a valid index name as accepted by the `CREATE INDEX` SQL query.

`index_desc_json`

  Definition of the index to create. It contains an array of IndexField objects, and each object describes a single document member to include in the index, and an optional string for the type of index that might be INDEX (default) or SPATIAL.

  A single IndexField description consists of the following fields:

  - `field`: string, the full document path to the document member or field to be indexed.

  - `type`: string, one of the supported SQL column types to map the field into. For numeric types, the optional UNSIGNED keyword may follow. For the TEXT type, the length to consider for indexing may be added.

  - `required`: bool, (optional) true if the field is required to exist in the document. Defaults to `false`, except for `GEOJSON` where it defaults to `true`.

  - `options`: integer, (optional) special option flags for use when decoding `GEOJSON` data.

  - `srid`: integer, (optional) srid value for use when decoding `GEOJSON` data.

  It is an error to include other fields not described above in IndexDefinition or IndexField documents.

### Return Values

### Examples

Example #1 mysql_xdevapi\Collection::createIndex() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
// Creating a text index
$collection->createIndex(
'myindex1',
'{"fields": [{
"field": "$.name",
"type": "TEXT(25)",
"required": true}],
"unique": false}'
);
// A spatial index
$collection->createIndex(
'myindex2',
'{"fields": [{
"field": "$.home",
"type": "GEOJSON",
"required": true}],
"type": "SPATIAL"}'
);
// Index with multiple fields
$collection->createIndex(
'myindex3',
'{"fields": [
{
"field": "$.name",
"type": "TEXT(20)",
"required": true
},
{
"field": "$.age",
"type": "INTEGER"
},
{
"field": "$.job",
"type": "TEXT(30)",
"required": false
}
],
"unique": true
}'
);`

# Collection::dropIndex

(No version information available, might only be in Git)

Collection::dropIndex — Drop collection index

### Description

public mysql_xdevapi\Collection::dropIndex(string `$index_name`): bool

Drop a collection index.

This operation does not yield an error if the index does not exist, but `false` is returned in that case.

### Parameters

`index_name`

  Name of collection index to drop.

### Return Values

`true` if the DROP INDEX operation succeeded, otherwise `false`.

### Examples

Example #1 mysql_xdevapi\Collection::dropIndex() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
// ...
$collection = $schema->getCollection("people");
$collection->createIndex(
'myindex',
'{"fields": [{"field": "$.name", "type": "TEXT(25)", "required": true}], "unique": false}'
);
// ...
if ($collection->dropIndex('myindex')) {
echo "An index named 'myindex' was found, and dropped.";
}
?>`

The above example will output:

    An index named 'myindex' was found, and dropped.

# Collection::existsInDatabase

(No version information available, might only be in Git)

Collection::existsInDatabase — Check if collection exists in database

### Description

public mysql_xdevapi\Collection::existsInDatabase(): bool

Checks if the Collection object refers to a collection in the database (schema).

### Parameters

This function has no parameters.

### Return Values

Returns `true` if collection exists in the database, else `false` if it does not.

A table defined with two columns (doc and _id) is considered a collection, and a third _json_schema column as of MySQL 8.0.21. Adding an additional column means existsInDatabase() will no longer see it as a collection.

### Examples

Example #1 mysql_xdevapi\Collection::existsInDatabase() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
// ...
$collection = $schema->getCollection("people");
// ...
if (!$collection->existsInDatabase()) {
echo "The collection no longer exists in the database named addressbook. What happened?";
}
?>`

# Collection::find

(No version information available, might only be in Git)

Collection::find — Search for document

### Description

public mysql_xdevapi\Collection::find(string `$search_condition` = ?): mysql_xdevapi\CollectionFind

Search a database collection for a document or set of documents. The found documents are returned as a CollectionFind object is to further modify or fetch results from.

### Parameters

`search_condition`

  Although optional, normally a condition is defined to limit the results to a subset of documents.

  Multiple elements might build the condition and the syntax supports parameter binding. The expression used as search condition must be a valid SQL expression. If no search condition is provided (field empty) then find('true') is assumed.

### Return Values

A CollectionFind object to verify the operation, or fetch the found documents.

### Examples

Example #1 mysql_xdevapi\Collection::find() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Swimmer"}')->execute();
$collection->add('{"name": "Fred", "age": 20, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 21, "job": "Teacher"}')->execute();
$collection->add('{"name": "Suki", "age": 22, "job": "Teacher"}')->execute();
$find = $collection->find('job LIKE :job AND age > :age');
$result = $find
->bind(['job' => 'Teacher', 'age' => 20])
->sort('age DESC')
->limit(2)
->execute();
print_r($result->fetchAll());
?>`

The above example will output:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b536100000000000000a8
                [age] => 22
                [job] => Teacher
                [name] => Suki
            )
        [1] => Array
            (
                [_id] => 00005b6b536100000000000000a7
                [age] => 21
                [job] => Teacher
                [name] => Wilma
            )
    )

# Collection::getName

(No version information available, might only be in Git)

Collection::getName — Get collection name

### Description

public mysql_xdevapi\Collection::getName(): string

Retrieve the collection's name.

### Parameters

This function has no parameters.

### Return Values

The collection name, as a string.

### Examples

Example #1 mysql_xdevapi\Collection::getName() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
// ...
var_dump($collection->getName());
?>`

The above example will output something similar to:

    string(6) "people"

# Collection::getOne

(No version information available, might only be in Git)

Collection::getOne — Get one document

### Description

public mysql_xdevapi\Collection::getOne(string `$id`): Document

Fetches one document from the collection.

This is a shortcut for: `Collection.find("_id = :id").bind("id", id).execute().fetchOne();`

### Parameters

`id`

  The document _id in the collection.

### Return Values

The collection object, or `null` if the _id does not match a document.

### Examples

Example #1 mysql_xdevapi\Collection::getOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();
// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids = $result->getGeneratedIds();
$alfreds_id = $ids[0];
// ...
print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>`

The above example will output something similar to:

    00005b6b536100000000000000b1

    Array
    (
        [_id] => 00005b6b536100000000000000b1
        [age] => 42
        [job] => Butler
        [name] => Alfred
    )

# Collection::getSchema

(No version information available, might only be in Git)

Collection::getSchema — Get schema object

### Description

public mysql_xdevapi\Collection::getSchema(): Schema Object

Retrieve the schema object that contains the collection.

### Parameters

This function has no parameters.

### Return Values

The schema object on success, or `null` if the object cannot be retrieved for the given collection.

### Examples

Example #1 mysql_xdevapi\Collection::getSchema() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
var_dump($collection->getSchema());
?>`

The above example will output something similar to:

    object(mysql_xdevapi\Schema)#9 (1) {
      ["name"]=>
      string(11) "addressbook"
    }

# Collection::getSession

(No version information available, might only be in Git)

Collection::getSession — Get session object

### Description

public mysql_xdevapi\Collection::getSession(): Session

Get a new Session object from the Collection object.

### Parameters

This function has no parameters.

### Return Values

A Session object.

### Examples

Example #1 mysql_xdevapi\Collection::getSession() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
// ...
$newsession = $collection->getSession();
var_dump($session);
var_dump($newsession);
?>`

The above example will output something similar to:

    object(mysql_xdevapi\Session)#1 (0) {
    }
    object(mysql_xdevapi\Session)#4 (0) {
    }

# Collection::modify

(No version information available, might only be in Git)

Collection::modify — Modify collection documents

### Description

public mysql_xdevapi\Collection::modify(string `$search_condition`): mysql_xdevapi\CollectionModify

Modify the documents of a collection that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

### Parameters

`search_condition`

  Must be a valid SQL expression used to match the documents to modify. This expression might be as simple as `true`, which matches all documents, or it might use functions and operators such as `'CAST(_id AS SIGNED) >= 10'`, `'age MOD 2 = 0 OR age MOD 3 = 0'`, or `'_id IN ["2","5","7","10"]'`.

### Return Values

If the operation is not executed, then the function will return a Modify object that can be used to add additional modify operations.

If the modify operation is executed, then the returned object will contain the result of the operation.

### Examples

Example #1 mysql_xdevapi\Collection::modify() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();
// Add two new jobs for all Painters: Artist and Crafter
$collection
->modify("job in ('Butler', 'Painter')")
->arrayAppend('job', 'Artist')
->arrayAppend('job', 'Crafter')
->execute();
// Remove the 'beer' field from all documents with the age 21
$collection
->modify('age < 21')
->unset(['beer'])
->execute();
?>`

# Collection::remove

(No version information available, might only be in Git)

Collection::remove — Remove collection documents

### Description

public mysql_xdevapi\Collection::remove(string `$search_condition`): mysql_xdevapi\CollectionRemove

Removes documents of a collection that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

### Parameters

`search_condition`

  Must be a valid SQL expression used to match the documents to remove. This expression might be as simple as `true`, which matches all documents, or it might use functions and operators such as `'CAST(_id AS SIGNED) >= 10'`, `'age MOD 2 = 0 OR age MOD 3 = 0'`, or `'_id IN ["2","5","7","10"]'`.

### Return Values

If the operation is not executed, then the function will return a Remove object that can be used to add additional remove operations.

If the remove operation is executed, then the returned object will contain the result of the operation.

### Examples

Example #1 mysql_xdevapi\Collection::remove() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();
// Remove all painters
$collection
->remove("job in ('Painter')")
->execute();
// Remove the oldest butler
$collection
->remove("job in ('Butler')")
->sort('age desc')
->limit(1)
->execute();
// Remove record with highest age
$collection
->remove('true')
->sort('age desc')
->limit(1)
->execute();
?>`

# Collection::removeOne

(No version information available, might only be in Git)

Collection::removeOne — Remove one collection document

### Description

public mysql_xdevapi\Collection::removeOne(string `$id`): mysql_xdevapi\Result

Remove one document from the collection with the corresponding ID. This is a shortcut for `Collection.remove("_id = :id").bind("id", id).execute()`.

### Parameters

`id`

  The ID of the collection document to remove. Typically this is the _id that was generated by MySQL Server when the record was added.

### Return Values

A Result object that can be used to query the number of affected items or the number warnings generated by the operation.

### Examples

Example #1 mysql_xdevapi\Collection::removeOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
// Normally the _id is known by other means,
// but for this example let's fetch the generated id and use it
$ids = $result->getGeneratedIds();
$alfred_id = $ids[0];
$result = $collection->removeOne($alfred_id);
if(!$result->getAffectedItemsCount()) {
echo "Alfred with id $alfred_id was not removed.";
} else {
echo "Goodbye, Alfred, you can take _id $alfred_id with you.";
}
?>`

The above example will output something similar to:

    Goodbye, Alfred, you can take _id 00005b6b536100000000000000cb with you.

# Collection::replaceOne

(No version information available, might only be in Git)

Collection::replaceOne — Replace one collection document

### Description

public mysql_xdevapi\Collection::replaceOne(string `$id`, string `$doc`): mysql_xdevapi\Result

Updates (or replaces) the document identified by ID, if it exists.

### Parameters

`id`

  ID of the document to replace or update. Typically this is the _id that was generated by MySQL Server when the record was added.

`doc`

  Collection document to update or replace the document matching the id parameter.

  This document can be either a document object or a valid JSON string describing the new document.

### Return Values

A Result object that can be used to query the number of affected items and the number warnings generated by the operation.

### Examples

Example #1 mysql_xdevapi\Collection::replaceOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
// Normally the _id is known by other means,
// but for this example let's fetch the generated id and use it
$ids = $result->getGeneratedIds();
$alfred_id = $ids[0];
// ...
$alfred = $collection->getOne($alfred_id);
$alfred['age'] = 81;
$alfred['job'] = 'Guru';
$collection->replaceOne($alfred_id, $alfred);
?>`

## Table of Contents

- Collection::add — Add collection document
- Collection::addOrReplaceOne — Add or replace collection document
- Collection::__construct — Collection constructor
- Collection::count — Get document count
- Collection::createIndex — Create collection index
- Collection::dropIndex — Drop collection index
- Collection::existsInDatabase — Check if collection exists in database
- Collection::find — Search for document
- Collection::getName — Get collection name
- Collection::getOne — Get one document
- Collection::getSchema — Get schema object
- Collection::getSession — Get session object
- Collection::modify — Modify collection documents
- Collection::remove — Remove collection documents
- Collection::removeOne — Remove one collection document
- Collection::replaceOne — Replace one collection document

# CollectionAdd class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CollectionAdd implements mysql_xdevapi\Executable {
/* Methods */
public execute(): mysql_xdevapi\Result
}

# CollectionAdd::__construct

(No version information available, might only be in Git)

CollectionAdd::__construct — CollectionAdd constructor

### Description

private mysql_xdevapi\CollectionAdd::__construct()

Use to add a document to a collection; called from a Collection object.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\CollectionAdd::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
// Add two documents
$collection
->add('{"name": "Fred", "age": 21, "job": "Construction"}')
->execute();
$collection
->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
->execute();
// Add two documents using a single JSON object
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')
->execute();
// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 00005b6b53610000000000000056
        [1] => 00005b6b53610000000000000057
    )

### Notes

> Note:

> A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

# CollectionAdd::execute

(No version information available, might only be in Git)

CollectionAdd::execute — Execute the statement

### Description

public mysql_xdevapi\CollectionAdd::execute(): mysql_xdevapi\Result

The execute method is required to send the CRUD operation request to the MySQL server.

### Parameters

This function has no parameters.

### Return Values

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

### Examples

Example #1 mysql_xdevapi\CollectionAdd::execute() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
// Add two documents
$collection
->add('{"name": "Fred", "age": 21, "job": "Construction"}')
->execute();
$collection
->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
->execute();
// Add two documents using a single JSON object
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')
->execute();
// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 00005b6b53610000000000000056
        [1] => 00005b6b53610000000000000057
    )

## Table of Contents

- CollectionAdd::__construct — CollectionAdd constructor
- CollectionAdd::execute — Execute the statement

# CollectionFind class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CollectionFind implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSortable {
/* Methods */
public bind(array `$placeholder_values`): mysql_xdevapi\CollectionFind
public execute(): mysql_xdevapi\DocResult
public fields(string `$projection`): mysql_xdevapi\CollectionFind
public groupBy(string `$sort_expr`): mysql_xdevapi\CollectionFind
public having(string `$sort_expr`): mysql_xdevapi\CollectionFind
public limit(int `$rows`): mysql_xdevapi\CollectionFind
public lockExclusive(int `$lock_waiting_option` = ?): mysql_xdevapi\CollectionFind
public lockShared(int `$lock_waiting_option` = ?): mysql_xdevapi\CollectionFind
public offset(int `$position`): mysql_xdevapi\CollectionFind
public sort(string `$sort_expr`): mysql_xdevapi\CollectionFind
}

# CollectionFind::bind

(No version information available, might only be in Git)

CollectionFind::bind — Bind value to query placeholder

### Description

public mysql_xdevapi\CollectionFind::bind(array `$placeholder_values`): mysql_xdevapi\CollectionFind

It allows the user to bind a parameter to the placeholder in the search condition of the find operation. The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME, NAME is the actual name of the placeholder. The bind function accepts a list of placeholders if multiple entities have to be substituted in the search condition.

### Parameters

`placeholder_values`

  Values to substitute in the search condition; multiple values are allowed and are passed as an array where "PLACEHOLDER_NAME => PLACEHOLDER_VALUE".

### Return Values

A CollectionFind object, or chain with execute() to return a Result object.

### Examples

Example #1 mysql_xdevapi\CollectionFind::bind() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000cf"
        ["age"]=>
        int(18)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(6) "Alfred"
      }
    }

# CollectionFind::__construct

(No version information available, might only be in Git)

CollectionFind::__construct — CollectionFind constructor

### Description

private mysql_xdevapi\CollectionFind::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 CollectionFind example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000cf"
        ["age"]=>
        int(18)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(6) "Alfred"
      }
    }

# CollectionFind::execute

(No version information available, might only be in Git)

CollectionFind::execute — Execute the statement

### Description

public mysql_xdevapi\CollectionFind::execute(): mysql_xdevapi\DocResult

Execute the find operation; this functionality allows for method chaining.

### Parameters

This function has no parameters.

### Return Values

A mysql_xdevapi\DocResult object that can be used to either fetch results from, or to query the status of the operation.

### Examples

Example #1 CollectionFind example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000cf"
        ["age"]=>
        int(18)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(6) "Alfred"
      }
    }

# CollectionFind::fields

(No version information available, might only be in Git)

CollectionFind::fields — Set document field filter

### Description

public mysql_xdevapi\CollectionFind::fields(string `$projection`): mysql_xdevapi\CollectionFind

Defines the columns for the query to return. If not defined, all columns are used.

### Parameters

`projection`

  Can either be a single string or an array of strings identifying the columns to be returned for each document that match the search condition.

### Return Values

A CollectionFind object that can be used for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionFind::fields() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->fields('name')
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(1) {
        ["name"]=>
        string(6) "Alfred"
      }
    }

# CollectionFind::groupBy

(No version information available, might only be in Git)

CollectionFind::groupBy — Set grouping criteria

### Description

public mysql_xdevapi\CollectionFind::groupBy(string `$sort_expr`): mysql_xdevapi\CollectionFind

This function can be used to group the result set by one or more columns. It is often used with aggregate functions such as `COUNT`, `MAX`, `MIN`, `SUM` etc.

### Parameters

`sort_expr`

  The column or columns that have to be used for the group operation, this can either be a single string or an array of string arguments, one for each column.

### Return Values

A CollectionFind object that can be used for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionFind::groupBy() example

`<?php
// Assuming $coll is a valid Collection object
// Extract all the documents from the Collection and group the results by the 'name' field
$res = $coll->find()->groupBy('name')->execute();
?>`

# CollectionFind::having

(No version information available, might only be in Git)

CollectionFind::having — Set condition for aggregate functions

### Description

public mysql_xdevapi\CollectionFind::having(string `$sort_expr`): mysql_xdevapi\CollectionFind

This function can be used after the 'field' operation in order to make a selection on the documents to extract.

### Parameters

`sort_expr`

  This must be a valid SQL expression, the use of aggreate functions is allowed

### Return Values

CollectionFind object that can be used for further processing

### Examples

Example #1 mysql_xdevapi\CollectionFind::having() example

`<?php
//Assuming $coll is a valid Collection object
//Find all the documents for which the 'age' is greather than 40,
//Only the columns 'name' and 'age' are returned in the Result object
$res = $coll->find()->fields(['name','age'])->having('age > 40')->execute();
?>`

# CollectionFind::limit

(No version information available, might only be in Git)

CollectionFind::limit — Limit number of returned documents

### Description

public mysql_xdevapi\CollectionFind::limit(int `$rows`): mysql_xdevapi\CollectionFind

Set the maximum number of documents to return.

### Parameters

`rows`

  Maximum number of documents.

### Return Values

A CollectionFind object that can be used for additional processing; chain with the execute() method to return a DocResult object.

### Examples

Example #1 mysql_xdevapi\CollectionFind::limit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->limit(1)
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000f3"
        ["age"]=>
        int(42)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(8) "Reginald"
      }
    }

# CollectionFind::lockExclusive

(No version information available, might only be in Git)

CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK

### Description

public mysql_xdevapi\CollectionFind::lockExclusive(int `$lock_waiting_option` = ?): mysql_xdevapi\CollectionFind

Locks the document exclusively. As long as the document is locked, other transactions can't update the document, use `SELECT ... LOCK IN SHARE MODE`, or read the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view.

To avoid concurrency problems, it makes sense to use this function with the mysql_xdevapi\Collection::modify() method. Essentially, this function uses row locks to serialise access to rows.

### Parameters

`lock_waiting_option`

  Optional waiting option. By default it is `MYSQLX_LOCK_DEFAULT`. Valid values are these constants:

  - `MYSQLX_LOCK_DEFAULT`

  - `MYSQLX_LOCK_NOWAIT`

  - `MYSQLX_LOCK_SKIP_LOCKED`

### Return Values

Returns a CollectionFind object that can be used for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionFind::lockExclusive() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$session->startTransaction();
$result = $collection
->find("age > 50")
->lockExclusive()
->execute();
// ... do an operation on the object
// Complete the transaction and unlock the document
$session->commit();
?>`

# CollectionFind::lockShared

(No version information available, might only be in Git)

CollectionFind::lockShared — Execute operation with SHARED LOCK

### Description

public mysql_xdevapi\CollectionFind::lockShared(int `$lock_waiting_option` = ?): mysql_xdevapi\CollectionFind

Allows to share the documents between multiple transactions which are locking in shared mode.

Other sessions can read the rows, but cannot modify them until your transaction commits.

If any of these rows were changed by another transaction that hasn't been committed, the query will wait until that transaction has ended to be able to use the latest values.

### Parameters

`lock_waiting_option`

  Optional waiting option. By default it is `MYSQLX_LOCK_DEFAULT`. Valid values are these constants:

  - `MYSQLX_LOCK_DEFAULT`

  - `MYSQLX_LOCK_NOWAIT`

  - `MYSQLX_LOCK_SKIP_LOCKED`

### Return Values

A CollectionFind object that can be used for further processing

### Examples

Example #1 mysql_xdevapi\CollectionFind::lockShared() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$session->startTransaction();
$result = $collection
->find("age > 50")
->lockShared()
->execute();
// ... read the object in shared mode
// Complete the transaction and unlock the document
$session->commit();
?>`

# CollectionFind::offset

(No version information available, might only be in Git)

CollectionFind::offset — Skip given number of elements to be returned

### Description

public mysql_xdevapi\CollectionFind::offset(int `$position`): mysql_xdevapi\CollectionFind

Skip (offset) these number of elements that otherwise would be returned by the find operation. Use with the limit() method.

Defining an offset larger than the result set size results in an empty set.

### Parameters

`position`

  Number of elements to skip for the limit() operation.

### Return Values

A CollectionFind object that can be used for additional processing.

### Examples

Example #1 mysql_xdevapi\CollectionFind::offset() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find()
->sort('age asc')
->offset(1)
->limit(1)
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000f3"
        ["age"]=>
        int(42)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(8) "Reginald"
      }
    }

# CollectionFind::sort

(No version information available, might only be in Git)

CollectionFind::sort — Set the sorting criteria

### Description

public mysql_xdevapi\CollectionFind::sort(string `$sort_expr`): mysql_xdevapi\CollectionFind

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

### Parameters

`sort_expr`

  One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

### Return Values

A CollectionFind object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionFind::sort() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find()
->sort('job desc', 'age asc')
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(2) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b53610000000000000106"
        ["age"]=>
        int(18)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(6) "Alfred"
      }
      [1]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b53610000000000000107"
        ["age"]=>
        int(42)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(8) "Reginald"
      }
    }

## Table of Contents

- CollectionFind::bind — Bind value to query placeholder
- CollectionFind::__construct — CollectionFind constructor
- CollectionFind::execute — Execute the statement
- CollectionFind::fields — Set document field filter
- CollectionFind::groupBy — Set grouping criteria
- CollectionFind::having — Set condition for aggregate functions
- CollectionFind::limit — Limit number of returned documents
- CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK
- CollectionFind::lockShared — Execute operation with SHARED LOCK
- CollectionFind::offset — Skip given number of elements to be returned
- CollectionFind::sort — Set the sorting criteria

# CollectionModify class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CollectionModify implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSkippable, mysql_xdevapi\CrudOperationSortable {
/* Methods */
public arrayAppend(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify
public arrayInsert(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify
public bind(array `$placeholder_values`): mysql_xdevapi\CollectionModify
public execute(): mysql_xdevapi\Result
public limit(int `$rows`): mysql_xdevapi\CollectionModify
public patch(string `$document`): mysql_xdevapi\CollectionModify
public replace(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify
public set(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify
public skip(int `$position`): mysql_xdevapi\CollectionModify
public sort(string `$sort_expr`): mysql_xdevapi\CollectionModify
public unset(array `$fields`): mysql_xdevapi\CollectionModify
}

# CollectionModify::arrayAppend

(No version information available, might only be in Git)

CollectionModify::arrayAppend — Append element to an array field

### Description

public mysql_xdevapi\CollectionModify::arrayAppend(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayInsert(), arrayAppend() always appends the new element at the end of the array, whereas arrayInsert() can define the location.

### Parameters

`collection_field`

  The identifier of the field where the new element is inserted.

`expression_or_literal`

  The new element to insert at the end of the document field array.

### Return Values

A CollectionModify object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionModify::arrayAppend() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name in ('Bernie', 'Jane')")
->arrayAppend('traits', 'Happy')
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b5361000000000000010c
                [name] => Bernie
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Brother
                        [2] => Human
                        [3] => Happy
                    )
            )
    )

# CollectionModify::arrayInsert

(No version information available, might only be in Git)

CollectionModify::arrayInsert — Insert element into an array field

### Description

public mysql_xdevapi\CollectionModify::arrayInsert(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify

Adds an element to a document's field, as multiple elements of a field are represented as an array. Unlike mysql_xdevapi\CollectionModify::arrayAppend() this method allows to specify where the new element is inserted by defining which item it is after, whereas mysql_xdevapi\CollectionModify::arrayAppend() always appends the new element at the end of the array.

### Parameters

`collection_field`

  Identifies the item in the array after which the new element will be inserted. The format of this parameter is `FIELD_NAME[ INDEX ]` where FIELD_NAME is the name of the document field to add the element to, and INDEX is the INDEX of the element within the field.

  The INDEX field is zero based, so the first item of the array has an index of 0.

`expression_or_literal`

  The new element to insert after FIELD_NAME[ INDEX ]

### Return Values

A CollectionModify object that can be used to execute the command, or to add additional operations

### Examples

Example #1 mysql_xdevapi\CollectionModify::arrayInsert() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name in ('Bernie', 'Jane')")
->arrayInsert('traits[1]', 'Happy')
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b5361000000000000010d
                [name] => Bernie
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Happy
                        [2] => Brother
                        [3] => Human
                    )
            )
    )

# CollectionModify::bind

(No version information available, might only be in Git)

CollectionModify::bind — Bind value to query placeholder

### Description

public mysql_xdevapi\CollectionModify::bind(array `$placeholder_values`): mysql_xdevapi\CollectionModify

Bind a parameter to the placeholder in the search condition of the modify operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the modify operation.

### Parameters

`placeholder_values`

  Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

### Return Values

A CollectionModify object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionModify::bind() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->arrayAppend('traits', 'Happy')
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b53610000000000000110
                [name] => Bernie
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Brother
                        [2] => Human
                        [3] => Happy
                    )
            )
    )

# CollectionModify::__construct

(No version information available, might only be in Git)

CollectionModify::__construct — CollectionModify constructor

### Description

private mysql_xdevapi\CollectionModify::__construct()

Modifies (updates) a collection and is instantiated by the mysql_xdevapi\Collection::modify() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\CollectionModify::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name in ('Bernie', 'Jane')")
->arrayAppend('traits', 'Happy')
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b5361000000000000010c
                [name] => Bernie
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Brother
                        [2] => Human
                        [3] => Happy
                    )
            )
    )

# CollectionModify::execute

(No version information available, might only be in Git)

CollectionModify::execute — Execute modify operation

### Description

public mysql_xdevapi\CollectionModify::execute(): mysql_xdevapi\Result

The execute method is required to send the CRUD operation request to the MySQL server.

### Parameters

This function has no parameters.

### Return Values

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

### Examples

Example #1 mysql_xdevapi\CollectionModify::execute() example

`<?php
/* ... */
?>`

# CollectionModify::limit

(No version information available, might only be in Git)

CollectionModify::limit — Limit number of modified documents

### Description

public mysql_xdevapi\CollectionModify::limit(int `$rows`): mysql_xdevapi\CollectionModify

Limit the number of documents modified by this operation. Optionally combine with skip() to define an offset value.

### Parameters

`rows`

  The maximum number of documents to modify.

### Return Values

A CollectionModify object.

### Examples

Example #1 mysql_xdevapi\CollectionModify::limit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$collection->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
$collection->add('{"name": "Betty", "age": 24, "job": "Teacher"}')->execute();
$collection
->modify("job = :job")
->bind(['job' => 'Teacher'])
->set('job', 'Principal')
->limit(1)
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b53610000000000000118
                [age] => 21
                [job] => Construction
                [name] => Fred
            )
        [1] => Array
            (
                [_id] => 00005b6b53610000000000000119
                [age] => 23
                [job] => Principal
                [name] => Wilma
            )
        [2] => Array
            (
                [_id] => 00005b6b5361000000000000011a
                [age] => 24
                [job] => Teacher
                [name] => Betty
            )
    )

# CollectionModify::patch

(No version information available, might only be in Git)

CollectionModify::patch — Patch document

### Description

public mysql_xdevapi\CollectionModify::patch(string `$document`): mysql_xdevapi\CollectionModify

Takes a patch object and applies it on one or more documents, and can update multiple document properties.

### Parameters

`document`

  A document with the properties to apply to the matching documents.

### Return Values

A CollectionModify object.

### Examples

Example #1 mysql_xdevapi\CollectionModify::patch() example

`<?php
$res = $coll->modify('"Programmatore" IN job')->patch('{"Hobby" : "Programmare"}')->execute();
?>`

# CollectionModify::replace

(No version information available, might only be in Git)

CollectionModify::replace — Replace document field

### Description

public mysql_xdevapi\CollectionModify::replace(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify

Replace (update) a given field value with a new one.

### Parameters

`collection_field`

  The document path of the item to set.

`expression_or_literal`

  The value to set on the specified attribute.

### Return Values

A CollectionModify object.

### Examples

Example #1 mysql_xdevapi\CollectionModify::replace() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->replace("name", "Bern")
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b5361000000000000011b
                [name] => Bern
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Brother
                        [2] => Human
                    )
            )
    )

# CollectionModify::set

(No version information available, might only be in Git)

CollectionModify::set — Set document attribute

### Description

public mysql_xdevapi\CollectionModify::set(string `$collection_field`, string `$expression_or_literal`): mysql_xdevapi\CollectionModify

Sets or updates attributes on documents in a collection.

### Parameters

`collection_field`

  The document path (name) of the item to set.

`expression_or_literal`

  The value to set it to.

### Return Values

A CollectionModify object.

### Examples

Example #1 mysql_xdevapi\CollectionModify::set() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();
$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->set("name", "Bern")
->execute();
$result = $collection
->find()
->execute();
print_r($result->fetchAll());
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [_id] => 00005b6b53610000000000000111
                [name] => Bern
                [traits] => Array
                    (
                        [0] => Friend
                        [1] => Brother
                        [2] => Human
                    )
            )
    )

# CollectionModify::skip

(No version information available, might only be in Git)

CollectionModify::skip — Skip elements

### Description

public mysql_xdevapi\CollectionModify::skip(int `$position`): mysql_xdevapi\CollectionModify

Skips the first N elements that would otherwise be returned by a find operation. If the number of elements skipped is larger than the size of the result set, then the find operation returns an empty set.

### Parameters

`position`

  Number of elements to skip.

### Return Values

A CollectionModify object to use for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionModify::skip() example

`<?php
$coll->modify('age > :age')->sort('age desc')->unset(['age'])->bind(['age' => 20])->limit(4)->skip(1)->execute();
?>`

# CollectionModify::sort

(No version information available, might only be in Git)

CollectionModify::sort — Set the sorting criteria

### Description

public mysql_xdevapi\CollectionModify::sort(string `$sort_expr`): mysql_xdevapi\CollectionModify

Sorts the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

### Parameters

`sort_expr`

  One or more sort expressions can be provided. The evaluation is from left to right and each expression must be separated by a comma.

### Return Values

CollectionModify object that can be used for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionModify::sort() example

`<?php
$res = $coll->modify('true')->sort('name desc', 'age asc')->limit(4)->set('Married', 'NO')->execute();
?>`

# CollectionModify::unset

(No version information available, might only be in Git)

CollectionModify::unset — Unset the value of document fields

### Description

public mysql_xdevapi\CollectionModify::unset(array `$fields`): mysql_xdevapi\CollectionModify

Removes attributes from documents in a collection.

### Parameters

`fields`

  The attributes to remove from documents in a collection.

### Return Values

CollectionModify object that can be used for further processing.

### Examples

Example #1 mysql_xdevapi\CollectionModify::unset() example

`<?php
$res = $coll->modify('job like :job_name')->unset(["age", "name"])->bind(['job_name' => 'Plumber'])->execute();
?>`

## Table of Contents

- CollectionModify::arrayAppend — Append element to an array field
- CollectionModify::arrayInsert — Insert element into an array field
- CollectionModify::bind — Bind value to query placeholder
- CollectionModify::__construct — CollectionModify constructor
- CollectionModify::execute — Execute modify operation
- CollectionModify::limit — Limit number of modified documents
- CollectionModify::patch — Patch document
- CollectionModify::replace — Replace document field
- CollectionModify::set — Set document attribute
- CollectionModify::skip — Skip elements
- CollectionModify::sort — Set the sorting criteria
- CollectionModify::unset — Unset the value of document fields

# CollectionRemove class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CollectionRemove implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSortable {
/* Methods */
public bind(array `$placeholder_values`): mysql_xdevapi\CollectionRemove
public execute(): mysql_xdevapi\Result
public limit(int `$rows`): mysql_xdevapi\CollectionRemove
public sort(string `$sort_expr`): mysql_xdevapi\CollectionRemove
}

# CollectionRemove::bind

(No version information available, might only be in Git)

CollectionRemove::bind — Bind value to placeholder

### Description

public mysql_xdevapi\CollectionRemove::bind(array `$placeholder_values`): mysql_xdevapi\CollectionRemove

Bind a parameter to the placeholder in the search condition of the remove operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the remove operation.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`placeholder_values`

  Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

### Return Values

A CollectionRemove object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionRemove::bind() example

`<?php
$res = $coll->remove('age > :age_from and age < :age_to')->bind(['age_from' => 20, 'age_to' => 50])->limit(7)->execute();
?>`

# CollectionRemove::__construct

(No version information available, might only be in Git)

CollectionRemove::__construct — CollectionRemove constructor

### Description

private mysql_xdevapi\CollectionRemove::__construct()

Removes collection documents and is instantiated by the mysql_xdevapi\Collection::remove() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Collection::remove() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");
$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();
// Remove all painters
$collection
->remove("job in ('Painter')")
->execute();
// Remove the oldest butler
$collection
->remove("job in ('Butler')")
->sort('age desc')
->limit(1)
->execute();
// Remove record with lowest age
$collection
->remove('true')
->sort('age desc')
->limit(1)
->execute();
?>`

# CollectionRemove::execute

(No version information available, might only be in Git)

CollectionRemove::execute — Execute remove operation

### Description

public mysql_xdevapi\CollectionRemove::execute(): mysql_xdevapi\Result

The execute function needs to be invoked in order to trigger the client to send the CRUD operation request to the server.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Result object.

### Examples

Example #1 mysql_xdevapi\CollectionRemove::execute() example

`<?php
$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();
?>`

# CollectionRemove::limit

(No version information available, might only be in Git)

CollectionRemove::limit — Limit number of documents to remove

### Description

public mysql_xdevapi\CollectionRemove::limit(int `$rows`): mysql_xdevapi\CollectionRemove

Sets the maximum number of documents to remove.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`rows`

  The maximum number of documents to remove.

### Return Values

Returns a CollectionRemove object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionRemove::limit() example

`<?php
$res = $coll->remove('job in (\'Barista\', \'Programmatore\', \'Ballerino\', \'Programmatrice\')')->limit(5)->sort(['age desc', 'name asc'])->execute();
?>`

# CollectionRemove::sort

(No version information available, might only be in Git)

CollectionRemove::sort — Set the sorting criteria

### Description

public mysql_xdevapi\CollectionRemove::sort(string `$sort_expr`): mysql_xdevapi\CollectionRemove

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`sort_expr`

  One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

### Return Values

A CollectionRemove object that can be used to execute the command, or to add additional operations.

### Examples

Example #1 mysql_xdevapi\CollectionRemove::sort() example

`<?php
$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();
?>`

## Table of Contents

- CollectionRemove::bind — Bind value to placeholder
- CollectionRemove::__construct — CollectionRemove constructor
- CollectionRemove::execute — Execute remove operation
- CollectionRemove::limit — Limit number of documents to remove
- CollectionRemove::sort — Set the sorting criteria

# ColumnResult class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\ColumnResult {
/* Methods */
public getCharacterSetName(): string
public getCollationName(): string
public getColumnLabel(): string
public getColumnName(): string
public getFractionalDigits(): int
public getLength(): int
public getSchemaName(): string
public getTableLabel(): string
public getTableName(): string
public getType(): int
public isNumberSigned(): int
public isPadded(): int
}

# ColumnResult::__construct

(No version information available, might only be in Git)

ColumnResult::__construct — ColumnResult constructor

### Description

private mysql_xdevapi\ColumnResult::__construct()

Retrieves column metadata, such as its character set; this is instantiated by the mysql_xdevapi\RowResult::getColumns() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\ColumnResult::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS nonsense")->execute();
$session->sql("CREATE DATABASE nonsense")->execute();
$session->sql("CREATE TABLE nonsense.numbers (hello int, world float unsigned)")->execute();
$session->sql("INSERT INTO nonsense.numbers values (42, 42)")->execute();
$schema = $session->getSchema("nonsense");
$table = $schema->getTable("numbers");
$result1 = $table->select('hello','world')->execute();
// Returns an array of ColumnResult objects
$columns = $result1->getColumns();
foreach ($columns as $column) {
echo "\nColumn label " , $column->getColumnLabel();
echo " is type " , $column->getType();
echo " and is ", ($column->isNumberSigned() === 0) ? "unsigned." : "signed.";
}
// Alternatively
$result2 = $session->sql("SELECT * FROM nonsense.numbers")->execute();
// Returns an array of FieldMetadata objects
print_r($result2->getColumns());`

The above example will output something similar to:

    Column label hello is type 19 and is signed.
    Column label world is type 4  and is unsigned.

    Array
    (
        [0] => mysql_xdevapi\FieldMetadata Object
            (
                [type] => 1
                [type_name] => SINT
                [name] => hello
                [original_name] => hello
                [table] => numbers
                [original_table] => numbers
                [schema] => nonsense
                [catalog] => def
                [collation] => 0
                [fractional_digits] => 0
                [length] => 11
                [flags] => 0
                [content_type] => 0
            )
        [1] => mysql_xdevapi\FieldMetadata Object
            (
                [type] => 6
                [type_name] => FLOAT
                [name] => world
                [original_name] => world
                [table] => numbers
                [original_table] => numbers
                [schema] => nonsense
                [catalog] => def
                [collation] => 0
                [fractional_digits] => 31
                [length] => 12
                [flags] => 1
                [content_type] => 0
            )
    )

# ColumnResult::getCharacterSetName

(No version information available, might only be in Git)

ColumnResult::getCharacterSetName — Get character set

### Description

public mysql_xdevapi\ColumnResult::getCharacterSetName(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getCharacterSetName() example

`<?php
/* ... */
?>`

# ColumnResult::getCollationName

(No version information available, might only be in Git)

ColumnResult::getCollationName — Get collation name

### Description

public mysql_xdevapi\ColumnResult::getCollationName(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getCollationName() example

`<?php
/* ... */
?>`

# ColumnResult::getColumnLabel

(No version information available, might only be in Git)

ColumnResult::getColumnLabel — Get column label

### Description

public mysql_xdevapi\ColumnResult::getColumnLabel(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getColumnLabel() example

`<?php
/* ... */
?>`

# ColumnResult::getColumnName

(No version information available, might only be in Git)

ColumnResult::getColumnName — Get column name

### Description

public mysql_xdevapi\ColumnResult::getColumnName(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getColumnName() example

`<?php
/* ... */
?>`

# ColumnResult::getFractionalDigits

(No version information available, might only be in Git)

ColumnResult::getFractionalDigits — Get fractional digit length

### Description

public mysql_xdevapi\ColumnResult::getFractionalDigits(): int

Fetch the number of fractional digits for column.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getFractionalDigits() example

`<?php
/* ... */
?>`

# ColumnResult::getLength

(No version information available, might only be in Git)

ColumnResult::getLength — Get column field length

### Description

public mysql_xdevapi\ColumnResult::getLength(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getLength() example

`<?php
/* ... */
?>`

# ColumnResult::getSchemaName

(No version information available, might only be in Git)

ColumnResult::getSchemaName — Get schema name

### Description

public mysql_xdevapi\ColumnResult::getSchemaName(): string

Fetch the schema name where the column is stored.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getSchemaName() example

`<?php
/* ... */
?>`

# ColumnResult::getTableLabel

(No version information available, might only be in Git)

ColumnResult::getTableLabel — Get table label

### Description

public mysql_xdevapi\ColumnResult::getTableLabel(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getTableLabel() example

`<?php
/* ... */
?>`

# ColumnResult::getTableName

(No version information available, might only be in Git)

ColumnResult::getTableName — Get table name

### Description

public mysql_xdevapi\ColumnResult::getTableName(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Name of the table for the column.

### Examples

Example #1 mysql_xdevapi\ColumnResult::getTableName() example

`<?php
/* ... */
?>`

# ColumnResult::getType

(No version information available, might only be in Git)

ColumnResult::getType — Get column type

### Description

public mysql_xdevapi\ColumnResult::getType(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\ColumnResult::getType() example

`<?php
/* ... */
?>`

# ColumnResult::isNumberSigned

(No version information available, might only be in Git)

ColumnResult::isNumberSigned — Check if signed type

### Description

public mysql_xdevapi\ColumnResult::isNumberSigned(): int

Retrieves a table's column information and is instantiated by the mysql_xdevapi\RowResult::getColumns() method.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

`true` if a given column as a signed type.

### Examples

Example #1 mysql_xdevapi\ColumnResult::isNumberSigned() example

`<?php
/* ... */
?>`

# ColumnResult::isPadded

(No version information available, might only be in Git)

ColumnResult::isPadded — Check if padded

### Description

public mysql_xdevapi\ColumnResult::isPadded(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

`true` if a given column is padded.

### Examples

Example #1 mysql_xdevapi\ColumnResult::isPadded() example

`<?php
/* ... */
?>`

## Table of Contents

- ColumnResult::__construct — ColumnResult constructor
- ColumnResult::getCharacterSetName — Get character set
- ColumnResult::getCollationName — Get collation name
- ColumnResult::getColumnLabel — Get column label
- ColumnResult::getColumnName — Get column name
- ColumnResult::getFractionalDigits — Get fractional digit length
- ColumnResult::getLength — Get column field length
- ColumnResult::getSchemaName — Get schema name
- ColumnResult::getTableLabel — Get table label
- ColumnResult::getTableName — Get table name
- ColumnResult::getType — Get column type
- ColumnResult::isNumberSigned — Check if signed type
- ColumnResult::isPadded — Check if padded

# CrudOperationBindable interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CrudOperationBindable {
/* Methods */
abstract public bind(array `$placeholder_values`): mysql_xdevapi\CrudOperationBindable
}

# CrudOperationBindable::bind

(No version information available, might only be in Git)

CrudOperationBindable::bind — Bind value to placeholder

### Description

abstract public mysql_xdevapi\CrudOperationBindable::bind(array `$placeholder_values`): mysql_xdevapi\CrudOperationBindable

Binds a value to a specific placeholder.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`placeholder_values`

  The name of the placeholders and the values to bind.

### Return Values

A CrudOperationBindable object.

### Examples

Example #1 mysql_xdevapi\CrudOperationBindable::bind() example

`<?php
$res = $coll->modify('name like :name')->arrayInsert('job[0]', 'Calciatore')->bind(['name' => 'ENTITY'])->execute();
$res = $table->delete()->orderby('age desc')->where('age < 20 and age > 12 and name != :name')->bind(['name' => 'Tierney'])->limit(2)->execute();
?>`

## Table of Contents

- CrudOperationBindable::bind — Bind value to placeholder

# CrudOperationLimitable interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CrudOperationLimitable {
/* Methods */
abstract public limit(int `$rows`): mysql_xdevapi\CrudOperationLimitable
}

# CrudOperationLimitable::limit

(No version information available, might only be in Git)

CrudOperationLimitable::limit — Set result limit

### Description

abstract public mysql_xdevapi\CrudOperationLimitable::limit(int `$rows`): mysql_xdevapi\CrudOperationLimitable

Sets the maximum number of records or documents to return.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`rows`

  The maximum number of records or documents.

### Return Values

A CrudOperationLimitable object.

### Examples

Example #1 mysql_xdevapi\CrudOperationLimitable::limit() example

`<?php
$res = $coll->find()->fields(['name as n','age as a','job as j'])->groupBy('j')->limit(11)->execute();
$res = $table->update()->set('age',69)->where('age > 15 and age < 22')->limit(4)->orderby(['age asc','name desc'])->execute();
?>`

## Table of Contents

- CrudOperationLimitable::limit — Set result limit

# CrudOperationSkippable interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CrudOperationSkippable {
/* Methods */
abstract public skip(int `$skip`): mysql_xdevapi\CrudOperationSkippable
}

# CrudOperationSkippable::skip

(No version information available, might only be in Git)

CrudOperationSkippable::skip — Number of operations to skip

### Description

abstract public mysql_xdevapi\CrudOperationSkippable::skip(int `$skip`): mysql_xdevapi\CrudOperationSkippable

Skip this number of records in the returned operation.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`skip`

  Number of elements to skip.

### Return Values

A CrudOperationSkippable object.

### Examples

Example #1 mysql_xdevapi\CrudOperationSkippable::skip() example

`<?php
$res = $coll->find('job like \'Programmatore\'')->limit(1)->skip(3)->sort('age asc')->execute();
?>`

## Table of Contents

- CrudOperationSkippable::skip — Number of operations to skip

# CrudOperationSortable interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\CrudOperationSortable {
/* Methods */
abstract public sort(string `$sort_expr`): mysql_xdevapi\CrudOperationSortable
}

# CrudOperationSortable::sort

(No version information available, might only be in Git)

CrudOperationSortable::sort — Sort results

### Description

abstract public mysql_xdevapi\CrudOperationSortable::sort(string `$sort_expr`): mysql_xdevapi\CrudOperationSortable

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`sort_expr`

  One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

### Return Values

A CrudOperationSortable object.

### Examples

Example #1 mysql_xdevapi\CrudOperationSortable::sort() example

`<?php
$res = $coll->find('job like \'Cavia\'')->sort('age desc', '_id desc')->execute();
?>`

## Table of Contents

- CrudOperationSortable::sort — Sort results

# DatabaseObject interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\DatabaseObject {
/* Methods */
abstract public existsInDatabase(): bool
abstract public getName(): string
abstract public getSession(): mysql_xdevapi\Session
}

# DatabaseObject::existsInDatabase

(No version information available, might only be in Git)

DatabaseObject::existsInDatabase — Check if object exists in database

### Description

abstract public mysql_xdevapi\DatabaseObject::existsInDatabase(): bool

Verifies if the database object refers to an object that exists in the database.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if object exists in the database, else `false` if it does not.

### Examples

Example #1 mysql_xdevapi\DatabaseObject::existsInDatabase() example

`<?php
$existInDb = $dbObj->existsInDatabase();
?>`

# DatabaseObject::getName

(No version information available, might only be in Git)

DatabaseObject::getName — Get object name

### Description

abstract public mysql_xdevapi\DatabaseObject::getName(): string

Fetch name of this database object.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The name of this database object.

### Examples

Example #1 mysql_xdevapi\DatabaseObject::getName() example

`<?php
$dbObjName = $dbObj->getName();
?>`

# DatabaseObject::getSession

(No version information available, might only be in Git)

DatabaseObject::getSession — Get session name

### Description

abstract public mysql_xdevapi\DatabaseObject::getSession(): mysql_xdevapi\Session

Fetch session associated to the database object.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The Session object.

### Examples

Example #1 mysql_xdevapi\DatabaseObject::getSession() example

`<?php
$session = $dbObj->getSession();
?>`

## Table of Contents

- DatabaseObject::existsInDatabase — Check if object exists in database
- DatabaseObject::getName — Get object name
- DatabaseObject::getSession — Get session name

# DocResult class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\DocResult implements mysql_xdevapi\BaseResult, Traversable {
/* Methods */
public fetchAll(): array
public fetchOne(): array
public getWarnings(): Array
public getWarningsCount(): int
}

# DocResult::__construct

(No version information available, might only be in Git)

DocResult::__construct — DocResult constructor

### Description

private mysql_xdevapi\DocResult::__construct()

Fetch document results and warnings, and is instantiated by CollectionFind.

### Parameters

This function has no parameters.

### Examples

Example #1 A DocResult example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();
// ...
$collection = $schema->getCollection("people");
// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->limit(1)
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b536100000000000000f3"
        ["age"]=>
        int(42)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(8) "Reginald"
      }
    }

# DocResult::fetchAll

(No version information available, might only be in Git)

DocResult::fetchAll — Get all rows

### Description

public mysql_xdevapi\DocResult::fetchAll(): array

Fetch all results from a result set.

### Parameters

This function has no parameters.

### Return Values

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

### Examples

Example #1 mysql_xdevapi\DocResult::fetchAll() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();
// ...
$collection = $schema->getCollection("people");
// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();
var_dump($result->fetchAll());
?>`

The above example will output something similar to:

    array(2) {

      [0]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b53610000000000000123"
        ["age"]=>
        int(42)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(8) "Reginald"
      }

      [1]=>
      array(4) {
        ["_id"]=>
        string(28) "00005b6b53610000000000000122"
        ["age"]=>
        int(18)
        ["job"]=>
        string(6) "Butler"
        ["name"]=>
        string(6) "Alfred"
      }

    }

# DocResult::fetchOne

(No version information available, might only be in Git)

DocResult::fetchOne — Get one row

### Description

public mysql_xdevapi\DocResult::fetchOne(): array

Fetch one result from a result set.

### Parameters

This function has no parameters.

### Return Values

The result, as an associative array or `null` if no results are present.

### Examples

Example #1 mysql_xdevapi\DocResult::fetchOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();
// ...
$collection = $schema->getCollection("people");
// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();
var_dump($result->fetchOne());
?>`

The above example will output something similar to:

    array(4) {
      ["_id"]=>
      string(28) "00005b6b53610000000000000125"
      ["age"]=>
      int(42)
      ["job"]=>
      string(6) "Butler"
      ["name"]=>
      string(8) "Reginald"
    }

# DocResult::getWarnings

(No version information available, might only be in Git)

DocResult::getWarnings — Get warnings from last operation

### Description

public mysql_xdevapi\DocResult::getWarnings(): Array

Fetches warnings generated by MySQL server's last operation.

### Parameters

This function has no parameters.

### Return Values

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

### Examples

Example #1 mysql_xdevapi\DocResult::getWarnings() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();
// ...
$collection = $schema->getCollection("people");
// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();
if (!$result->getWarningsCount()) {
echo "There was an error:\n";
print_r($result->getWarnings());
exit;
}
var_dump($result->fetchOne());
?>`

The above example will output something similar to:

    There was an error:

    Array
    (
        [0] => mysql_xdevapi\Warning Object
            (
                [message] => Something bad and so on
                [level] => 2
                [code] => 1365
            )
        [1] => mysql_xdevapi\Warning Object
            (
                [message] => Something bad and so on
                [level] => 2
                [code] => 1365
            )
    )

# DocResult::getWarningsCount

(No version information available, might only be in Git)

DocResult::getWarningsCount — Get warning count from last operation

### Description

public mysql_xdevapi\DocResult::getWarningsCount(): int

Returns the number of warnings raised by the last operation. Specifically, these warnings are raised by the MySQL server.

### Parameters

This function has no parameters.

### Return Values

The number of warnings from the last operation.

### Examples

Example #1 mysql_xdevapi\DocResult::getWarningsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();
// ...
$collection = $schema->getCollection("people");
// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();
if (!$result->getWarningsCount()) {
echo "There was an error:\n";
print_r($result->getWarnings());
exit;
}
var_dump($result->fetchOne());
?>`

The above example will output something similar to:

    array(4) {
      ["_id"]=>
      string(28) "00005b6b53610000000000000135"
      ["age"]=>
      int(42)
      ["job"]=>
      string(6) "Butler"
      ["name"]=>
      string(8) "Reginald"
    }

## Table of Contents

- DocResult::__construct — DocResult constructor
- DocResult::fetchAll — Get all rows
- DocResult::fetchOne — Get one row
- DocResult::getWarnings — Get warnings from last operation
- DocResult::getWarningsCount — Get warning count from last operation

# Exception class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Exception extends RuntimeException implements Throwable {
}

# Executable interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Executable {
/* Methods */
abstract public execute(): mysql_xdevapi\Result
}

# Executable::execute

(No version information available, might only be in Git)

Executable::execute — Execute statement

### Description

abstract public mysql_xdevapi\Executable::execute(): mysql_xdevapi\Result

Execute the statement from either a collection operation or a table query; this functionality allows for method chaining.

### Parameters

This function has no parameters.

### Return Values

One of the Result objects, such as Result or SqlStatementResult.

### Examples

Example #1 execute() examples

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$result_sql = $session->sql("CREATE DATABASE addressbook")->execute();
var_dump($result_sql);
$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("humans");
$result_collection = $collection->add(
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}');
$result_collection_executed = $result_collection->execute();
var_dump($result_collection);
var_dump($result_collection_executed);
?>`

The above example will output something similar to:

    object(mysql_xdevapi\SqlStatementResult)#3 (0) {
    }

    object(mysql_xdevapi\CollectionAdd)#5 (0) {
    }

    object(mysql_xdevapi\Result)#7 (0) {
    }

## Table of Contents

- Executable::execute — Execute statement

# ExecutionStatus class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\ExecutionStatus {
/* Properties */
public $affectedItems;
public $matchedItems;
public $foundItems;
public $lastInsertId;
public $lastDocumentId;
/* Constructor */
private __construct()
}

## Properties

affectedItems

matchedItems

foundItems

lastInsertId

lastDocumentId

# ExecutionStatus::__construct

(No version information available, might only be in Git)

ExecutionStatus::__construct — ExecutionStatus constructor

### Description

private mysql_xdevapi\ExecutionStatus::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\ExecutionStatus::__construct() example

`<?php
/* ... */
?>`

## Table of Contents

- ExecutionStatus::__construct — ExecutionStatus constructor

# Expression class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Expression {
/* Properties */
public $name;
/* Constructor */
public __construct(string `$expression`)
}

## Properties

name

# Expression::__construct

(No version information available, might only be in Git)

Expression::__construct — Expression constructor

### Description

public mysql_xdevapi\Expression::__construct(string `$expression`)

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`expression`

### Examples

Example #1 mysql_xdevapi\Expression::__construct() example

`<?php
/* ... */
?>`

## Table of Contents

- Expression::__construct — Expression constructor

# Result class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Result implements mysql_xdevapi\BaseResult, Traversable {
/* Methods */
public getAffectedItemsCount(): int
public getAutoIncrementValue(): int
public getGeneratedIds(): array
public getWarnings(): array
public getWarningsCount(): int
}

# Result::__construct

(No version information available, might only be in Git)

Result::__construct — Result constructor

### Description

private mysql_xdevapi\Result::__construct()

An object that retrieves generated IDs, AUTO_INCREMENT values, and warnings, for a Result set.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Result::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("
CREATE TABLE addressbook.names
(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30), age INT, PRIMARY KEY (id))
")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->insert("name", "age")->values(["Suzanne", 31],["Julie", 43])->execute();
$result = $table->insert("name", "age")->values(["Suki", 34])->execute();
$ai = $result->getAutoIncrementValue();
var_dump($ai);
?>`

The above example will output:

    int(3)

# Result::getAffectedItemsCount

(No version information available, might only be in Git)

Result::getAffectedItemsCount — Get affected row count

### Description

public mysql_xdevapi\Result::getAffectedItemsCount(): int

Get the number of affected rows by the previous operation.

### Parameters

This function has no parameters.

### Return Values

The number (as an integer) of affected rows.

### Examples

Example #1 mysql_xdevapi\Result::getAffectedItemsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
$result = $collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
var_dump( $res->getAffectedItemsCount() );
?>`

The above example will output:

    int(1)

# Result::getAutoIncrementValue

(No version information available, might only be in Git)

Result::getAutoIncrementValue — Get autoincremented value

### Description

public mysql_xdevapi\Result::getAutoIncrementValue(): int

Get the last AUTO_INCREMENT value (last insert id).

### Parameters

This function has no parameters.

### Return Values

The last AUTO_INCREMENT value.

### Examples

Example #1 mysql_xdevapi\Result::getAutoIncrementValue() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("
CREATE TABLE addressbook.names
(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30), age INT, PRIMARY KEY (id))
")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->insert("name", "age")->values(["Suzanne", 31],["Julie", 43])->execute();
$result = $table->insert("name", "age")->values(["Suki", 34])->execute();
$ai = $result->getAutoIncrementValue();
var_dump($ai);
?>`

The above example will output:

    int(3)

# Result::getGeneratedIds

(No version information available, might only be in Git)

Result::getGeneratedIds — Get generated ids

### Description

public mysql_xdevapi\Result::getGeneratedIds(): array

Fetch the generated _id values from the last operation. The unique _id field is generated by the MySQL server.

### Parameters

This function has no parameters.

### Return Values

An array of generated _id's from the last operation, or an empty array if there are none.

### Examples

Example #1 mysql_xdevapi\Result::getGeneratedIds() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
$result = $collection->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')->execute();
$ids = $result->getGeneratedIds();
var_dump($ids);
?>`

The above example will output something similar to:

    array(2) {
      [0]=>
      string(28) "00005b6b53610000000000000064"
      [1]=>
      string(28) "00005b6b53610000000000000065"
    }

# Result::getWarnings

(No version information available, might only be in Git)

Result::getWarnings — Get warnings from last operation

### Description

public mysql_xdevapi\Result::getWarnings(): array

Retrieve warnings from the last Result operation.

### Parameters

This function has no parameters.

### Return Values

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarnings() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();
print_r($warnings);
?>`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
        [1] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
    )

# Result::getWarningsCount

(No version information available, might only be in Git)

Result::getWarningsCount — Get warning count from last operation

### Description

public mysql_xdevapi\Result::getWarningsCount(): int

Retrieve the number of warnings from the last Result operation.

### Parameters

This function has no parameters.

### Return Values

The number of warnings generated by the last operation.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
echo $res->getWarningsCount();
?>`

The above example will output something similar to:

    2

## Table of Contents

- Result::__construct — Result constructor
- Result::getAffectedItemsCount — Get affected row count
- Result::getAutoIncrementValue — Get autoincremented value
- Result::getGeneratedIds — Get generated ids
- Result::getWarnings — Get warnings from last operation
- Result::getWarningsCount — Get warning count from last operation

# RowResult class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\RowResult implements mysql_xdevapi\BaseResult, Traversable {
/* Methods */
public fetchAll(): array
public fetchOne(): array
public getColumnsCount(): int
public getColumnNames(): array
public getColumns(): array
public getWarnings(): array
public getWarningsCount(): int
}

# RowResult::__construct

(No version information available, might only be in Git)

RowResult::__construct — RowResult constructor

### Description

private mysql_xdevapi\RowResult::__construct()

Represents the result set obtained from querying the database.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\RowResult::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$row = $table->select('name', 'age')->where('age > 18')->execute()->fetchAll();
print_r($row);`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 33
            )
    )

# RowResult::fetchAll

(No version information available, might only be in Git)

RowResult::fetchAll — Get all rows from result

### Description

public mysql_xdevapi\RowResult::fetchAll(): array

Fetch all the rows from the result set.

### Parameters

This function has no parameters.

### Return Values

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

### Examples

Example #1 mysql_xdevapi\RowResult::fetchAll() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$row = $table->select('name', 'age')->execute()->fetchAll();
print_r($row);`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 33
            )
    )

# RowResult::fetchOne

(No version information available, might only be in Git)

RowResult::fetchOne — Get row from result

### Description

public mysql_xdevapi\RowResult::fetchOne(): array

Fetch one result from the result set.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The result, as an associative array or `null` if no results are present.

### Examples

Example #1 mysql_xdevapi\RowResult::fetchOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$row = $table->select('name', 'age')->where('age < 40')->execute()->fetchOne();
print_r($row);`

The above example will output something similar to:

    Array
    (
        [name] => Sam
        [age] => 33
    )

# RowResult::getColumnsCount

(No version information available, might only be in Git)

RowResult::getColumnsCount — Get column count

### Description

public mysql_xdevapi\RowResult::getColumnsCount(): int

Retrieve the column count for columns present in the result set.

### Parameters

This function has no parameters.

### Return Values

The number of columns; 0 if there are none.

### Changelog

Version | Description
--- | ---
8.0.14 | Method renamed from getColumnCount() to getColumnsCount().

### Examples

Example #1 mysql_xdevapi\RowResult::getColumnsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$sql = $session->sql("SELECT * from addressbook.names")->execute();
echo $sql->getColumnsCount();`

The above example will output something similar to:

    2

# RowResult::getColumnNames

(No version information available, might only be in Git)

RowResult::getColumnNames — Get all column names

### Description

public mysql_xdevapi\RowResult::getColumnNames(): array

Retrieve column names for columns present in the result set.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

A numerical array of table columns names, or an empty array if the result set is empty.

### Examples

Example #1 mysql_xdevapi\RowResult::getColumnNames() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$sql = $session->sql("SELECT * from addressbook.names")->execute();
$colnames = $sql->getColumnNames();
print_r($colnames);`

The above example will output something similar to:

    Array
    (
        [0] => name
        [1] => age
    )

# RowResult::getColumns

(No version information available, might only be in Git)

RowResult::getColumns — Get column metadata

### Description

public mysql_xdevapi\RowResult::getColumns(): array

Retrieve column metadata for columns present in the result set.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

An array of FieldMetadata objects representing the columns in the result, or an empty array if the result set is empty.

### Examples

Example #1 mysql_xdevapi\RowResult::getColumns() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$sql = $session->sql("SELECT * from addressbook.names")->execute();
$cols = $sql->getColumns();
print_r($cols);`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\FieldMetadata Object
            (
                [type] => 7
                [type_name] => BYTES
                [name] => name
                [original_name] => name
                [table] => names
                [original_table] => names
                [schema] => addressbook
                [catalog] => def
                [collation] => 255
                [fractional_digits] => 0
                [length] => 65535
                [flags] => 0
                [content_type] => 0
            )
        [1] => mysql_xdevapi\FieldMetadata Object
            (
                [type] => 1
                [type_name] => SINT
                [name] => age
                [original_name] => age
                [table] => names
                [original_table] => names
                [schema] => addressbook
                [catalog] => def
                [collation] => 0
                [fractional_digits] => 0
                [length] => 11
                [flags] => 0
                [content_type] => 0
            )
    )

# RowResult::getWarnings

(No version information available, might only be in Git)

RowResult::getWarnings — Get warnings from last operation

### Description

public mysql_xdevapi\RowResult::getWarnings(): array

Retrieve warnings from the last RowResult operation.

### Parameters

This function has no parameters.

### Return Values

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarnings() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();
print_r($warnings);
?>`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
        [1] => mysql_xdevapi\Warning Object
            (
                [message] => Division by 0
                [level] => 2
                [code] => 1365
            )
    )

# RowResult::getWarningsCount

(No version information available, might only be in Git)

RowResult::getWarningsCount — Get warning count from last operation

### Description

public mysql_xdevapi\RowResult::getWarningsCount(): int

Retrieve the number of warnings from the last RowResult operation.

### Parameters

This function has no parameters.

### Return Values

The number of warnings generated by the last operation.

### Examples

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");
$table->insert(['x'])->values([1])->values([2])->execute();
$res = $table->select(['x/0 as bad_x'])->execute();
echo $res->getWarningsCount();
?>`

The above example will output something similar to:

    2

## Table of Contents

- RowResult::__construct — RowResult constructor
- RowResult::fetchAll — Get all rows from result
- RowResult::fetchOne — Get row from result
- RowResult::getColumnsCount — Get column count
- RowResult::getColumnNames — Get all column names
- RowResult::getColumns — Get column metadata
- RowResult::getWarnings — Get warnings from last operation
- RowResult::getWarningsCount — Get warning count from last operation

# Schema class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Schema implements mysql_xdevapi\DatabaseObject {
/* Properties */
public $name;
/* Methods */
public createCollection(string `$name`, string `$validate` = ?): mysql_xdevapi\Collection
public dropCollection(string `$collection_name`): bool
public existsInDatabase(): bool
public getCollection(string `$name`): mysql_xdevapi\Collection
public getCollectionAsTable(string `$name`): mysql_xdevapi\Table
public getCollections(): array
public getName(): string
public getSession(): mysql_xdevapi\Session
public getTable(string `$name`): mysql_xdevapi\Table
public getTables(): array
}

## Properties

name

# Schema::__construct

(No version information available, might only be in Git)

Schema::__construct — Schema constructor

### Description

private mysql_xdevapi\Schema::__construct()

The Schema object provides full access to the schema (database).

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Schema::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();
$schema = $session->getSchema("food");
$schema->createCollection("trees");
print_r($schema->gettables());
print_r($schema->getcollections());`

The above example will output something similar to:

    Array
    (
        [fruit] => mysql_xdevapi\Table Object
            (
                [name] => fruit
            )
    )
    Array
    (
        [trees] => mysql_xdevapi\Collection Object
            (
                [name] => trees
            )
    )

# Schema::createCollection

(No version information available, might only be in Git)

Schema::createCollection — Add collection to schema

### Description

public mysql_xdevapi\Schema::createCollection(string `$name`, string `$validate` = ?): mysql_xdevapi\Collection

Create a collection within the schema.

### Parameters

`name`

  Collection name.

`validate`

  Validation definition, as a JSON object.

### Return Values

The Collection object.

### Changelog

Version | Description
--- | ---
8.0.20 | Added the optional validate parameter.

### Examples

Example #1 mysql_xdevapi\Schema::createCollection() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();
$schema = $session->getSchema("food");
$schema->createCollection("trees");
print_r($schema->gettables());
print_r($schema->getcollections());`

The above example will output something similar to:

    Array
    (
        [fruit] => mysql_xdevapi\Table Object
            (
                [name] => fruit
            )
    )
    Array
    (
        [trees] => mysql_xdevapi\Collection Object
            (
                [name] => trees
            )
    )

Example #2 mysql_xdevapi\Schema::createCollection() example

`<?php
$collection = $schema->createCollection("mycollection", '{
"validation": {
"level": "strict",
"schema": {
"id": "http://json-schema.org/geo",
"description": "A geographical coordinate",
"type": "object",
"properties": {
"latitude": {
"type": "number"
},
"longitude": {
"type": "number"
}
},
"required": ["latitude", "longitude"]
}
}
}');
// Succeeds
$collection->add('{"latitude": 10, "longitude": 20}')->execute();
// Fails, invalid types (not numbers)
$collection->add('{"latitude": "lat", "longitude": "long"}')->execute();`

# Schema::dropCollection

(No version information available, might only be in Git)

Schema::dropCollection — Drop collection from schema

### Description

public mysql_xdevapi\Schema::dropCollection(string `$collection_name`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`collection_name`

### Return Values

### Examples

Example #1 mysql_xdevapi\Schema::dropCollection() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();
$schema = $session->getSchema("food");
$schema->createCollection("trees");
$schema->dropCollection("trees");
$schema->createCollection("buildings");
print_r($schema->gettables());
print_r($schema->getcollections());`

The above example will output something similar to:

    Array
    (
        [fruit] => mysql_xdevapi\Table Object
            (
                [name] => fruit
            )
    )
    Array
    (
        [buildings] => mysql_xdevapi\Collection Object
            (
                [name] => buildings
            )
    )

# Schema::existsInDatabase

(No version information available, might only be in Git)

Schema::existsInDatabase — Check if exists in database

### Description

public mysql_xdevapi\Schema::existsInDatabase(): bool

Checks if the current object (schema, table, collection, or view) exists in the schema object.

### Parameters

This function has no parameters.

### Return Values

`true` if the schema, table, collection, or view still exists in the schema, else `false`.

### Examples

Example #1 mysql_xdevapi\Schema::existsInDatabase() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();
$schema = $session->getSchema("food");
$schema->createCollection("trees");
// ...
$trees = $schema->getCollection("trees");
// ...
// Is this collection still in the database (schema)?
if ($trees->existsInDatabase()) {
echo "Yes, the 'trees' collection is still present.";
}`

The above example will output something similar to:

    Yes, the 'trees' collection is still present.

# Schema::getCollection

(No version information available, might only be in Git)

Schema::getCollection — Get collection from schema

### Description

public mysql_xdevapi\Schema::getCollection(string `$name`): mysql_xdevapi\Collection

Get a collection from the schema.

### Parameters

`name`

  Collection name to retrieve.

### Return Values

The Collection object for the selected collection.

### Examples

Example #1 mysql_xdevapi\Schema::getCollection() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$schema = $session->getSchema("food");
$schema->createCollection("trees");
// ...
$trees = $schema->getCollection("trees");
var_dump($trees);`

The above example will output something similar to:

    object(mysql_xdevapi\Collection)#3 (1) {
      ["name"]=>
      string(5) "trees"
    }

# Schema::getCollectionAsTable

(No version information available, might only be in Git)

Schema::getCollectionAsTable — Get collection as a Table object

### Description

public mysql_xdevapi\Schema::getCollectionAsTable(string `$name`): mysql_xdevapi\Table

Get a collection, but as a Table object instead of a Collection object.

### Parameters

`name`

  Name of the collection to instantiate a Table object from.

### Return Values

A mysql_xdevapi\Table object for the collection.

### Examples

Example #1 mysql_xdevapi\Schema::getCollectionAsTable() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collect = $schema->createCollection("people");
$collect->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collect->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
$table = $schema->getCollectionAsTable("people");
$collection = $schema->getCollection("people");
var_dump($table);
var_dump($collection);`

The above example will output something similar to:

    object(mysql_xdevapi\Table)#4 (1) {
      ["name"]=>
      string(6) "people"
    }

    object(mysql_xdevapi\Collection)#5 (1) {
      ["name"]=>
      string(6) "people"
    }

# Schema::getCollections

(No version information available, might only be in Git)

Schema::getCollections — Get all schema collections

### Description

public mysql_xdevapi\Schema::getCollections(): array

Fetch a list of collections for this schema.

### Parameters

This function has no parameters.

### Return Values

Array of all collections in this schema, where each array element value is a Collection object with the collection name as the key.

### Examples

Example #1 mysql_xdevapi\Schema::getCollections() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$collect = $schema->createCollection("people");
$collect->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collect->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
$collections = $schema->getCollections();
var_dump($collections);
?>`

The above example will output something similar to:

    array(1) {
      ["people"]=>
      object(mysql_xdevapi\Collection)#4 (1) {
        ["name"]=>
        string(6) "people"
      }
    }

# Schema::getName

(No version information available, might only be in Git)

Schema::getName — Get schema name

### Description

public mysql_xdevapi\Schema::getName(): string

Get the name of the schema.

### Parameters

This function has no parameters.

### Return Values

The name of the schema connected to the schema object, as a string.

### Examples

Example #1 mysql_xdevapi\Schema::getName() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
// ...
var_dump($schema->getName());
?>`

The above example will output something similar to:

    string(11) "addressbook"

# Schema::getSession

(No version information available, might only be in Git)

Schema::getSession — Get schema session

### Description

public mysql_xdevapi\Schema::getSession(): mysql_xdevapi\Session

Get a new Session object from the Schema object.

### Parameters

This function has no parameters.

### Return Values

A Session object.

### Examples

Example #1 mysql_xdevapi\Schema::getSession() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
// ...
$newsession = $schema->getSession();
var_dump($session);
var_dump($newsession);
?>`

The above example will output something similar to:

    object(mysql_xdevapi\Session)#1 (0) {
    }

    object(mysql_xdevapi\Session)#3 (0) {
    }

# Schema::getTable

(No version information available, might only be in Git)

Schema::getTable — Get schema table

### Description

public mysql_xdevapi\Schema::getTable(string `$name`): mysql_xdevapi\Table

Fetch a Table object for the provided table in the schema.

### Parameters

`name`

  Name of the table.

### Return Values

A Table object.

### Examples

Example #1 mysql_xdevapi\Schema::getTable() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$row = $table->select('name', 'age')->execute()->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 33
            )
    )

# Schema::getTables

(No version information available, might only be in Git)

Schema::getTables — Get schema tables

### Description

public mysql_xdevapi\Schema::getTables(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Array of all tables in this schema, where each array element value is a Table object with the table name as the key.

### Examples

Example #1 mysql_xdevapi\Schema::getTables() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$session->sql("CREATE TABLE addressbook.cities(name text, population int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Portland', 639863), ('Seattle', 704352)")->execute();
$schema = $session->getSchema("addressbook");
$tables = $schema->getTables();
var_dump($tables);
?>`

The above example will output something similar to:

    array(2) {
      ["cities"]=>
      object(mysql_xdevapi\Table)#3 (1) {
        ["name"]=>
        string(6) "cities"
      }

      ["names"]=>
      object(mysql_xdevapi\Table)#4 (1) {
        ["name"]=>
        string(5) "names"
      }
    }

## Table of Contents

- Schema::__construct — Schema constructor
- Schema::createCollection — Add collection to schema
- Schema::dropCollection — Drop collection from schema
- Schema::existsInDatabase — Check if exists in database
- Schema::getCollection — Get collection from schema
- Schema::getCollectionAsTable — Get collection as a Table object
- Schema::getCollections — Get all schema collections
- Schema::getName — Get schema name
- Schema::getSession — Get schema session
- Schema::getTable — Get schema table
- Schema::getTables — Get schema tables

# SchemaObject interface

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\SchemaObject implements mysql_xdevapi\DatabaseObject {
/* Methods */
abstract getSchema(): mysql_xdevapi\Schema
}

# SchemaObject::getSchema

(No version information available, might only be in Git)

SchemaObject::getSchema — Get schema object

### Description

abstract mysql_xdevapi\SchemaObject::getSchema(): mysql_xdevapi\Schema

Used by other objects to retrieve a schema object.

### Parameters

This function has no parameters.

### Return Values

The current Schema object.

### Examples

Example #1 mysql_xdevapi\Session::getSchema() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
print_r($schema);`

The above example will output something similar to:

    mysql_xdevapi\Schema Object
    (
        [name] => addressbook
    )

## Table of Contents

- SchemaObject::getSchema — Get schema object

# Session class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Session {
/* Methods */
public close(): bool
public commit(): Object
public createSchema(string `$schema_name`): mysql_xdevapi\Schema
public dropSchema(string `$schema_name`): bool
public generateUUID(): string
public getDefaultSchema(): ?mysql_xdevapi\Schema
public getSchema(string `$schema_name`): mysql_xdevapi\Schema
public getSchemas(): array
public getServerVersion(): int
public listClients(): array
public quoteName(string `$name`): string
public releaseSavepoint(string `$name`): void
public rollback(): void
public rollbackTo(string `$name`): void
public setSavepoint(string `$name` = ?): string
public sql(string `$query`): mysql_xdevapi\SqlStatement
public startTransaction(): void
}

# Session::close

(No version information available, might only be in Git)

Session::close — Close session

### Description

public mysql_xdevapi\Session::close(): bool

Close the session with the server.

### Parameters

This function has no parameters.

### Return Values

`true` if the session closed.

### Examples

Example #1 mysql_xdevapi\Session::close() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$session->close();`

# Session::commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7, PHP 8)

Session::commit — Commit transaction

### Description

public mysql_xdevapi\Session::commit(): Object

Commit the transaction.

### Parameters

This function has no parameters.

### Return Values

An SqlStatementResult object.

### Examples

Example #1 mysql_xdevapi\Session::commit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");
$session->startTransaction();
$collection->add('{"John":42, "Sam":33}')->execute();
$savepoint = $session->setSavepoint();
$session->commit();
$session->close();`

# Session::__construct

(No version information available, might only be in Git)

Session::__construct — Description constructor

### Description

private mysql_xdevapi\Session::__construct()

A Session object, as initiated by getSession().

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Session::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->close();
?>`

# Session::createSchema

(No version information available, might only be in Git)

Session::createSchema — Create new schema

### Description

public mysql_xdevapi\Session::createSchema(string `$schema_name`): mysql_xdevapi\Schema

Creates a new schema.

### Parameters

`schema_name`

  Name of the schema to create.

### Return Values

A Schema object on success, and emits an exception on failure.

### Examples

Example #1 mysql_xdevapi\Session::createSchema() example

`<?php
$uri = 'mysqlx://happyuser:password@127.0.0.1:33060/';
$sess = mysql_xdevapi\getSession($uri);
try {
if ($schema = $sess->createSchema('fruit')) {
echo "Info: I created a schema named 'fruit'\n";
}
} catch (Exception $e) {
echo $e->getMessage();
}
?>`

The above example will output something similar to:

    Info: I created a schema named 'fruit'

# Session::dropSchema

(No version information available, might only be in Git)

Session::dropSchema — Drop a schema

### Description

public mysql_xdevapi\Session::dropSchema(string `$schema_name`): bool

Drop a schema (database).

### Parameters

`schema_name`

  Name of the schema to drop.

### Return Values

`true` if the schema is dropped, or `false` if it does not exist or can't be dropped.

An `E_WARNING` level error is generated if the schema does not exist.

### Examples

Example #1 mysql_xdevapi\Session::dropSchema() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->dropSchema("addressbook");
$session->close();
?>`

# Session::generateUUID

(No version information available, might only be in Git)

Session::generateUUID — Get new UUID

### Description

public mysql_xdevapi\Session::generateUUID(): string

Generate a Universal Unique IDentifier (UUID) generated according to » RFC 4122.

### Parameters

This function has no parameters.

### Return Values

The UUID; a string with a length of 32.

### Examples

Example #1 mysql_xdevapi\Session::generateUuid() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$uuid = $session->generateUuid();
var_dump($uuid);`

The above example will output something similar to:

    string(32) "484B18AC7980F8D4FE84613CDA5EE84B"

# Session::getDefaultSchema

(No version information available, might only be in Git)

Session::getDefaultSchema — Get default schema name

### Description

public mysql_xdevapi\Session::getDefaultSchema(): ?mysql_xdevapi\Schema

Retrieve the default schema that's typically set in the connection URI.

### Parameters

This function has no parameters.

### Return Values

The default schema defined by the connection, or `null` if one was not set.

### Examples

Example #1 mysql_xdevapi\Session::getSchema() example

`<?php
$uri = "mysqlx://testuser:testpasswd@localhost:33160/testx?ssl-mode=disabled";
$session = mysql_xdevapi\getSession($uri);
$schema = $session->getDefaultSchema();
echo $schema->getName();
?>`

The above example will output:

    testx

# Session::getSchema

(No version information available, might only be in Git)

Session::getSchema — Get a new schema object

### Description

public mysql_xdevapi\Session::getSchema(string `$schema_name`): mysql_xdevapi\Schema

A new Schema object for the provided schema name.

### Parameters

`schema_name`

  Name of the schema (database) to fetch a Schema object for.

### Return Values

A Schema object.

### Examples

Example #1 mysql_xdevapi\Session::getSchema() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
print_r($schema);`

The above example will output something similar to:

    mysql_xdevapi\Schema Object
    (
        [name] => addressbook
    )

# Session::getSchemas

(No version information available, might only be in Git)

Session::getSchemas — Get the schemas

### Description

public mysql_xdevapi\Session::getSchemas(): array

Get schema objects for all schemas available to the session.

### Parameters

This function has no parameters.

### Return Values

An array containing objects that represent all of the schemas available to the session.

### Examples

Example #1 mysql_xdevapi\Session::getSchemas() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schemas = $session->getSchemas();
print_r($schemas);`

The above example will output something similar to:

    Array
    (
        [0] => mysql_xdevapi\Schema Object
            (
                [name] => addressbook
            )
        [1] => mysql_xdevapi\Schema Object
            (
                [name] => information_schema
            )
        ...

# Session::getServerVersion

(No version information available, might only be in Git)

Session::getServerVersion — Get server version

### Description

public mysql_xdevapi\Session::getServerVersion(): int

Retrieve the MySQL server version for the session.

### Parameters

This function has no parameters.

### Return Values

The MySQL server version for the session, as an integer such as "80012".

### Examples

Example #1 mysql_xdevapi\Session::getServerVersion() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$version = $session->getServerVersion();
var_dump($version);`

The above example will output something similar to:

    int(80012)

# Session::listClients

(No version information available, might only be in Git)

Session::listClients — Get client list

### Description

public mysql_xdevapi\Session::listClients(): array

Get a list of client connections to the session's MySQL server.

### Parameters

This function has no parameters.

### Return Values

An array containing the currently logged clients. The array elements are "client_id", "user", "host", and "sql_session".

### Examples

Example #1 mysql_xdevapi\Session::listClients() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$ids = $session->listClients();
var_dump($ids);
?>`

The above example will output something similar to:

    array(1) {
      [0]=>
      array(4) {
        ["client_id"]=>
        int(61)
        ["user"]=>
        string(4) "root"
        ["host"]=>
        string(9) "localhost"
        ["sql_session"]=>
        int(72)
      }
    }

# Session::quoteName

(No version information available, might only be in Git)

Session::quoteName — Add quotes

### Description

public mysql_xdevapi\Session::quoteName(string `$name`): string

A quoting function to escape SQL names and identifiers. It escapes the identifier given in accordance to the settings of the current connection. This escape function should not be used to escape values.

### Parameters

`name`

  The string to quote.

### Return Values

The quoted string.

### Examples

Example #1 mysql_xdevapi\Session::quoteName() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$first = "MySQL's test";
var_dump($first);
var_dump($session->quoteName($first));
$second = 'Another `test` "like" `this`';
var_dump($second);
var_dump($session->quoteName($second));
?>`

The above example will output something similar to:

    string(12) "MySQL's test"
    string(14) "`MySQL's test`"

    string(28) "Another `test` "like" `this`"
    string(34) "`Another ``test`` "like" ``this```"

# Session::releaseSavepoint

(No version information available, might only be in Git)

Session::releaseSavepoint — Release set savepoint

### Description

public mysql_xdevapi\Session::releaseSavepoint(string `$name`): void

Release a previously set savepoint.

### Parameters

`name`

  Name of the savepoint to release.

### Return Values

An SqlStatementResult object.

### Examples

Example #1 mysql_xdevapi\Session::releaseSavepoint() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");
$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();
$savepoint = $session->setSavepoint();
$collection->add( '{"test3":3, "test4":4}' )->execute();
$session->releaseSavepoint($savepoint);
$session->rollback();
?>`

# Session::rollback

(No version information available, might only be in Git)

Session::rollback — Rollback transaction

### Description

public mysql_xdevapi\Session::rollback(): void

Rollback the transaction.

### Parameters

This function has no parameters.

### Return Values

An SqlStatementResult object.

### Examples

Example #1 mysql_xdevapi\Session::rollback() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");
$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();
$savepoint = $session->setSavepoint();
$collection->add( '{"test3":3, "test4":4}' )->execute();
$session->releaseSavepoint($savepoint);
$session->rollback();
?>`

# Session::rollbackTo

(No version information available, might only be in Git)

Session::rollbackTo — Rollback transaction to savepoint

### Description

public mysql_xdevapi\Session::rollbackTo(string `$name`): void

Rollback the transaction back to the savepoint.

### Parameters

`name`

  Name of the savepoint to rollback to; case-insensitive.

### Return Values

An SqlStatementResult object.

### Examples

Example #1 mysql_xdevapi\Session::rollbackTo() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");
$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();
$savepoint1 = $session->setSavepoint();
$collection->add( '{"test3":3, "test4":4}' )->execute();
$savepoint2 = $session->setSavepoint();
$session->rollbackTo($savepoint1);
?>`

# Session::setSavepoint

(No version information available, might only be in Git)

Session::setSavepoint — Create savepoint

### Description

public mysql_xdevapi\Session::setSavepoint(string `$name` = ?): string

Create a new savepoint for the transaction.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`name`

  The name of the savepoint. The name is auto-generated if the optional `name` parameter is not defined as 'SAVEPOINT1', 'SAVEPOINT2', and so on.

### Return Values

The name of the save point.

### Examples

Example #1 mysql_xdevapi\Session::setSavepoint() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");
$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();
$savepoint = $session->setSavepoint();
$collection->add( '{"test3":3, "test4":4}' )->execute();
$session->releaseSavepoint($savepoint);
$session->rollback();
?>`

# Session::sql

(No version information available, might only be in Git)

Session::sql — Create SQL query

### Description

public mysql_xdevapi\Session::sql(string `$query`): mysql_xdevapi\SqlStatement

Create a native SQL statement. Placeholders are supported using the native "?" syntax. Use the `execute` method to execute the SQL statement.

### Parameters

`query`

  SQL statement to execute.

### Return Values

An SqlStatement object.

### Examples

Example #1 mysql_xdevapi\Session::sql() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("CREATE DATABASE addressbook")->execute();
?>`

# Session::startTransaction

(No version information available, might only be in Git)

Session::startTransaction — Start transaction

### Description

public mysql_xdevapi\Session::startTransaction(): void

Start a new transaction.

### Parameters

This function has no parameters.

### Return Values

An SqlStatementResult object.

### Examples

Example #1 mysql_xdevapi\Session::startTransaction() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");
$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();
$savepoint = $session->setSavepoint();
$collection->add( '{"test3":3, "test4":4}' )->execute();
$session->releaseSavepoint($savepoint);
$session->rollback();
?>`

## Table of Contents

- Session::close — Close session
- Session::commit — Commit transaction
- Session::__construct — Description constructor
- Session::createSchema — Create new schema
- Session::dropSchema — Drop a schema
- Session::generateUUID — Get new UUID
- Session::getDefaultSchema — Get default schema name
- Session::getSchema — Get a new schema object
- Session::getSchemas — Get the schemas
- Session::getServerVersion — Get server version
- Session::listClients — Get client list
- Session::quoteName — Add quotes
- Session::releaseSavepoint — Release set savepoint
- Session::rollback — Rollback transaction
- Session::rollbackTo — Rollback transaction to savepoint
- Session::setSavepoint — Create savepoint
- Session::sql — Create SQL query
- Session::startTransaction — Start transaction

# SqlStatement class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\SqlStatement {
/* Constants */
const int EXECUTE_ASYNC = 1;
const int BUFFERED = 2;
/* Properties */
public $statement;
/* Methods */
public bind(string `$param`): mysql_xdevapi\SqlStatement
public execute(): mysql_xdevapi\Result
public getNextResult(): mysql_xdevapi\Result
public getResult(): mysql_xdevapi\Result
public hasMoreResults(): bool
}

## Properties

statement

## Predefined Constants

`mysql_xdevapi\SqlStatement::EXECUTE_ASYNC`

`mysql_xdevapi\SqlStatement::BUFFERED`

# SqlStatement::bind

(No version information available, might only be in Git)

SqlStatement::bind — Bind statement parameters

### Description

public mysql_xdevapi\SqlStatement::bind(string `$param`): mysql_xdevapi\SqlStatement

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`param`

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatement::bind() example

`<?php
/* ... */
?>`

# SqlStatement::__construct

(No version information available, might only be in Git)

SqlStatement::__construct — Description constructor

### Description

private mysql_xdevapi\SqlStatement::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\SqlStatement::__construct() example

`<?php
/* ... */
?>`

# SqlStatement::execute

(No version information available, might only be in Git)

SqlStatement::execute — Execute the operation

### Description

public mysql_xdevapi\SqlStatement::execute(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatement::execute() example

`<?php
/* ... */
?>`

# SqlStatement::getNextResult

(No version information available, might only be in Git)

SqlStatement::getNextResult — Get next result

### Description

public mysql_xdevapi\SqlStatement::getNextResult(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatement::getNextResult() example

`<?php
/* ... */
?>`

# SqlStatement::getResult

(No version information available, might only be in Git)

SqlStatement::getResult — Get result

### Description

public mysql_xdevapi\SqlStatement::getResult(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatement::getResult() example

`<?php
/* ... */
?>`

# SqlStatement::hasMoreResults

(No version information available, might only be in Git)

SqlStatement::hasMoreResults — Check for more results

### Description

public mysql_xdevapi\SqlStatement::hasMoreResults(): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

`true` if the result set has more objects to fetch.

### Examples

Example #1 mysql_xdevapi\SqlStatement::hasMoreResults() example

`<?php
/* ... */
?>`

## Table of Contents

- SqlStatement::bind — Bind statement parameters
- SqlStatement::__construct — Description constructor
- SqlStatement::execute — Execute the operation
- SqlStatement::getNextResult — Get next result
- SqlStatement::getResult — Get result
- SqlStatement::hasMoreResults — Check for more results

# SqlStatementResult class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\SqlStatementResult implements mysql_xdevapi\BaseResult, Traversable {
/* Methods */
public fetchAll(): array
public fetchOne(): array
public getAffectedItemsCount(): int
public getColumnsCount(): int
public getColumnNames(): array
public getColumns(): Array
public getGeneratedIds(): array
public getLastInsertId(): String
public getWarnings(): array
public getWarningCounts(): int
public hasData(): bool
public nextResult(): mysql_xdevapi\Result
}

# SqlStatementResult::__construct

(No version information available, might only be in Git)

SqlStatementResult::__construct — Description constructor

### Description

private mysql_xdevapi\SqlStatementResult::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::__construct() example

`<?php
/* ... */
?>`

# SqlStatementResult::fetchAll

(No version information available, might only be in Git)

SqlStatementResult::fetchAll — Get all rows from result

### Description

public mysql_xdevapi\SqlStatementResult::fetchAll(): array

Fetch all the rows from the result set.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::fetchAll() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS dbtest")->execute();
$session->sql("CREATE DATABASE dbtest")->execute();
$session->sql("CREATE TABLE dbtest.workers(name text, age int, job text)")->execute();
$session->sql("INSERT INTO dbtest.workers values ('John', 42, 'bricklayer'), ('Sam', 33, 'carpenter')")->execute();
$schema = $session->getSchema("dbtest");
$table = $schema->getTable("workers");
$rows = $session->sql("SELECT * FROM dbtest.workers")->execute()->fetchAll();
print_r($rows);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 33
            )
    )

# SqlStatementResult::fetchOne

(No version information available, might only be in Git)

SqlStatementResult::fetchOne — Get single row

### Description

public mysql_xdevapi\SqlStatementResult::fetchOne(): array

Fetch one row from the result set.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The result, as an associative array. In case there is not any result, null will be returned.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::fetchOne() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS dbtest")->execute();
$session->sql("CREATE DATABASE dbtest")->execute();
$session->sql("CREATE TABLE dbtest.workers(name text, age int, job text)")->execute();
$session->sql("INSERT INTO dbtest.workers values ('John', 42, 'bricklayer'), ('Sam', 33, 'carpenter')")->execute();
$schema = $session->getSchema("dbtest");
$table = $schema->getTable("workers");
$rows = $session->sql("SELECT * FROM dbtest.workers")->execute()->fetchOne();
print_r($rows);
?>`

The above example will output something similar to:

    Array
    (
        [name] => John
        [age] => 42
        [job] => bricklayer
    )

# SqlStatementResult::getAffectedItemsCount

(No version information available, might only be in Git)

SqlStatementResult::getAffectedItemsCount — Get affected row count

### Description

public mysql_xdevapi\SqlStatementResult::getAffectedItemsCount(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getAffectedItemsCount() example

`<?php
/* ... */
?>`

# SqlStatementResult::getColumnsCount

(No version information available, might only be in Git)

SqlStatementResult::getColumnsCount — Get column count

### Description

public mysql_xdevapi\SqlStatementResult::getColumnsCount(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The number of columns; 0 if there are none.

### Changelog

Version | Description
--- | ---
8.0.14 | Method renamed from getColumnCount() to getColumnsCount().

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getColumnsCount() example

`<?php
/* ... */
?>`

# SqlStatementResult::getColumnNames

(No version information available, might only be in Git)

SqlStatementResult::getColumnNames — Get column names

### Description

public mysql_xdevapi\SqlStatementResult::getColumnNames(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getColumnNames() example

`<?php
/* ... */
?>`

# SqlStatementResult::getColumns

(No version information available, might only be in Git)

SqlStatementResult::getColumns — Get columns

### Description

public mysql_xdevapi\SqlStatementResult::getColumns(): Array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getColumns() example

`<?php
/* ... */
?>`

# SqlStatementResult::getGeneratedIds

(No version information available, might only be in Git)

SqlStatementResult::getGeneratedIds — Get generated ids

### Description

public mysql_xdevapi\SqlStatementResult::getGeneratedIds(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

An array of generated _id's from the last operation, or an empty array if there are none.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getGeneratedIds() example

`<?php
/* ... */
?>`

# SqlStatementResult::getLastInsertId

(No version information available, might only be in Git)

SqlStatementResult::getLastInsertId — Get last insert id

### Description

public mysql_xdevapi\SqlStatementResult::getLastInsertId(): String

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The ID for the last insert operation.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getLastInsertId() example

`<?php
/* ... */
?>`

# SqlStatementResult::getWarnings

(No version information available, might only be in Git)

SqlStatementResult::getWarnings — Get warnings from last operation

### Description

public mysql_xdevapi\SqlStatementResult::getWarnings(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getWarnings() example

`<?php
/* ... */
?>`

# SqlStatementResult::getWarningsCount

(No version information available, might only be in Git)

SqlStatementResult::getWarningsCount — Get warning count from last operation

### Description

public mysql_xdevapi\SqlStatementResult::getWarningCounts(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The number of warnings raised during the last CRUD operation.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::getWarningsCount() example

`<?php
/* ... */
?>`

# SqlStatementResult::hasData

(No version information available, might only be in Git)

SqlStatementResult::hasData — Check if result has data

### Description

public mysql_xdevapi\SqlStatementResult::hasData(): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

`true` if the result set has data.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::hasData() example

`<?php
/* ... */
?>`

# SqlStatementResult::nextResult

(No version information available, might only be in Git)

SqlStatementResult::nextResult — Get next result

### Description

public mysql_xdevapi\SqlStatementResult::nextResult(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

The next Result object from the result set.

### Examples

Example #1 mysql_xdevapi\SqlStatementResult::nextResult() example

`<?php
/* ... */
?>`

## Table of Contents

- SqlStatementResult::__construct — Description constructor
- SqlStatementResult::fetchAll — Get all rows from result
- SqlStatementResult::fetchOne — Get single row
- SqlStatementResult::getAffectedItemsCount — Get affected row count
- SqlStatementResult::getColumnsCount — Get column count
- SqlStatementResult::getColumnNames — Get column names
- SqlStatementResult::getColumns — Get columns
- SqlStatementResult::getGeneratedIds — Get generated ids
- SqlStatementResult::getLastInsertId — Get last insert id
- SqlStatementResult::getWarnings — Get warnings from last operation
- SqlStatementResult::getWarningsCount — Get warning count from last operation
- SqlStatementResult::hasData — Check if result has data
- SqlStatementResult::nextResult — Get next result

# Statement class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Statement {
/* Constants */
const int EXECUTE_ASYNC = 1;
const int BUFFERED = 2;
/* Methods */
public getNextResult(): mysql_xdevapi\Result
public getResult(): mysql_xdevapi\Result
public hasMoreResults(): bool
}

## Predefined Constants

`mysql_xdevapi\Statement::EXECUTE_ASYNC`

`mysql_xdevapi\Statement::BUFFERED`

# Statement::__construct

(No version information available, might only be in Git)

Statement::__construct — Description constructor

### Description

private mysql_xdevapi\Statement::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Statement::__construct() example

`<?php
/* ... */
?>`

# Statement::getNextResult

(No version information available, might only be in Git)

Statement::getNextResult — Get next result

### Description

public mysql_xdevapi\Statement::getNextResult(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\Statement::getNextResult() example

`<?php
/* ... */
?>`

# Statement::getResult

(No version information available, might only be in Git)

Statement::getResult — Get result

### Description

public mysql_xdevapi\Statement::getResult(): mysql_xdevapi\Result

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\Statement::getResult() example

`<?php
/* ... */
?>`

# Statement::hasMoreResults

(No version information available, might only be in Git)

Statement::hasMoreResults — Check if more results

### Description

public mysql_xdevapi\Statement::hasMoreResults(): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 mysql_xdevapi\Statement::hasMoreResults() example

`<?php
/* ... */
?>`

## Table of Contents

- Statement::__construct — Description constructor
- Statement::getNextResult — Get next result
- Statement::getResult — Get result
- Statement::hasMoreResults — Check if more results

# Table class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

Provides access to the table through INSERT/SELECT/UPDATE/DELETE statements.

## Class synopsis

class mysql_xdevapi\Table implements mysql_xdevapi\SchemaObject {
/* Properties */
public $name;
/* Methods */
public count(): int
public delete(): mysql_xdevapi\TableDelete
public existsInDatabase(): bool
public getName(): string
public getSchema(): mysql_xdevapi\Schema
public getSession(): mysql_xdevapi\Session
public insert(mixed `$columns`, mixed `...$more_columns`): mysql_xdevapi\TableInsert
public isView(): bool
public select(mixed `$columns`, mixed `...$more_columns`): mysql_xdevapi\TableSelect
public update(): mysql_xdevapi\TableUpdate
}

## Properties

name

# Table::__construct

(No version information available, might only be in Git)

Table::__construct — Table constructor

### Description

private mysql_xdevapi\Table::__construct()

Construct a table object.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Table::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
?>`

# Table::count

(No version information available, might only be in Git)

Table::count — Get row count

### Description

public mysql_xdevapi\Table::count(): int

Fetch the number of rows in the table.

### Parameters

This function has no parameters.

### Return Values

The total number of rows in the table.

### Examples

Example #1 mysql_xdevapi\Table::count() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
var_dump($table->count());
?>`

The above example will output:

    int(2)

# Table::delete

(No version information available, might only be in Git)

Table::delete — Delete rows from table

### Description

public mysql_xdevapi\Table::delete(): mysql_xdevapi\TableDelete

Deletes rows from a table.

### Parameters

This function has no parameters.

### Return Values

A TableDelete object; use the execute() method to execute the delete query.

### Examples

Example #1 mysql_xdevapi\Table::delete() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()->where("name = :name")->orderby("age DESC")->limit(1)->bind(['name' => 'John'])->execute();
?>`

# Table::existsInDatabase

(No version information available, might only be in Git)

Table::existsInDatabase — Check if table exists in database

### Description

public mysql_xdevapi\Table::existsInDatabase(): bool

Verifies if this table exists in the database.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if table exists in the database, else `false` if it does not.

### Examples

Example #1 mysql_xdevapi\Table::existsInDatabase() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
if ($table->existsInDatabase()) {
echo "Yes, this table still exists in the session's schema.";
}
?>`

The above example will output something similar to:

    Yes, this table still exists in the session's schema.

# Table::getName

(No version information available, might only be in Git)

Table::getName — Get table name

### Description

public mysql_xdevapi\Table::getName(): string

Returns the name of this database object.

### Parameters

This function has no parameters.

### Return Values

The name of this database object.

### Examples

Example #1 mysql_xdevapi\Table::getName() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
var_dump($table->getName());
?>`

The above example will output something similar to:

    string(5) "names"

# Table::getSchema

(No version information available, might only be in Git)

Table::getSchema — Get table schema

### Description

public mysql_xdevapi\Table::getSchema(): mysql_xdevapi\Schema

Fetch the schema associated with the table.

### Parameters

This function has no parameters.

### Return Values

A Schema object.

### Examples

Example #1 mysql_xdevapi\Table::getSchema() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
var_dump($table->getSchema());
?>`

The above example will output something similar to:

    object(mysql_xdevapi\Schema)#9 (1) {
      ["name"]=>
      string(11) "addressbook"
    }

# Table::getSession

(No version information available, might only be in Git)

Table::getSession — Get table session

### Description

public mysql_xdevapi\Table::getSession(): mysql_xdevapi\Session

Get session associated with the table.

### Parameters

This function has no parameters.

### Return Values

A Session object.

### Examples

Example #1 mysql_xdevapi\Table::getSession() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
var_dump($table->getSession());
?>`

The above example will output something similar to:

    object(mysql_xdevapi\Session)#9 (0) {
    }

# Table::insert

(No version information available, might only be in Git)

Table::insert — Insert table rows

### Description

public mysql_xdevapi\Table::insert(mixed `$columns`, mixed `...$more_columns`): mysql_xdevapi\TableInsert

Inserts rows into a table.

### Parameters

`columns`

  The columns to insert data into. Can be an array with one or more values, or a string.

`more_columns`

  Additional columns definitions.

### Return Values

A TableInsert object; use the execute() method to execute the insert statement.

### Examples

Example #1 mysql_xdevapi\Table::insert() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table ->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>`

# Table::isView

(No version information available, might only be in Git)

Table::isView — Check if table is view

### Description

public mysql_xdevapi\Table::isView(): bool

Determine if the underlying object is a view or not.

### Parameters

This function has no parameters.

### Return Values

`true` if the underlying object is a view, otherwise `false`.

### Examples

Example #1 mysql_xdevapi\Table::isView() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
if ($table->isView()) {
echo "This is a view.";
} else {
echo "This is not a view.";
}
?>`

The above example will output:

    This is not a view.

# Table::select

(No version information available, might only be in Git)

Table::select — Select rows from table

### Description

public mysql_xdevapi\Table::select(mixed `$columns`, mixed `...$more_columns`): mysql_xdevapi\TableSelect

Fetches data from a table.

### Parameters

`columns`

  The columns to select data from. Can be an array with one or more values, or a string.

`more_columns`

  Additional columns parameter definitions.

### Return Values

A TableSelect object; use the execute() method to execute the select and return a RowResult object.

### Examples

Example #1 mysql_xdevapi\Table::count() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$row = $table->select('name', 'age')->execute()->fetchAll();
print_r($row);`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 33
            )
    )

# Table::update

(No version information available, might only be in Git)

Table::update — Update rows in table

### Description

public mysql_xdevapi\Table::update(): mysql_xdevapi\TableUpdate

Updates columns in a table.

### Parameters

This function has no parameters.

### Return Values

A TableUpdate object; use the execute() method to execute the update statement.

### Examples

Example #1 mysql_xdevapi\Table::update() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->update()->set('age',34)->where('name = "Sam"')->limit(1)->execute();
?>`

## Table of Contents

- Table::__construct — Table constructor
- Table::count — Get row count
- Table::delete — Delete rows from table
- Table::existsInDatabase — Check if table exists in database
- Table::getName — Get table name
- Table::getSchema — Get table schema
- Table::getSession — Get table session
- Table::insert — Insert table rows
- Table::isView — Check if table is view
- Table::select — Select rows from table
- Table::update — Update rows in table

# TableDelete class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

A statement for delete operations on Table.

## Class synopsis

class mysql_xdevapi\TableDelete implements mysql_xdevapi\Executable {
/* Methods */
public bind(array `$placeholder_values`): mysql_xdevapi\TableDelete
public execute(): mysql_xdevapi\Result
public limit(int `$rows`): mysql_xdevapi\TableDelete
public orderby(string `$orderby_expr`): mysql_xdevapi\TableDelete
public where(string `$where_expr`): mysql_xdevapi\TableDelete
}

# TableDelete::bind

(No version information available, might only be in Git)

TableDelete::bind — Bind delete query parameters

### Description

public mysql_xdevapi\TableDelete::bind(array `$placeholder_values`): mysql_xdevapi\TableDelete

Binds a value to a specific placeholder.

### Parameters

`placeholder_values`

  The name of the placeholder and the value to bind.

### Return Values

A TableDelete object.

### Examples

Example #1 mysql_xdevapi\TableDelete::bind() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();
?>`

# TableDelete::__construct

(No version information available, might only be in Git)

TableDelete::__construct — TableDelete constructor

### Description

private mysql_xdevapi\TableDelete::__construct()

Initiated by using the delete() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\TableDelete::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();
?>`

# TableDelete::execute

(No version information available, might only be in Git)

TableDelete::execute — Execute delete query

### Description

public mysql_xdevapi\TableDelete::execute(): mysql_xdevapi\Result

Execute the delete query.

### Parameters

This function has no parameters.

### Return Values

A Result object.

### Examples

Example #1 mysql_xdevapi\TableDelete::execute() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();
?>`

# TableDelete::limit

(No version information available, might only be in Git)

TableDelete::limit — Limit deleted rows

### Description

public mysql_xdevapi\TableDelete::limit(int `$rows`): mysql_xdevapi\TableDelete

Sets the maximum number of records or documents to delete.

### Parameters

`rows`

  The maximum number of records or documents to delete.

### Return Values

TableDelete object.

### Examples

Example #1 mysql_xdevapi\TableDelete::limit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();
?>`

# TableDelete::orderby

(No version information available, might only be in Git)

TableDelete::orderby — Set delete sort criteria

### Description

public mysql_xdevapi\TableDelete::orderby(string `$orderby_expr`): mysql_xdevapi\TableDelete

Set the order options for a result set.

### Parameters

`orderby_expr`

  The sort definition.

### Return Values

A TableDelete object.

### Examples

Example #1 mysql_xdevapi\TableDelete::orderBy() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("age = :age")
->bind(['age' => 42])
->orderby("name DESC")
->limit(1)
->execute();
?>`

# TableDelete::where

(No version information available, might only be in Git)

TableDelete::where — Set delete search condition

### Description

public mysql_xdevapi\TableDelete::where(string `$where_expr`): mysql_xdevapi\TableDelete

Sets the search condition to filter.

### Parameters

`where_expr`

  Define the search condition to filter documents or records.

### Return Values

TableDelete object.

### Examples

Example #1 mysql_xdevapi\TableDelete::where() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->delete()
->where("id = :id")
->bind(['id' => 42])
->limit(1)
->execute();
?>`

## Table of Contents

- TableDelete::bind — Bind delete query parameters
- TableDelete::__construct — TableDelete constructor
- TableDelete::execute — Execute delete query
- TableDelete::limit — Limit deleted rows
- TableDelete::orderby — Set delete sort criteria
- TableDelete::where — Set delete search condition

# TableInsert class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

A statement for insert operations on Table.

## Class synopsis

class mysql_xdevapi\TableInsert implements mysql_xdevapi\Executable {
/* Methods */
public execute(): mysql_xdevapi\Result
public values(array `$row_values`): mysql_xdevapi\TableInsert
}

# TableInsert::__construct

(No version information available, might only be in Git)

TableInsert::__construct — TableInsert constructor

### Description

private mysql_xdevapi\TableInsert::__construct()

Initiated by using the insert() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\TableInsert::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>`

# TableInsert::execute

(No version information available, might only be in Git)

TableInsert::execute — Execute insert query

### Description

public mysql_xdevapi\TableInsert::execute(): mysql_xdevapi\Result

Execute the statement.

### Parameters

This function has no parameters.

### Return Values

A Result object.

### Examples

Example #1 mysql_xdevapi\TableInsert::execute() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>`

# TableInsert::values

(No version information available, might only be in Git)

TableInsert::values — Add insert row values

### Description

public mysql_xdevapi\TableInsert::values(array `$row_values`): mysql_xdevapi\TableInsert

Set the values to be inserted.

### Parameters

`row_values`

  Values (an array) of columns to insert.

### Return Values

A TableInsert object.

### Examples

Example #1 mysql_xdevapi\TableInsert::values() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>`

## Table of Contents

- TableInsert::__construct — TableInsert constructor
- TableInsert::execute — Execute insert query
- TableInsert::values — Add insert row values

# TableSelect class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

A statement for record retrieval operations on a Table.

## Class synopsis

class mysql_xdevapi\TableSelect implements mysql_xdevapi\Executable {
/* Methods */
public bind(array `$placeholder_values`): mysql_xdevapi\TableSelect
public execute(): mysql_xdevapi\RowResult
public groupBy(mixed `$sort_expr`): mysql_xdevapi\TableSelect
public having(string `$sort_expr`): mysql_xdevapi\TableSelect
public limit(int `$rows`): mysql_xdevapi\TableSelect
public lockExclusive(int `$lock_waiting_option` = ?): mysql_xdevapi\TableSelect
public lockShared(int `$lock_waiting_option` = ?): mysql_xdevapi\TableSelect
public offset(int `$position`): mysql_xdevapi\TableSelect
public orderby(mixed `$sort_expr`, mixed `...$sort_exprs`): mysql_xdevapi\TableSelect
public where(string `$where_expr`): mysql_xdevapi\TableSelect
}

# TableSelect::bind

(No version information available, might only be in Git)

TableSelect::bind — Bind select query parameters

### Description

public mysql_xdevapi\TableSelect::bind(array `$placeholder_values`): mysql_xdevapi\TableSelect

Binds a value to a specific placeholder.

### Parameters

`placeholder_values`

  The name of the placeholder, and the value to bind.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::bind() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
    )

# TableSelect::__construct

(No version information available, might only be in Git)

TableSelect::__construct — TableSelect constructor

### Description

private mysql_xdevapi\TableSelect::__construct()

An object returned by the select() method; use execute() to execute the query.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\TableSelect::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->orderBy('age desc')
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
    )

# TableSelect::execute

(No version information available, might only be in Git)

TableSelect::execute — Execute select statement

### Description

public mysql_xdevapi\TableSelect::execute(): mysql_xdevapi\RowResult

Execute the select statement by chaining it with the execute() method.

### Parameters

This function has no parameters.

### Return Values

A RowResult object.

### Examples

Example #1 mysql_xdevapi\TableSelect::execute() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->orderBy('age desc')
->execute();
$row = $result->fetchAll();
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
    )

# TableSelect::groupBy

(No version information available, might only be in Git)

TableSelect::groupBy — Set select grouping criteria

### Description

public mysql_xdevapi\TableSelect::groupBy(mixed `$sort_expr`): mysql_xdevapi\TableSelect

Sets a grouping criteria for the result set.

### Parameters

`sort_expr`

  The grouping criteria.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::groupBy() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Suki', 31)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('count(*) as count', 'age')
->groupBy('age')->orderBy('age asc')
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [count] => 1
                [age] => 31
            )
        [1] => Array
            (
                [count] => 2
                [age] => 42
            )
    )

# TableSelect::having

(No version information available, might only be in Git)

TableSelect::having — Set select having condition

### Description

public mysql_xdevapi\TableSelect::having(string `$sort_expr`): mysql_xdevapi\TableSelect

Sets a condition for records to consider in aggregate function operations.

### Parameters

`sort_expr`

  A condition on the aggregate functions used on the grouping criteria.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::having() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Suki', 31)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('count(*) as count', 'age')
->groupBy('age')->orderBy('age asc')
->having('count > 1')
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [count] => 2
                [age] => 42
            )
    )

# TableSelect::limit

(No version information available, might only be in Git)

TableSelect::limit — Limit selected rows

### Description

public mysql_xdevapi\TableSelect::limit(int `$rows`): mysql_xdevapi\TableSelect

Sets the maximum number of records or documents to return.

### Parameters

`rows`

  The maximum number of records or documents.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::limit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name', 'age')
->limit(1)
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
    )

# TableSelect::lockExclusive

(No version information available, might only be in Git)

TableSelect::lockExclusive — Execute EXCLUSIVE LOCK

### Description

public mysql_xdevapi\TableSelect::lockExclusive(int `$lock_waiting_option` = ?): mysql_xdevapi\TableSelect

Execute a read operation with EXCLUSIVE LOCK. Only one lock can be active at a time.

### Parameters

`lock_waiting_option`

  The optional waiting option that defaults to `MYSQLX_LOCK_DEFAULT`. Valid values are:

  - `MYSQLX_LOCK_DEFAULT`

  - `MYSQLX_LOCK_NOWAIT`

  - `MYSQLX_LOCK_SKIP_LOCKED`

### Return Values

TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::lockExclusive() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$session->startTransaction();
$result = $table->select('name', 'age')
->lockExclusive(MYSQLX_LOCK_NOWAIT)
->execute();
$session->commit();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 42
            )
    )

# TableSelect::lockShared

(No version information available, might only be in Git)

TableSelect::lockShared — Execute SHARED LOCK

### Description

public mysql_xdevapi\TableSelect::lockShared(int `$lock_waiting_option` = ?): mysql_xdevapi\TableSelect

Execute a read operation with SHARED LOCK. Only one lock can be active at a time.

### Parameters

`lock_waiting_option`

  The optional waiting option that defaults to `MYSQLX_LOCK_DEFAULT`. Valid values are:

  - `MYSQLX_LOCK_DEFAULT`

  - `MYSQLX_LOCK_NOWAIT`

  - `MYSQLX_LOCK_SKIP_LOCKED`

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::lockShared() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$session->startTransaction();
$result = $table->select('name', 'age')
->lockShared(MYSQLX_LOCK_NOWAIT)
->execute();
$session->commit();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
        [1] => Array
            (
                [name] => Sam
                [age] => 42
            )
    )

# TableSelect::offset

(No version information available, might only be in Git)

TableSelect::offset — Set limit offset

### Description

public mysql_xdevapi\TableSelect::offset(int `$position`): mysql_xdevapi\TableSelect

Skip given number of rows in result.

### Parameters

`position`

  The limit offset.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::offset() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name', 'age')
->limit(1)
->offset(1)
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => Sam
                [age] => 42
            )
    )

# TableSelect::orderby

(No version information available, might only be in Git)

TableSelect::orderby — Set select sort criteria

### Description

public mysql_xdevapi\TableSelect::orderby(mixed `$sort_expr`, mixed `...$sort_exprs`): mysql_xdevapi\TableSelect

Sets the order by criteria.

### Parameters

`sort_expr`

  The expressions that define the order by criteria. Can be an array with one or more expressions, or a string.

`sort_exprs`

  Additional sort_expr parameters.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::orderBy() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name', 'age')
->orderBy('name desc')
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => Sam
                [age] => 42
            )
        [1] => Array
            (
                [name] => John
                [age] => 42
            )
    )

# TableSelect::where

(No version information available, might only be in Git)

TableSelect::where — Set select search condition

### Description

public mysql_xdevapi\TableSelect::where(string `$where_expr`): mysql_xdevapi\TableSelect

Sets the search condition to filter.

### Parameters

`where_expr`

  Define the search condition to filter documents or records.

### Return Values

A TableSelect object.

### Examples

Example #1 mysql_xdevapi\TableSelect::where() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->execute();
$row = $result->fetchAll();
print_r($row);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [name] => John
                [age] => 42
            )
    )

## Table of Contents

- TableSelect::bind — Bind select query parameters
- TableSelect::__construct — TableSelect constructor
- TableSelect::execute — Execute select statement
- TableSelect::groupBy — Set select grouping criteria
- TableSelect::having — Set select having condition
- TableSelect::limit — Limit selected rows
- TableSelect::lockExclusive — Execute EXCLUSIVE LOCK
- TableSelect::lockShared — Execute SHARED LOCK
- TableSelect::offset — Set limit offset
- TableSelect::orderby — Set select sort criteria
- TableSelect::where — Set select search condition

# TableUpdate class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

A statement for record update operations on a Table.

## Class synopsis

class mysql_xdevapi\TableUpdate implements mysql_xdevapi\Executable {
/* Methods */
public bind(array `$placeholder_values`): mysql_xdevapi\TableUpdate
public execute(): mysql_xdevapi\TableUpdate
public limit(int `$rows`): mysql_xdevapi\TableUpdate
public orderby(mixed `$orderby_expr`, mixed `...$orderby_exprs`): mysql_xdevapi\TableUpdate
public set(string `$table_field`, string `$expression_or_literal`): mysql_xdevapi\TableUpdate
public where(string `$where_expr`): mysql_xdevapi\TableUpdate
}

# TableUpdate::bind

(No version information available, might only be in Git)

TableUpdate::bind — Bind update query parameters

### Description

public mysql_xdevapi\TableUpdate::bind(array `$placeholder_values`): mysql_xdevapi\TableUpdate

Binds a value to a specific placeholder.

### Parameters

`placeholder_values`

  The name of the placeholder, and the value to bind, defined as a JSON array.

### Return Values

A TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::bind() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$table->update()
->set('status', 'admin')
->where('name = :name and age > :age')
->bind(['name' => 'Bernie', 'age' => 2000])
->execute();
?>`

# TableUpdate::__construct

(No version information available, might only be in Git)

TableUpdate::__construct — TableUpdate constructor

### Description

private mysql_xdevapi\TableUpdate::__construct()

Initiated by using the update() method.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\TableUpdate::__construct() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

# TableUpdate::execute

(No version information available, might only be in Git)

TableUpdate::execute — Execute update query

### Description

public mysql_xdevapi\TableUpdate::execute(): mysql_xdevapi\TableUpdate

Executes the update statement.

### Parameters

This function has no parameters.

### Return Values

A TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::execute() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

# TableUpdate::limit

(No version information available, might only be in Git)

TableUpdate::limit — Limit update row count

### Description

public mysql_xdevapi\TableUpdate::limit(int `$rows`): mysql_xdevapi\TableUpdate

Set the maximum number of records or documents update.

### Parameters

`rows`

  The maximum number of records or documents to update.

### Return Values

A TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::limit() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

# TableUpdate::orderby

(No version information available, might only be in Git)

TableUpdate::orderby — Set sorting criteria

### Description

public mysql_xdevapi\TableUpdate::orderby(mixed `$orderby_expr`, mixed `...$orderby_exprs`): mysql_xdevapi\TableUpdate

Sets the sorting criteria.

### Parameters

`orderby_expr`

  The expressions that define the order by criteria. Can be an array with one or more expressions, or a string.

`orderby_exprs`

  Additional sort_expr parameters.

### Return Values

TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::orderby() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

# TableUpdate::set

(No version information available, might only be in Git)

TableUpdate::set — Add field to be updated

### Description

public mysql_xdevapi\TableUpdate::set(string `$table_field`, string `$expression_or_literal`): mysql_xdevapi\TableUpdate

Updates the column value on records in a table.

### Parameters

`table_field`

  The column name to be updated.

`expression_or_literal`

  The value to be set on the specified column.

### Return Values

TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::set() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

# TableUpdate::where

(No version information available, might only be in Git)

TableUpdate::where — Set search filter

### Description

public mysql_xdevapi\TableUpdate::where(string `$where_expr`): mysql_xdevapi\TableUpdate

Set the search condition to filter.

### Parameters

`where_expr`

  The search condition to filter documents or records.

### Return Values

A TableUpdate object.

### Examples

Example #1 mysql_xdevapi\TableUpdate::where() example

`<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>`

## Table of Contents

- TableUpdate::bind — Bind update query parameters
- TableUpdate::__construct — TableUpdate constructor
- TableUpdate::execute — Execute update query
- TableUpdate::limit — Limit update row count
- TableUpdate::orderby — Set sorting criteria
- TableUpdate::set — Add field to be updated
- TableUpdate::where — Set search filter

# Warning class

(PECL mysql-xdevapi >= 8.0.11)

## Introduction

## Class synopsis

class mysql_xdevapi\Warning {
/* Properties */
public $message;
public $level;
public $code;
/* Constructor */
private __construct()
}

## Properties

message

level

code

# Warning::__construct

(No version information available, might only be in Git)

Warning::__construct — Warning constructor

### Description

private mysql_xdevapi\Warning::__construct()

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Examples

Example #1 mysql_xdevapi\Warning::__construct() example

`<?php
/* ... */
?>`

## Table of Contents

- Warning::__construct — Warning constructor

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Building / Compiling From Source
- Predefined Constants
- Changelog
- Examples
- Mysql_xdevapi Functions
  - expression — Bind prepared statement variables as parameters
  - getSession — Connect to a MySQL server
- mysql_xdevapi\BaseResult — BaseResult interface
  - BaseResult::getWarnings — Fetch warnings from last operation
  - BaseResult::getWarningsCount — Fetch warning count from last operation
- mysql_xdevapi\Client — Client class
  - mysql_xdevapi\Client::close — Close client
  - Client::__construct — Client constructor
  - Client::getClient — Get client session
- mysql_xdevapi\Collection — Collection class
  - Collection::add — Add collection document
  - Collection::addOrReplaceOne — Add or replace collection document
  - Collection::__construct — Collection constructor
  - Collection::count — Get document count
  - Collection::createIndex — Create collection index
  - Collection::dropIndex — Drop collection index
  - Collection::existsInDatabase — Check if collection exists in database
  - Collection::find — Search for document
  - Collection::getName — Get collection name
  - Collection::getOne — Get one document
  - Collection::getSchema — Get schema object
  - Collection::getSession — Get session object
  - Collection::modify — Modify collection documents
  - Collection::remove — Remove collection documents
  - Collection::removeOne — Remove one collection document
  - Collection::replaceOne — Replace one collection document
- mysql_xdevapi\CollectionAdd — CollectionAdd class
  - CollectionAdd::__construct — CollectionAdd constructor
  - CollectionAdd::execute — Execute the statement
- mysql_xdevapi\CollectionFind — CollectionFind class
  - CollectionFind::bind — Bind value to query placeholder
  - CollectionFind::__construct — CollectionFind constructor
  - CollectionFind::execute — Execute the statement
  - CollectionFind::fields — Set document field filter
  - CollectionFind::groupBy — Set grouping criteria
  - CollectionFind::having — Set condition for aggregate functions
  - CollectionFind::limit — Limit number of returned documents
  - CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK
  - CollectionFind::lockShared — Execute operation with SHARED LOCK
  - CollectionFind::offset — Skip given number of elements to be returned
  - CollectionFind::sort — Set the sorting criteria
- mysql_xdevapi\CollectionModify — CollectionModify class
  - CollectionModify::arrayAppend — Append element to an array field
  - CollectionModify::arrayInsert — Insert element into an array field
  - CollectionModify::bind — Bind value to query placeholder
  - CollectionModify::__construct — CollectionModify constructor
  - CollectionModify::execute — Execute modify operation
  - CollectionModify::limit — Limit number of modified documents
  - CollectionModify::patch — Patch document
  - CollectionModify::replace — Replace document field
  - CollectionModify::set — Set document attribute
  - CollectionModify::skip — Skip elements
  - CollectionModify::sort — Set the sorting criteria
  - CollectionModify::unset — Unset the value of document fields
- mysql_xdevapi\CollectionRemove — CollectionRemove class
  - CollectionRemove::bind — Bind value to placeholder
  - CollectionRemove::__construct — CollectionRemove constructor
  - CollectionRemove::execute — Execute remove operation
  - CollectionRemove::limit — Limit number of documents to remove
  - CollectionRemove::sort — Set the sorting criteria
- mysql_xdevapi\ColumnResult — ColumnResult class
  - ColumnResult::__construct — ColumnResult constructor
  - ColumnResult::getCharacterSetName — Get character set
  - ColumnResult::getCollationName — Get collation name
  - ColumnResult::getColumnLabel — Get column label
  - ColumnResult::getColumnName — Get column name
  - ColumnResult::getFractionalDigits — Get fractional digit length
  - ColumnResult::getLength — Get column field length
  - ColumnResult::getSchemaName — Get schema name
  - ColumnResult::getTableLabel — Get table label
  - ColumnResult::getTableName — Get table name
  - ColumnResult::getType — Get column type
  - ColumnResult::isNumberSigned — Check if signed type
  - ColumnResult::isPadded — Check if padded
- mysql_xdevapi\CrudOperationBindable — CrudOperationBindable interface
  - CrudOperationBindable::bind — Bind value to placeholder
- mysql_xdevapi\CrudOperationLimitable — CrudOperationLimitable interface
  - CrudOperationLimitable::limit — Set result limit
- mysql_xdevapi\CrudOperationSkippable — CrudOperationSkippable interface
  - CrudOperationSkippable::skip — Number of operations to skip
- mysql_xdevapi\CrudOperationSortable — CrudOperationSortable interface
  - CrudOperationSortable::sort — Sort results
- mysql_xdevapi\DatabaseObject — DatabaseObject interface
  - DatabaseObject::existsInDatabase — Check if object exists in database
  - DatabaseObject::getName — Get object name
  - DatabaseObject::getSession — Get session name
- mysql_xdevapi\DocResult — DocResult class
  - DocResult::__construct — DocResult constructor
  - DocResult::fetchAll — Get all rows
  - DocResult::fetchOne — Get one row
  - DocResult::getWarnings — Get warnings from last operation
  - DocResult::getWarningsCount — Get warning count from last operation
- mysql_xdevapi\Exception — Exception class
- mysql_xdevapi\Executable — Executable interface
  - Executable::execute — Execute statement
- mysql_xdevapi\ExecutionStatus — ExecutionStatus class
  - ExecutionStatus::__construct — ExecutionStatus constructor
- mysql_xdevapi\Expression — Expression class
  - Expression::__construct — Expression constructor
- mysql_xdevapi\Result — Result class
  - Result::__construct — Result constructor
  - Result::getAffectedItemsCount — Get affected row count
  - Result::getAutoIncrementValue — Get autoincremented value
  - Result::getGeneratedIds — Get generated ids
  - Result::getWarnings — Get warnings from last operation
  - Result::getWarningsCount — Get warning count from last operation
- mysql_xdevapi\RowResult — RowResult class
  - RowResult::__construct — RowResult constructor
  - RowResult::fetchAll — Get all rows from result
  - RowResult::fetchOne — Get row from result
  - RowResult::getColumnsCount — Get column count
  - RowResult::getColumnNames — Get all column names
  - RowResult::getColumns — Get column metadata
  - RowResult::getWarnings — Get warnings from last operation
  - RowResult::getWarningsCount — Get warning count from last operation
- mysql_xdevapi\Schema — Schema class
  - Schema::__construct — Schema constructor
  - Schema::createCollection — Add collection to schema
  - Schema::dropCollection — Drop collection from schema
  - Schema::existsInDatabase — Check if exists in database
  - Schema::getCollection — Get collection from schema
  - Schema::getCollectionAsTable — Get collection as a Table object
  - Schema::getCollections — Get all schema collections
  - Schema::getName — Get schema name
  - Schema::getSession — Get schema session
  - Schema::getTable — Get schema table
  - Schema::getTables — Get schema tables
- mysql_xdevapi\SchemaObject — SchemaObject interface
  - SchemaObject::getSchema — Get schema object
- mysql_xdevapi\Session — Session class
  - Session::close — Close session
  - Session::commit — Commit transaction
  - Session::__construct — Description constructor
  - Session::createSchema — Create new schema
  - Session::dropSchema — Drop a schema
  - Session::generateUUID — Get new UUID
  - Session::getDefaultSchema — Get default schema name
  - Session::getSchema — Get a new schema object
  - Session::getSchemas — Get the schemas
  - Session::getServerVersion — Get server version
  - Session::listClients — Get client list
  - Session::quoteName — Add quotes
  - Session::releaseSavepoint — Release set savepoint
  - Session::rollback — Rollback transaction
  - Session::rollbackTo — Rollback transaction to savepoint
  - Session::setSavepoint — Create savepoint
  - Session::sql — Create SQL query
  - Session::startTransaction — Start transaction
- mysql_xdevapi\SqlStatement — SqlStatement class
  - SqlStatement::bind — Bind statement parameters
  - SqlStatement::__construct — Description constructor
  - SqlStatement::execute — Execute the operation
  - SqlStatement::getNextResult — Get next result
  - SqlStatement::getResult — Get result
  - SqlStatement::hasMoreResults — Check for more results
- mysql_xdevapi\SqlStatementResult — SqlStatementResult class
  - SqlStatementResult::__construct — Description constructor
  - SqlStatementResult::fetchAll — Get all rows from result
  - SqlStatementResult::fetchOne — Get single row
  - SqlStatementResult::getAffectedItemsCount — Get affected row count
  - SqlStatementResult::getColumnsCount — Get column count
  - SqlStatementResult::getColumnNames — Get column names
  - SqlStatementResult::getColumns — Get columns
  - SqlStatementResult::getGeneratedIds — Get generated ids
  - SqlStatementResult::getLastInsertId — Get last insert id
  - SqlStatementResult::getWarnings — Get warnings from last operation
  - SqlStatementResult::getWarningsCount — Get warning count from last operation
  - SqlStatementResult::hasData — Check if result has data
  - SqlStatementResult::nextResult — Get next result
- mysql_xdevapi\Statement — Statement class
  - Statement::__construct — Description constructor
  - Statement::getNextResult — Get next result
  - Statement::getResult — Get result
  - Statement::hasMoreResults — Check if more results
- mysql_xdevapi\Table — Table class
  - Table::__construct — Table constructor
  - Table::count — Get row count
  - Table::delete — Delete rows from table
  - Table::existsInDatabase — Check if table exists in database
  - Table::getName — Get table name
  - Table::getSchema — Get table schema
  - Table::getSession — Get table session
  - Table::insert — Insert table rows
  - Table::isView — Check if table is view
  - Table::select — Select rows from table
  - Table::update — Update rows in table
- mysql_xdevapi\TableDelete — TableDelete class
  - TableDelete::bind — Bind delete query parameters
  - TableDelete::__construct — TableDelete constructor
  - TableDelete::execute — Execute delete query
  - TableDelete::limit — Limit deleted rows
  - TableDelete::orderby — Set delete sort criteria
  - TableDelete::where — Set delete search condition
- mysql_xdevapi\TableInsert — TableInsert class
  - TableInsert::__construct — TableInsert constructor
  - TableInsert::execute — Execute insert query
  - TableInsert::values — Add insert row values
- mysql_xdevapi\TableSelect — TableSelect class
  - TableSelect::bind — Bind select query parameters
  - TableSelect::__construct — TableSelect constructor
  - TableSelect::execute — Execute select statement
  - TableSelect::groupBy — Set select grouping criteria
  - TableSelect::having — Set select having condition
  - TableSelect::limit — Limit selected rows
  - TableSelect::lockExclusive — Execute EXCLUSIVE LOCK
  - TableSelect::lockShared — Execute SHARED LOCK
  - TableSelect::offset — Set limit offset
  - TableSelect::orderby — Set select sort criteria
  - TableSelect::where — Set select search condition
- mysql_xdevapi\TableUpdate — TableUpdate class
  - TableUpdate::bind — Bind update query parameters
  - TableUpdate::__construct — TableUpdate constructor
  - TableUpdate::execute — Execute update query
  - TableUpdate::limit — Limit update row count
  - TableUpdate::orderby — Set sorting criteria
  - TableUpdate::set — Add field to be updated
  - TableUpdate::where — Set search filter
- mysql_xdevapi\Warning — Warning class
  - Warning::__construct — Warning constructor

# Original MySQL API

# Introduction

This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

In order to have these functions available, you must compile PHP with MySQL support.

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

## Installation

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

For compiling, simply use the --with-mysql[=DIR] configuration option where the optional `[DIR]` points to the MySQL installation directory.

Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these versions provide. For that, use the MySQLi extension.

If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.

## Installation on Linux Systems

Note: `[DIR]` is the path to the MySQL client library files (headers and libraries), which can be downloaded from » MySQL.

ext/mysql compile time support matrix
PHP Version | Default | Configure Options: mysqlnd | Configure Options: `libmysqlclient` | Changelog
--- | --- | --- | --- | ---
4.x.x | libmysqlclient | Not Available | --without-mysql to disable | MySQL enabled by default, MySQL client libraries are bundled
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Not Available | --with-mysql=[DIR] | MySQL is no longer enabled by default, and the MySQL client libraries are no longer bundled
5.3.x | libmysqlclient | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd is now available
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd is now the default

## Installation on Windows Systems

## PHP 5.0.x, 5.1.x, 5.2.x

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended.

As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is `c:\php\ext`

> Note: If when starting the web server an error similar to the following occurs: `"Unable to load dynamic library './php_mysql.dll'"`, this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.

## PHP 5.3.0+

The MySQL Native Driver is enabled by default. Include php_mysql.dll, but libmysql.dll is no longer required or used.

## MySQL Installation Notes

Warning

Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.

> Note: If you need charsets other than latin (default), you have to install external (not bundled) libmysqlclient with compiled charset support.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQL Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mysql.allow_local_infile | "1" | `INI_SYSTEM` |
mysql.allow_persistent | "1" | `INI_SYSTEM` |
mysql.max_persistent | "-1" | `INI_SYSTEM` |
mysql.max_links | "-1" | `INI_SYSTEM` |
mysql.trace_mode | "0" | `INI_ALL` |
mysql.default_port | NULL | `INI_ALL` |
mysql.default_socket | NULL | `INI_ALL` |
mysql.default_host | NULL | `INI_ALL` |
mysql.default_user | NULL | `INI_ALL` |
mysql.default_password | NULL | `INI_ALL` |
mysql.connect_timeout | "60" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mysql.allow_local_infile` int
  Allow accessing, from PHP's perspective, local files with LOAD DATA statements
`mysql.allow_persistent` bool
  Whether to allow persistent connections to MySQL.
`mysql.max_persistent` int
  The maximum number of persistent MySQL connections per process.
`mysql.max_links` int
  The maximum number of MySQL connections per process, including persistent connections.
`mysql.trace_mode` bool
  Trace mode. When `mysql.trace_mode` is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0)
`mysql.default_port` string
  The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the `mysql-tcp` entry in /etc/services or the compile-time `MYSQL_PORT` constant, in that order. Win32 will only use the `MYSQL_PORT` constant.
`mysql.default_socket` string
  The default socket name to use when connecting to a local database server if no other socket name is specified.
`mysql.default_host` string
  The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in SQL safe mode.
`mysql.default_user` string
  The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in SQL safe mode.
`mysql.default_password` string
  The default password to use when connecting to the database server if no other password is specified. Doesn't apply in SQL safe mode.
`mysql.connect_timeout` int
  Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.

## Resource Types

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

# Changelog

The following changes have been made to classes/functions/methods of this extension.

### General Changelog for the ext/mysql extension

This changelog references the ext/mysql extension.

### Global ext/mysql changes

The following is a list of changes to the entire ext/mysql extension.

Version | Description
--- | ---
7.0.0 | This extension was removed from PHP. For details, see Choosing an API.

### Changes to existing functions

The following list is a compilation of changelog entries from the ext/mysql functions.

Version | Function | Description
--- | --- | ---

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

It is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions. The following constants are defined:

MySQL client constants
Constant | Description
--- | ---
`MYSQL_CLIENT_COMPRESS` | Use compression protocol
`MYSQL_CLIENT_IGNORE_SPACE` | Allow space after function names
`MYSQL_CLIENT_INTERACTIVE` | Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection.
`MYSQL_CLIENT_SSL` | Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5.

The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MySQL fetch constants
Constant | Description
--- | ---
`MYSQL_ASSOC` | Columns are returned into the array having the fieldname as the array index.
`MYSQL_BOTH` | Columns are returned into the array having both a numerical index and the fieldname as the array index.
`MYSQL_NUM` | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

# Examples

## Table of Contents

- MySQL extension overview example

## MySQL extension overview example

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

Example #1 MySQL extension overview example

`<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>`

# MySQL Functions

## Notes

> Note: Most MySQL functions accept `link_identifier` as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return `false`.

# mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Get number of affected rows in previous MySQL operation

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_affected_rows()
- PDOStatement::rowCount()

### Description

mysql_affected_rows(resource `$link_identifier` = NULL): int

Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with `link_identifier`.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the number of affected rows on success, and -1 if the last query failed.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.

In the case of "INSERT ... ON DUPLICATE KEY UPDATE" queries, the return value will be `1` if an insert was performed, or `2` for an update of an existing row.

### Examples

Example #1 mysql_affected_rows() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>`

The above example will output something similar to:

    Records deleted: 10
    Records deleted: 0

Example #2 mysql_affected_rows() example using transactions

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>`

The above example will output something similar to:

    Updated Records: 10

### Notes

> Note: Transactions
> If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT.

> Note: SELECT Statements
> To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows().

> Note: Cascaded Foreign Keys
> mysql_affected_rows() does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints.

### See Also

- mysql_num_rows() - Get number of rows in result
- mysql_info() - Get information about the most recent query

# mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Returns the name of the character set

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_character_set_name()

### Description

mysql_client_encoding(resource `$link_identifier` = NULL): string

Retrieves the `character_set` variable from MySQL.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the default character set name for the current connection.

### Examples

Example #1 mysql_client_encoding() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);
echo "The current character set is: $charset\n";
?>`

The above example will output something similar to:

    The current character set is: latin1

### See Also

- mysql_set_charset() - Sets the client character set
- mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement

# mysql_close

(PHP 4, PHP 5)

mysql_close — Close MySQL connection

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_close()
- PDO: Assign the value of `null` to the PDO object

### Description

mysql_close(resource `$link_identifier` = NULL): bool

mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If `link_identifier` isn't specified, the last opened link is used.

Open non-persistent MySQL connections and result sets are automatically destroyed when a PHP script finishes its execution. So, while explicitly closing open connections and freeing result sets is optional, doing so is recommended. This will immediately return resources to PHP and MySQL, which can improve performance. For related information, see freeing resources

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysql_close() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>`

The above example will output:

    Connected successfully

### Notes

> Note: mysql_close() will not close persistent links created by mysql_pconnect(). For additional details, see the manual page on persistent connections.

### See Also

- mysql_connect() - Open a connection to a MySQL Server
- mysql_free_result() - Free result memory

# mysql_connect

(PHP 4, PHP 5)

mysql_connect — Open a connection to a MySQL Server

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_connect()
- PDO::__construct()

### Description

mysql_connect(
string `$server` = ini_get("mysql.default_host"),
string `$username` = ini_get("mysql.default_user"),
string `$password` = ini_get("mysql.default_password"),
bool `$new_link` = `false`,
int `$client_flags` = 0
): resource|false

Opens or reuses a connection to a MySQL server.

### Parameters

`server`
  The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.
`username`
  The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.
`password`
  The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.
`new_link`
  If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The `new_link` parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
`client_flags`
  The `client_flags` parameter can be a combination of the following constants: 128 (enable `LOAD DATA LOCAL` handling), `MYSQL_CLIENT_SSL`, `MYSQL_CLIENT_COMPRESS`, `MYSQL_CLIENT_IGNORE_SPACE` or `MYSQL_CLIENT_INTERACTIVE`. Read the section about MySQL client constants for further information. In SQL safe mode, this parameter is ignored.

### Return Values

Returns a MySQL link identifier on success or `false` on failure.

### Examples

Example #1 mysql_connect() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>`

Example #2 mysql_connect() example using `hostname:port` syntax

`<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>`

Example #3 mysql_connect() example using ":/path/to/socket" syntax

`<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock
// variant 1: omit localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>`

### Notes

> Note: Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, the correct path should be set as mysql.default_host in php.ini and the server field left blank.

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

> Note: Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character `E`. On Windows, if the environment is not copied the `SYSTEMROOT` environment variable won't be available and PHP will have problems loading Winsock.

### See Also

- mysql_pconnect() - Open a persistent connection to a MySQL server
- mysql_close() - Close MySQL connection

# mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Create a MySQL database

Warning

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_query()
- PDO::query()

### Description

mysql_create_db(string `$database_name`, resource `$link_identifier` = NULL): bool

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

### Parameters

`database_name`
  The name of the database being created.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysql_create_db() alternative example

The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue an sql `CREATE DATABASE` statement instead.

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>`

The above example will output something similar to:

    Database my_db created successfully

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_createdb()

> Note: This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

### See Also

- mysql_query() - Send a MySQL query
- mysql_select_db() - Select a MySQL database

# mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Move internal result pointer

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_data_seek()
- `PDO::FETCH_ORI_ABS`

### Description

mysql_data_seek(resource `$result`, int `$row_number`): bool

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

`row_number` starts at 0. The `row_number` should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with an `E_WARNING` and mysql_data_seek() will return `false`.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`row_number`
  The desired row number of the new result pointer.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysql_data_seek() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}
mysql_free_result($result);
?>`

### Notes

> Note: The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query().

### See Also

- mysql_query() - Send a MySQL query
- mysql_num_rows() - Get number of rows in result
- mysql_fetch_row() - Get a result row as an enumerated array
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- mysql_fetch_object() - Fetch a result row as an object

# mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Retrieves database name from the call to mysql_list_dbs()

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- Query: `SELECT DATABASE()`

### Description

mysql_db_name(resource `$result`, int `$row`, mixed `$field` = NULL): string

Retrieve the database name from a call to mysql_list_dbs().

### Parameters

`result`
  The result pointer from a call to mysql_list_dbs().
`row`
  The index into the result set.
`field`
  The field name.

### Return Values

Returns the database name on success, and `false` on failure. If `false` is returned, use mysql_error() to determine the nature of the error.

### Examples

Example #1 mysql_db_name() example

`<?php
error_reporting(E_ALL);
$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);
$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
echo mysql_db_name($db_list, $i) . "\n";
$i++;
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_dbname()

### See Also

- mysql_list_dbs() - List databases available on a MySQL server
- mysql_tablename() - Get table name of field

# mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Selects a database and executes a query on it

Warning

This function was deprecated in PHP 5.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_select_db() then the query
- PDO::__construct()

### Description

mysql_db_query(string `$database`, string `$query`, resource `$link_identifier` = NULL): resource|bool

mysql_db_query() selects a database, and executes a query on it.

### Parameters

`database`
  The name of the database that will be selected.
`query`
  The MySQL query. Data inside the query should be properly escaped.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns a positive MySQL result resource to the query result, or `false` on error. The function also returns `true`/`false` for `INSERT`/`UPDATE`/`DELETE` queries to indicate success/failure.

### Examples

Example #1 mysql_db_query() alternative example

`<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('mysql_dbname', $link)) {
echo 'Could not select database';
exit;
}
$sql = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['foo'];
}
mysql_free_result($result);
?>`

### Notes

> Note: Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the `database.table` syntax in their sql queries or mysql_select_db() instead of this function.

### See Also

- mysql_query() - Send a MySQL query
- mysql_select_db() - Select a MySQL database

# mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Drop (delete) a MySQL database

Warning

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- Execute a `DROP DATABASE` query

### Description

mysql_drop_db(string `$database_name`, resource `$link_identifier` = NULL): bool

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue an sql `DROP DATABASE` statement instead.

### Parameters

`database_name`
  The name of the database that will be deleted.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysql_drop_db() alternative example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db was successfully dropped\n";
} else {
echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>`

### Notes

Warning

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

> Note: For backward compatibility, the following deprecated alias may be used: mysql_dropdb()

### See Also

- mysql_query() - Send a MySQL query

# mysql_errno

(PHP 4, PHP 5)

mysql_errno — Returns the numerical value of the error message from previous MySQL operation

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_errno()
- PDO::errorCode()

### Description

mysql_errno(resource `$link_identifier` = NULL): int

Returns the error number from the last MySQL function.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the error number from the last MySQL function, or `0` (zero) if no error occurred.

### Examples

Example #1 mysql_errno() example

`<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!mysql_select_db("nonexistentdb", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}
mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>`

The above example will output something similar to:

    1049: Unknown database 'nonexistentdb'
    1146: Table 'kossu.nonexistenttable' doesn't exist

### See Also

- mysql_error() - Returns the text of the error message from previous MySQL operation
- » MySQL error codes

# mysql_error

(PHP 4, PHP 5)

mysql_error — Returns the text of the error message from previous MySQL operation

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_error()
- PDO::errorInfo()

### Description

mysql_error(resource `$link_identifier` = NULL): string

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the error text from the last MySQL function, or `''` (empty string) if no error occurred.

### Examples

Example #1 mysql_error() example

`<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>`

The above example will output something similar to:

    1049: Unknown database 'nonexistentdb'
    1146: Table 'kossu.nonexistenttable' doesn't exist

### See Also

- mysql_errno() - Returns the numerical value of the error message from previous MySQL operation
- » MySQL error codes

# mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Escapes a string for use in a mysql_query

Warning

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_escape_string()
- PDO::quote()

### Description

mysql_escape_string(string `$unescaped_string`): string

This function will escape the `unescaped_string`, so that it is safe to place it in a mysql_query(). This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

### Parameters

`unescaped_string`
  The string that is to be escaped.

### Return Values

Returns the escaped string.

### Examples

Example #1 mysql_escape_string() example

`<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>`

The above example will output:

    Escaped string: Zak\'s Laptop

### Notes

> Note: mysql_escape_string() does not escape `%` and `_`.

### See Also

- mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement

# mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_array()
- PDOStatement::fetch()

### Description

mysql_fetch_array(resource `$result`, int `$result_type` = MYSQL_BOTH): array

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`result_type`
  The type of array that is to be fetched. It's a constant and can take the following values: `MYSQL_ASSOC`, `MYSQL_NUM`, and `MYSQL_BOTH`.

### Return Values

Returns an array of strings that corresponds to the fetched row, or `false` if there are no more rows. The type of returned array depends on how `result_type` is defined. By using `MYSQL_BOTH` (default), you'll get an array with both associative and number indices. Using `MYSQL_ASSOC`, you only get associative indices (as mysql_fetch_assoc() works), using `MYSQL_NUM`, you only get number indices (as mysql_fetch_row() works).

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

### Examples

Example #1 Query with aliased duplicate field names

    SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Example #2 mysql_fetch_array() with `MYSQL_NUM`

`<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>`

Example #3 mysql_fetch_array() with `MYSQL_ASSOC`

`<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
mysql_free_result($result);
?>`

Example #4 mysql_fetch_array() with `MYSQL_BOTH`

`<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
printf ("ID: %s Name: %s", $row[0], $row["name"]);
}
mysql_free_result($result);
?>`

### Notes

> Note: Performance
> An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### See Also

- mysql_fetch_row() - Get a result row as an enumerated array
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_data_seek() - Move internal result pointer
- mysql_query() - Send a MySQL query

# mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Fetch a result row as an associative array

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_assoc()
- PDOStatement::fetch() with `mode` as `PDO::FETCH_ASSOC`

### Description

mysql_fetch_assoc(resource `$result`): array

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

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

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

### Examples

Example #1 An expanded mysql_fetch_assoc() example

`<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>`

### Notes

> Note: Performance
> An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### See Also

- mysql_fetch_row() - Get a result row as an enumerated array
- mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- mysql_data_seek() - Move internal result pointer
- mysql_query() - Send a MySQL query
- mysql_error() - Returns the text of the error message from previous MySQL operation

# mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Get column information from a result and return as an object

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field()
- PDOStatement::getColumnMeta()

### Description

mysql_fetch_field(resource `$result`, int `$field_offset` = 0): object

Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`
  The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The `field_offset` starts at `0`.

### Return Values

Returns an object containing field information. The properties of the object are:

- name - column name
- table - name of the table the column belongs to, which is the alias name if one is defined
- max_length - maximum length of the column
- not_null - 1 if the column cannot be `null`
- primary_key - 1 if the column is a primary key
- unique_key - 1 if the column is a unique key
- multiple_key - 1 if the column is a non-unique key
- numeric - 1 if the column is numeric
- blob - 1 if the column is a BLOB
- type - the type of the column
- unsigned - 1 if the column is unsigned
- zerofill - 1 if the column is zero-filled

### Examples

Example #1 mysql_fetch_field() example

`<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
echo "Information for column $i:<br />\n";
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
echo "<pre>
blob: $meta->blob
max_length: $meta->max_length
multiple_key: $meta->multiple_key
name: $meta->name
not_null: $meta->not_null
numeric: $meta->numeric
primary_key: $meta->primary_key
table: $meta->table
type: $meta->type
unique_key: $meta->unique_key
unsigned: $meta->unsigned
zerofill: $meta->zerofill
</pre>";
$i++;
}
mysql_free_result($result);
?>`

### Notes

> Note: Field names returned by this function are case-sensitive.

> Note: If field or tablenames are aliased in the SQL query the aliased name will be returned. The original name can be retrieved for instance by using mysqli_result::fetch_field().

### See Also

- mysql_field_seek() - Set result pointer to a specified field offset

# mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Get the length of each output in a result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_lengths()
- PDOStatement::getColumnMeta()

### Description

mysql_fetch_lengths(resource `$result`): array|false

Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths() stores the lengths of each result column in the last row returned by mysql_fetch_row(), mysql_fetch_assoc(), mysql_fetch_array(), and mysql_fetch_object() in an array, starting at offset 0.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

An array of lengths on success or `false` on failure.

### Examples

Example #1 A mysql_fetch_lengths() example

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);
print_r($row);
print_r($lengths);
?>`

The above example will output something similar to:

    Array
    (
        [id] => 42
        [email] => user@example.com
    )
    Array
    (
        [0] => 2
        [1] => 16
    )

### See Also

- mysql_field_len() - Returns the length of the specified field
- mysql_fetch_row() - Get a result row as an enumerated array
- strlen() - Get string length

# mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Fetch a result row as an object

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_object()
- PDOStatement::fetch() with `mode` as `PDO::FETCH_OBJ`

### Description

mysql_fetch_object(resource `$result`, string `$class_name` = ?, array `$params` = ?): object

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`class_name`
  The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
`params`
  An optional array of parameters to pass to the constructor for `class_name` objects.

### Return Values

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

### Examples

Example #1 mysql_fetch_object() example

`<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>`

Example #2 mysql_fetch_object() example

`<?php
class foo {
public $name;
}
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>`

### Notes

> Note: Performance
> Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

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

> Note: Field names returned by this function are case-sensitive.

> Note: This function sets NULL fields to the PHP `null` value.

### See Also

- mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_fetch_row() - Get a result row as an enumerated array
- mysql_data_seek() - Move internal result pointer
- mysql_query() - Send a MySQL query

# mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Get a result row as an enumerated array

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_row()
- PDOStatement::fetch() with `mode` as `PDO::FETCH_NUM`

### Description

mysql_fetch_row(resource `$result`): array

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

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

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

### Examples

Example #1 Fetching one row with mysql_fetch_row()

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>`

### Notes

> Note: This function sets NULL fields to the PHP `null` value.

### See Also

- mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_fetch_object() - Fetch a result row as an object
- mysql_data_seek() - Move internal result pointer
- mysql_fetch_lengths() - Get the length of each output in a result
- mysql_result() - Get result data

# mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Get the flags associated with the specified field in a result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field_direct() [flags]
- PDOStatement::getColumnMeta() [flags]

### Description

mysql_field_flags(resource `$result`, int `$field_offset`): string|false

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Returns a string of flags associated with the result or `false` on failure.

The following flags are reported, if your version of MySQL is current enough to support them: `"not_null"`, `"primary_key"`, `"unique_key"`, `"multiple_key"`, `"blob"`, `"unsigned"`, `"zerofill"`, `"binary"`, `"enum"`, `"auto_increment"` and `"timestamp"`.

### Examples

Example #1 A mysql_field_flags() example

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$flags = mysql_field_flags($result, 0);
echo $flags;
print_r(explode(' ', $flags));
?>`

The above example will output something similar to:

    not_null primary_key auto_increment
    Array
    (
        [0] => not_null
        [1] => primary_key
        [2] => auto_increment
    )

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldflags()

### See Also

- mysql_field_type() - Get the type of the specified field in a result
- mysql_field_len() - Returns the length of the specified field

# mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Returns the length of the specified field

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field_direct() [length]
- PDOStatement::getColumnMeta() [len]

### Description

mysql_field_len(resource `$result`, int `$field_offset`): int|false

mysql_field_len() returns the length of the specified field.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

The length of the specified field index on success or `false` on failure.

### Examples

Example #1 mysql_field_len() example

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
// Will get the length of the id field as specified in the database
// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldlen()

### See Also

- mysql_fetch_lengths() - Get the length of each output in a result
- strlen() - Get string length

# mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Get the name of the specified field in a result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field_direct() [name] or [orgname]
- PDOStatement::getColumnMeta() [name]

### Description

mysql_field_name(resource `$result`, int `$field_offset`): string|false

mysql_field_name() returns the name of the specified field index.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

The name of the specified field index on success or `false` on failure.

### Examples

Example #1 mysql_field_name() example

`<?php
/* The users table consists of three fields:
* user_id
* username
* password.
*/
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);
echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>`

The above example will output:

    user_id
    password

### Notes

> Note: Field names returned by this function are case-sensitive.

> Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldname()

### See Also

- mysql_field_type() - Get the type of the specified field in a result
- mysql_field_len() - Returns the length of the specified field

# mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Set result pointer to a specified field offset

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_field_seek()
- PDOStatement::fetch() using the `cursor_orientation` and `offset` parameters

### Description

mysql_field_seek(resource `$result`, int `$field_offset`): bool

Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mysql_fetch_field() - Get column information from a result and return as an object

# mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Get name of the table the specified field is in

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field_direct() [table] or [orgtable]
- PDOStatement::getColumnMeta() [table]

### Description

mysql_field_table(resource `$result`, int `$field_offset`): string

Returns the name of the table that the specified field is in.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

The name of the table on success.

### Examples

Example #1 A mysql_field_table() example

`<?php
$query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country.id";
// get the result from the DB
$result = mysql_query($query);
// Lists the table name and then the field name
for ($i = 0; $i < mysql_num_fields($result); ++$i) {
$table = mysql_field_table($result, $i);
$field = mysql_field_name($result, $i);
echo "$table: $field\n";
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtable()

### See Also

- mysql_list_tables() - List tables in a MySQL database

# mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Get the type of the specified field in a result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_fetch_field_direct() [type]
- PDOStatement::getColumnMeta() [driver:decl_type] or [pdo_type]

### Description

mysql_field_type(resource `$result`, int `$field_offset`): string

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`field_offset`

  The numerical field offset. The `field_offset` starts at `0`. If `field_offset` does not exist, an error of level `E_WARNING` is also issued.

### Return Values

The returned field type will be one of `"int"`, `"real"`, `"string"`, `"blob"`, and others as detailed in the » MySQL documentation.

### Examples

Example #1 mysql_field_type() example

`<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?>`

The above example will output something similar to:

    Your 'func' table has 4 fields and 1 record(s)
    The table has the following fields:
    string name 64 not_null primary_key binary
    int ret 1 not_null
    string dl 128 not_null
    string type 9 not_null enum

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtype()

### See Also

- mysql_field_name() - Get the name of the specified field in a result
- mysql_field_len() - Returns the length of the specified field

# mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Free result memory

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_free_result()
- Assign the value of `null` to the PDO object, or PDOStatement::closeCursor()

### Description

mysql_free_result(resource `$result`): bool

mysql_free_result() will free all memory associated with the result identifier `result`.

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

Returns `true` on success or `false` on failure.

If a non-resource is used for the `result`, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

### Examples

Example #1 A mysql_free_result() example

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);
/* Now we free up the result and continue on with our script */
mysql_free_result($result);
echo $row['id'];
echo $row['email'];
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_freeresult()

### See Also

- mysql_query() - Send a MySQL query
- is_resource() - Finds whether a variable is a resource

# mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Get MySQL client info

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_get_client_info()
- PDO::getAttribute() with `attribute` as `PDO::ATTR_CLIENT_VERSION`

### Description

mysql_get_client_info(): string

mysql_get_client_info() returns a string that represents the client library version.

### Parameters

This function has no parameters.

### Return Values

The MySQL client version.

### Examples

Example #1 mysql_get_client_info() example

`<?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?>`

The above example will output something similar to:

    MySQL client info: 3.23.39

### See Also

- mysql_get_host_info() - Get MySQL host info
- mysql_get_proto_info() - Get MySQL protocol info
- mysql_get_server_info() - Get MySQL server info

# mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Get MySQL host info

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_get_host_info()
- PDO::getAttribute() with `attribute` as `PDO::ATTR_CONNECTION_STATUS`

### Description

mysql_get_host_info(resource `$link_identifier` = NULL): string|false

Describes the type of connection in use for the connection, including the server host name.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns a string describing the type of MySQL connection in use for the connection or `false` on failure.

### Examples

Example #1 mysql_get_host_info() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?>`

The above example will output something similar to:

    MySQL host info: Localhost via UNIX socket

### See Also

- mysql_get_client_info() - Get MySQL client info
- mysql_get_proto_info() - Get MySQL protocol info
- mysql_get_server_info() - Get MySQL server info

# mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Get MySQL protocol info

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_get_proto_info()

### Description

mysql_get_proto_info(resource `$link_identifier` = NULL): int|false

Retrieves the MySQL protocol.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the MySQL protocol on success or `false` on failure.

### Examples

Example #1 mysql_get_proto_info() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?>`

The above example will output something similar to:

    MySQL protocol version: 10

### See Also

- mysql_get_client_info() - Get MySQL client info
- mysql_get_host_info() - Get MySQL host info
- mysql_get_server_info() - Get MySQL server info

# mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Get MySQL server info

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_get_server_info()
- PDO::getAttribute() with `attribute` as `PDO::ATTR_SERVER_VERSION`

### Description

mysql_get_server_info(resource `$link_identifier` = NULL): string|false

Retrieves the MySQL server version.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the MySQL server version on success or `false` on failure.

### Examples

Example #1 mysql_get_server_info() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?>`

The above example will output something similar to:

    MySQL server version: 4.0.1-alpha

### See Also

- mysql_get_client_info() - Get MySQL client info
- mysql_get_host_info() - Get MySQL host info
- mysql_get_proto_info() - Get MySQL protocol info
- phpversion() - Gets the current PHP version

# mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Get information about the most recent query

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_info()

### Description

mysql_info(resource `$link_identifier` = NULL): string

Returns detailed information about the last query.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns information about the statement on success, or `false` on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return `false`.

### Examples

Example #1 Relevant MySQL Statements

Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query.

    INSERT INTO ... SELECT ...
    String format: Records: 23 Duplicates: 0 Warnings: 0
    INSERT INTO ... VALUES (...),(...),(...)...
    String format: Records: 37 Duplicates: 0 Warnings: 0
    LOAD DATA INFILE ...
    String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
    ALTER TABLE
    String format: Records: 60 Duplicates: 0 Warnings: 0
    UPDATE
    String format: Rows matched: 65 Changed: 65 Warnings: 0

### Notes

> Note: mysql_info() returns a non-`false` value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

### See Also

- mysql_affected_rows() - Get number of affected rows in previous MySQL operation
- mysql_insert_id() - Get the ID generated in the last query
- mysql_stat() - Get current system status

# mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Get the ID generated in the last query

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_insert_id()
- PDO::lastInsertId()

### Description

mysql_insert_id(resource `$link_identifier` = NULL): int

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

The ID generated for an AUTO_INCREMENT column by the previous query on success, `0` if the previous query does not generate an AUTO_INCREMENT value, or `false` if no MySQL connection was established.

### Examples

Example #1 mysql_insert_id() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>`

### Notes

Caution

mysql_insert_id() will convert the return type of the native MySQL C API function `mysql_insert_id()` to a type of `long` (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.

> Note: Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

> Note: The value of the MySQL SQL function `LAST_INSERT_ID()` always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

### See Also

- mysql_query() - Send a MySQL query
- mysql_info() - Get information about the most recent query

# mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — List databases available on a MySQL server

Warning

This function was deprecated in PHP 5.4.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- SQL Query: `SHOW DATABASES`

### Description

mysql_list_dbs(resource `$link_identifier` = NULL): resource

Returns a result pointer containing the databases available from the current mysql daemon.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns a result pointer resource on success, or `false` on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

### Examples

Example #1 mysql_list_dbs() example

`<?php
// Usage without mysql_list_dbs()
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_assoc($res)) {
echo $row['Database'] . "\n";
}
// Deprecated as of PHP 5.4.0
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
?>`

The above example will output something similar to:

    database1
    database2
    database3

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_listdbs()

### See Also

- mysql_db_name() - Retrieves database name from the call to mysql_list_dbs
- mysql_select_db() - Select a MySQL database

# mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — List MySQL table fields

Warning

This function was deprecated in PHP 5.4.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- SQL Query: `SHOW COLUMNS FROM sometable`

### Description

mysql_list_fields(string `$database_name`, string `$table_name`, resource `$link_identifier` = NULL): resource

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL `SHOW COLUMNS FROM table [LIKE 'name']` statement instead.

### Parameters

`database_name`
  The name of the database that's being queried.
`table_name`
  The name of the table that's being queried.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

A result pointer resource on success, or `false` on failure.

The returned result can be used with mysql_field_flags(), mysql_field_len(), mysql_field_name() and mysql_field_type().

### Examples

Example #1 Alternate to deprecated mysql_list_fields()

`<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>`

The above example will output something similar to:

    Array
    (
        [Field] => id
        [Type] => int(7)
        [Null] =>
        [Key] => PRI
        [Default] =>
        [Extra] => auto_increment
    )
    Array
    (
        [Field] => email
        [Type] => varchar(100)
        [Null] =>
        [Key] =>
        [Default] =>
        [Extra] =>
    )

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_listfields()

### See Also

- mysql_field_flags() - Get the flags associated with the specified field in a result
- mysql_info() - Get information about the most recent query

# mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — List MySQL processes

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_thread_id()

### Description

mysql_list_processes(resource `$link_identifier` = NULL): resource|false

Retrieves the current MySQL server threads.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

A result pointer resource on success or `false` on failure.

### Examples

Example #1 mysql_list_processes() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
$row["Command"], $row["Time"]);
}
mysql_free_result($result);
?>`

The above example will output something similar to:

    1 localhost test Processlist 0
    4 localhost mysql sleep 5

### See Also

- mysql_thread_id() - Return the current thread ID
- mysql_stat() - Get current system status

# mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — List tables in a MySQL database

Warning

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

- SQL Query: `SHOW TABLES FROM dbname`

### Description

mysql_list_tables(string `$database`, resource `$link_identifier` = NULL): resource|false

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL `SHOW TABLES [FROM db_name] [LIKE 'pattern']` statement instead.

### Parameters

`database`
  The name of the database
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

A result pointer resource on success or `false` on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

### Examples

Example #1 mysql_list_tables() alternative example

`<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_listtables()

### See Also

- mysql_list_dbs() - List databases available on a MySQL server
- mysql_tablename() - Get table name of field

# mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Get number of fields in result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_num_fields()
- PDOStatement::columnCount()

### Description

mysql_num_fields(resource `$result`): int|false

Retrieves the number of fields from a query.

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

Returns the number of fields in the result set resource on success or `false` on failure.

### Examples

Example #1 A mysql_num_fields() example

`<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_numfields()

### See Also

- mysql_select_db() - Select a MySQL database
- mysql_query() - Send a MySQL query
- mysql_fetch_field() - Get column information from a result and return as an object
- mysql_num_rows() - Get number of rows in result

# mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Get number of rows in result

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_num_rows()
- mysqli_stmt_num_rows()
- PDOStatement::rowCount()

### Description

mysql_num_rows(resource `$result`): int|false

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

### Return Values

The number of rows in a result set on success or `false` on failure.

### Examples

Example #1 mysql_num_rows() example

`<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>`

### Notes

> Note: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

> Note: For backward compatibility, the following deprecated alias may be used: mysql_numrows()

### See Also

- mysql_affected_rows() - Get number of affected rows in previous MySQL operation
- mysql_connect() - Open a connection to a MySQL Server
- mysql_data_seek() - Move internal result pointer
- mysql_select_db() - Select a MySQL database
- mysql_query() - Send a MySQL query

# mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Open a persistent connection to a MySQL server

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_connect() with `p:` host prefix
- PDO::__construct() with `PDO::ATTR_PERSISTENT` as a driver option

### Description

mysql_pconnect(
string `$server` = ini_get("mysql.default_host"),
string `$username` = ini_get("mysql.default_user"),
string `$password` = ini_get("mysql.default_password"),
int `$client_flags` = 0
): resource

Establishes a persistent connection to a MySQL server.

mysql_pconnect() acts very much like mysql_connect() with two major differences.

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

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

This type of link is therefore called 'persistent'.

### Parameters

`server`
  The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'
`username`
  The username. Default value is the name of the user that owns the server process.
`password`
  The password. Default value is an empty password.
`client_flags`
  The `client_flags` parameter can be a combination of the following constants: 128 (enable `LOAD DATA LOCAL` handling), `MYSQL_CLIENT_SSL`, `MYSQL_CLIENT_COMPRESS`, `MYSQL_CLIENT_IGNORE_SPACE` or `MYSQL_CLIENT_INTERACTIVE`.

### Return Values

Returns a MySQL persistent link identifier on success, or `false` on failure.

### Notes

> Note: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

Warning

Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.

### See Also

- mysql_connect() - Open a connection to a MySQL Server
- Persistent Database Connections

# mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping a server connection or reconnect if there is no connection

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_ping()

### Description

mysql_ping(resource `$link_identifier` = NULL): bool

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

> Note: Automatic reconnection is disabled by default in versions of MySQL >= 5.0.3.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` if the connection to the server MySQL server is working, otherwise `false`.

### Examples

Example #1 A mysql_ping() example

`<?php
set_time_limit(0);
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');
/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);
/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>`

### See Also

- mysql_thread_id() - Return the current thread ID
- mysql_list_processes() - List MySQL processes

# mysql_query

(PHP 4, PHP 5)

mysql_query — Send a MySQL query

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_query()
- PDO::query()

### Description

mysql_query(string `$query`, resource `$link_identifier` = NULL): mixed

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified `link_identifier`.

### Parameters

`query`
  An SQL query The query string should not end with a semicolon. Data inside the query should be properly escaped.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or `false` on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns `true` on success or `false` on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return `false` if the user does not have permission to access the table(s) referenced by the query.

### Examples

Example #1 Invalid Query

The following query is syntactically invalid, so mysql_query() fails and returns `false`.

`<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>`

Example #2 Valid Query

The following query is valid, so mysql_query() returns a resource.

`<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>`

### See Also

- mysql_connect() - Open a connection to a MySQL Server
- mysql_error() - Returns the text of the error message from previous MySQL operation
- mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
- mysql_result() - Get result data
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_unbuffered_query() - Send an SQL query to MySQL without fetching and buffering the result rows

# mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_real_escape_string()
- PDO::quote()

### Description

mysql_real_escape_string(string `$unescaped_string`, resource `$link_identifier` = NULL): string

Escapes special characters in the `unescaped_string`, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: `\x00`, `\n`, `\r`, `\`, `'`, `"` and `\x1a`.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Caution

# Security: the default character set

The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string(). See the concepts section on character sets for more information.

### Parameters

`unescaped_string`
  The string that is to be escaped.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns the escaped string, or `false` on error.

### Errors/Exceptions

Executing this function without a MySQL connection present will also emit `E_WARNING` level PHP errors. Only execute this function with a valid MySQL connection present.

### Examples

Example #1 Simple mysql_real_escape_string() example

`<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>`

Example #2 mysql_real_escape_string() requires a connection example

This example demonstrates what happens if a MySQL connection is not present when calling this function.

`<?php
// We have not connected to MySQL
$lastname = "O'Reilly";
$_lastname = mysql_real_escape_string($lastname);
$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";
var_dump($_lastname);
var_dump($query);
?>`

The above example will output something similar to:

    Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5
    Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5

    bool(false)
    string(41) "SELECT * FROM actors WHERE last_name = ''"

Example #3 An example SQL Injection Attack

`<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
?>`

The query sent to MySQL:

    SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

### Notes

> Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level `E_WARNING` is generated, and `false` is returned. If `link_identifier` isn't defined, the last MySQL connection is used.

> Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

> Note: mysql_real_escape_string() does not escape `%` and `_`. These are wildcards in MySQL if combined with `LIKE`, `GRANT`, or `REVOKE`.

### See Also

- mysql_set_charset() - Sets the client character set
- mysql_client_encoding() - Returns the name of the character set

# mysql_result

(PHP 4, PHP 5)

mysql_result — Get result data

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
- PDOStatement::fetchColumn()

### Description

mysql_result(resource `$result`, int `$row`, mixed `$field` = 0): string

Retrieves the contents of one cell from a MySQL result set.

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

### Parameters

`result`

  The result resource that is being evaluated. This result comes from a call to mysql_query().

`row`
  The row number from the result that's being retrieved. Row numbers start at `0`.
`field`
  The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

### Return Values

The contents of one cell from a MySQL result set on success, or `false` on failure.

### Examples

Example #1 mysql_result() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name
mysql_close($link);
?>`

### Notes

> Note: Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

### See Also

- mysql_fetch_row() - Get a result row as an enumerated array
- mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
- mysql_fetch_assoc() - Fetch a result row as an associative array
- mysql_fetch_object() - Fetch a result row as an object

# mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Select a MySQL database

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_select_db()
- PDO::__construct() (part of dsn)

### Description

mysql_select_db(string `$database_name`, resource `$link_identifier` = NULL): bool

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

### Parameters

`database_name`
  The name of the database that is to be selected.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mysql_select_db() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>`

### Notes

> Note: For backward compatibility, the following deprecated alias may be used: mysql_selectdb()

### See Also

- mysql_connect() - Open a connection to a MySQL Server
- mysql_pconnect() - Open a persistent connection to a MySQL server
- mysql_query() - Send a MySQL query

# mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_set_charset()
- PDO: Add `charset` to the connection string, such as `charset=utf8`

### Description

mysql_set_charset(string `$charset`, resource `$link_identifier` = NULL): bool

Sets the default character set for the current connection.

### Parameters

`charset`
  A valid character set name.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note: This function requires MySQL 5.0.7 or later.

> Note: This is the preferred way to change the charset. Using mysql_query() to set it (such as `SET NAMES utf8`) is not recommended. See the MySQL character set concepts section for more information.

### See Also

- Setting character sets in MySQL
- » List of character sets that MySQL supports
- mysql_client_encoding() - Returns the name of the character set

# mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Get current system status

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_stat()
- PDO::getAttribute() with `attribute` as `PDO::ATTR_SERVER_INFO`

### Description

mysql_stat(resource `$link_identifier` = NULL): string

mysql_stat() returns the current server status.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the `SHOW STATUS` SQL command. If `link_identifier` is invalid, `null` is returned.

### Examples

Example #1 mysql_stat() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$status = explode(' ', mysql_stat($link));
print_r($status);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Uptime: 5380
        [1] => Threads: 2
        [2] => Questions: 1321299
        [3] => Slow queries: 0
        [4] => Opens: 26
        [5] => Flush tables: 1
        [6] => Open tables: 17
        [7] => Queries per second avg: 245.595
    )

Example #2 Alternative mysql_stat() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SHOW STATUS', $link);
while ($row = mysql_fetch_assoc($result)) {
echo $row['Variable_name'] . ' = ' . $row['Value'] . "\n";
}
?>`

The above example will output something similar to:

    back_log = 50
    basedir = /usr/local/
    bdb_cache_size = 8388600
    bdb_log_buffer_size = 32768
    bdb_home = /var/db/mysql/
    bdb_max_lock = 10000
    bdb_logdir =
    bdb_shared_data = OFF
    bdb_tmpdir = /var/tmp/
    ...

### See Also

- mysql_get_server_info() - Get MySQL server info
- mysql_list_processes() - List MySQL processes

# mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Get table name of field

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- SQL Query: `SHOW TABLES`

### Description

mysql_tablename(resource `$result`, int `$i`): string|false

Retrieves the table name from a `result`.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL `SHOW TABLES [FROM db_name] [LIKE 'pattern']` statement instead.

### Parameters

`result`
  A result pointer resource that's returned from mysql_list_tables().
`i`
  The integer index (row/table number)

### Return Values

The name of the table on success or `false` on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

### Examples

Example #1 mysql_tablename() example

`<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
}
mysql_free_result($result);
?>`

### Notes

> Note: The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

### See Also

- mysql_list_tables() - List tables in a MySQL database
- mysql_field_table() - Get name of the table the specified field is in
- mysql_db_name() - Retrieves database name from the call to mysql_list_dbs

# mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Return the current thread ID

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- mysqli_thread_id()

### Description

mysql_thread_id(resource `$link_identifier` = NULL): int|false

Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.

### Parameters

`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

The thread ID on success or `false` on failure.

### Examples

Example #1 mysql_thread_id() example

`<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
printf("current thread id is %d\n", $thread_id);
}
?>`

The above example will output something similar to:

    current thread id is 73

### See Also

- mysql_ping() - Ping a server connection or reconnect if there is no connection
- mysql_list_processes() - List MySQL processes

# mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows

Warning

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

- See: Buffered and Unbuffered queries

### Description

mysql_unbuffered_query(string `$query`, resource `$link_identifier` = NULL): resource

mysql_unbuffered_query() sends the SQL query `query` to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query() while multiple database connections are open, you must specify the optional parameter `link_identifier` to identify which connection you want to use.

### Parameters

`query`
  The SQL query to execute. Data inside the query should be properly escaped.
`link_identifier`

  The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an `E_WARNING` level error is generated.

### Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or `false` on error.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns `true` on success or `false` on error.

### Notes

> Note: The benefits of mysql_unbuffered_query() come at a cost: you cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query(), until all rows are fetched. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL, using the same `link_identifier`.

### See Also

- mysql_query() - Send a MySQL query

## Table of Contents

- mysql_affected_rows — Get number of affected rows in previous MySQL operation
- mysql_client_encoding — Returns the name of the character set
- mysql_close — Close MySQL connection
- mysql_connect — Open a connection to a MySQL Server
- mysql_create_db — Create a MySQL database
- mysql_data_seek — Move internal result pointer
- mysql_db_name — Retrieves database name from the call to mysql_list_dbs
- mysql_db_query — Selects a database and executes a query on it
- mysql_drop_db — Drop (delete) a MySQL database
- mysql_errno — Returns the numerical value of the error message from previous MySQL operation
- mysql_error — Returns the text of the error message from previous MySQL operation
- mysql_escape_string — Escapes a string for use in a mysql_query
- mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
- mysql_fetch_assoc — Fetch a result row as an associative array
- mysql_fetch_field — Get column information from a result and return as an object
- mysql_fetch_lengths — Get the length of each output in a result
- mysql_fetch_object — Fetch a result row as an object
- mysql_fetch_row — Get a result row as an enumerated array
- mysql_field_flags — Get the flags associated with the specified field in a result
- mysql_field_len — Returns the length of the specified field
- mysql_field_name — Get the name of the specified field in a result
- mysql_field_seek — Set result pointer to a specified field offset
- mysql_field_table — Get name of the table the specified field is in
- mysql_field_type — Get the type of the specified field in a result
- mysql_free_result — Free result memory
- mysql_get_client_info — Get MySQL client info
- mysql_get_host_info — Get MySQL host info
- mysql_get_proto_info — Get MySQL protocol info
- mysql_get_server_info — Get MySQL server info
- mysql_info — Get information about the most recent query
- mysql_insert_id — Get the ID generated in the last query
- mysql_list_dbs — List databases available on a MySQL server
- mysql_list_fields — List MySQL table fields
- mysql_list_processes — List MySQL processes
- mysql_list_tables — List tables in a MySQL database
- mysql_num_fields — Get number of fields in result
- mysql_num_rows — Get number of rows in result
- mysql_pconnect — Open a persistent connection to a MySQL server
- mysql_ping — Ping a server connection or reconnect if there is no connection
- mysql_query — Send a MySQL query
- mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
- mysql_result — Get result data
- mysql_select_db — Select a MySQL database
- mysql_set_charset — Sets the client character set
- mysql_stat — Get current system status
- mysql_tablename — Get table name of field
- mysql_thread_id — Return the current thread ID
- mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Changelog
- Predefined Constants
- Examples
  - MySQL extension overview example
- MySQL Functions
  - mysql_affected_rows — Get number of affected rows in previous MySQL operation
  - mysql_client_encoding — Returns the name of the character set
  - mysql_close — Close MySQL connection
  - mysql_connect — Open a connection to a MySQL Server
  - mysql_create_db — Create a MySQL database
  - mysql_data_seek — Move internal result pointer
  - mysql_db_name — Retrieves database name from the call to mysql_list_dbs
  - mysql_db_query — Selects a database and executes a query on it
  - mysql_drop_db — Drop (delete) a MySQL database
  - mysql_errno — Returns the numerical value of the error message from previous MySQL operation
  - mysql_error — Returns the text of the error message from previous MySQL operation
  - mysql_escape_string — Escapes a string for use in a mysql_query
  - mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  - mysql_fetch_assoc — Fetch a result row as an associative array
  - mysql_fetch_field — Get column information from a result and return as an object
  - mysql_fetch_lengths — Get the length of each output in a result
  - mysql_fetch_object — Fetch a result row as an object
  - mysql_fetch_row — Get a result row as an enumerated array
  - mysql_field_flags — Get the flags associated with the specified field in a result
  - mysql_field_len — Returns the length of the specified field
  - mysql_field_name — Get the name of the specified field in a result
  - mysql_field_seek — Set result pointer to a specified field offset
  - mysql_field_table — Get name of the table the specified field is in
  - mysql_field_type — Get the type of the specified field in a result
  - mysql_free_result — Free result memory
  - mysql_get_client_info — Get MySQL client info
  - mysql_get_host_info — Get MySQL host info
  - mysql_get_proto_info — Get MySQL protocol info
  - mysql_get_server_info — Get MySQL server info
  - mysql_info — Get information about the most recent query
  - mysql_insert_id — Get the ID generated in the last query
  - mysql_list_dbs — List databases available on a MySQL server
  - mysql_list_fields — List MySQL table fields
  - mysql_list_processes — List MySQL processes
  - mysql_list_tables — List tables in a MySQL database
  - mysql_num_fields — Get number of fields in result
  - mysql_num_rows — Get number of rows in result
  - mysql_pconnect — Open a persistent connection to a MySQL server
  - mysql_ping — Ping a server connection or reconnect if there is no connection
  - mysql_query — Send a MySQL query
  - mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
  - mysql_result — Get result data
  - mysql_select_db — Select a MySQL database
  - mysql_set_charset — Sets the client character set
  - mysql_stat — Get current system status
  - mysql_tablename — Get table name of field
  - mysql_thread_id — Return the current thread ID
  - mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows

# MySQL Native Driver

# Introduction

MySQL Native Driver is a replacement for the MySQL Client Library (libmysqlclient). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0.

The MySQL database extensions MySQL extension, `mysqli` and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol.

With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library.

MySQL Native Driver is written in C as a PHP extension.

# Overview

What it is not

Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, `mysqli` and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API.

Why use it?

Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library.

The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past.

Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications.

Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory.

> Note: Reporting memory usage
> Because MySQL Native Driver uses the PHP memory management system, its memory usage can be tracked with memory_get_usage(). This is not possible with libmysqlclient because it uses the C function malloc() instead.

Special features

MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below:

- Improved persistent connections
- The special function mysqli_fetch_all()
- Performance statistics calls: mysqli_get_client_stats(), mysqli_get_connection_stats()

The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

MySQL Native Driver also allows for persistent connections when used with the `mysqli` extension.

SSL Support

MySQL Native Driver supports SSL.

Compressed Protocol Support

MySQL Native Driver supports the compressed client server protocol. Extension `ext/mysqli`, if configured to use MySQL Native Driver, can also take advantage of this feature. Note that `PDO_MYSQL` does NOT support compression when used together with mysqlnd.

Named Pipes Support

Named pipes can be used to connect on Windows environments.

# Installation

Installation on Unix

In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code.

For example, to build the MySQL extension, `mysqli` and PDO MYSQL using the MySQL Native Driver, the following command would be given:

    ./configure --with-mysql=mysqlnd \
    --with-mysqli=mysqlnd \
    --with-pdo-mysql=mysqlnd \
    [other options]

Installation on Windows

In the official PHP Windows distributions, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.

SHA-256 Authentication Plugin support

The MySQL Native Driver requires the OpenSSL functionality of PHP to be loaded and enabled to connect to MySQL through accounts that use the MySQL SHA-256 Authentication Plugin. For example, PHP could be configured using:

    ./configure --with-mysql=mysqlnd \
    --with-mysqli=mysqlnd \
    --with-pdo-mysql=mysqlnd \
    --with-openssl
    [other options]

In Autotools, the extended SSL support in `mysqlnd` is enabled implicitly when building together with the `openssl` extension using the --with-openssl configure option. When building without the `openssl` extension, the --with-mysqlnd-ssl configure option can be used to enable extended SSL support explicitly.

### Changelog

Version | Description
--- | ---
8.4.0 | The --with-mysqlnd-ssl Autotools configure option was added to enable the extended SSL support explicitly when building without the `openssl` extension.

# Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQL Native Driver Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mysqlnd.collect_statistics | "1" | `INI_SYSTEM` |
mysqlnd.collect_memory_statistics | "0" | `INI_SYSTEM` |
mysqlnd.debug | "" | `INI_SYSTEM` |
mysqlnd.log_mask | 0 | `INI_ALL` |
mysqlnd.mempool_default_size | 16000 | `INI_ALL` |
mysqlnd.net_read_timeout | "86400" | `INI_ALL` | Before PHP 7.2.0 the default value was "31536000" and the changeability was `INI_SYSTEM`
mysqlnd.net_cmd_buffer_size | "4096" | `INI_SYSTEM` |
mysqlnd.net_read_buffer_size | "32768" | `INI_SYSTEM` |
mysqlnd.sha256_server_public_key | "" | `INI_PERDIR` |
mysqlnd.trace_alloc | "" | `INI_SYSTEM` |
mysqlnd.fetch_data_copy | 0 | `INI_ALL` | Removed as of PHP 8.1.0

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mysqlnd.collect_statistics` bool
  Enables the collection of various client statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), and are shown in `mysqlnd` section of the output of the phpinfo() function as well. This configuration setting enables all MySQL Native Driver statistics except those relating to memory management.
`mysqlnd.collect_memory_statistics` bool
  Enable the collection of various memory statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), and are shown in `mysqlnd` section of the output of the phpinfo() function as well. This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics.
`mysqlnd.debug` string
  Records communication from all extensions using `mysqlnd` to the specified log file. The format of the directive is `mysqlnd.debug = "option1[,parameter_option1][:option2[,parameter_option2]]"`. The options for the format string are as follows:
  - A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash.
  - a[,file] - Appends trace output to the specified file.
  - d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros.
  - f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected.
  - F - Marks each debugger output line with the name of the source file containing the macro causing the output.
  - i - Marks each debugger output line with the PID of the current process.
  - L - Marks each debugger output line with the name of the source file line number of the macro causing the output.
  - n - Marks each debugger output line with the current function nesting depth
  - o[,file] - Similar to a[,file] but overwrites old file, and does not append.
  - O[,file] - Similar to A[,file] but overwrites old file, and does not append.
  - t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200.
  - x - This option activates profiling.
  - m - Trace memory allocation and deallocation related calls.
  Example:

      d:t:x:O,/tmp/mysqlnd.trace

  > Note: This feature is only available with a debug build of PHP.

`mysqlnd.log_mask` int
  Defines which queries will be logged. The default 0, which disables logging. Define using an integer, and not with PHP constants. For example, a value of 48 (16 + 32) will log slow queries which either use 'no good index' (SERVER_QUERY_NO_GOOD_INDEX_USED = 16) or no index at all (SERVER_QUERY_NO_INDEX_USED = 32). A value of 2043 (1 + 2 + 8 + ... + 1024) will log all slow query types. The types are as follows: SERVER_STATUS_IN_TRANS=1, SERVER_STATUS_AUTOCOMMIT=2, SERVER_MORE_RESULTS_EXISTS=8, SERVER_QUERY_NO_GOOD_INDEX_USED=16, SERVER_QUERY_NO_INDEX_USED=32, SERVER_STATUS_CURSOR_EXISTS=64, SERVER_STATUS_LAST_ROW_SENT=128, SERVER_STATUS_DB_DROPPED=256, SERVER_STATUS_NO_BACKSLASH_ESCAPES=512, and SERVER_QUERY_WAS_SLOW=1024.
`mysqlnd.mempool_default_size` int
  Default size of the mysqlnd memory pool, which is used by result sets.
`mysqlnd.net_read_timeout` int
  `mysqlnd` and the MySQL Client Library, `libmysqlclient` use different networking APIs. `mysqlnd` uses PHP streams, whereas `libmysqlclient` uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, `default_socket_timeout`. This default applies to all streams that set no other timeout value. `mysqlnd` does not set any other value and therefore connections of long running queries can be disconnected after `default_socket_timeout` seconds resulting in an error message 2006 - MySQL Server has gone away. The MySQL Client Library sets a default timeout of 24 * 3600 seconds (1 day) and waits for other timeouts to occur, such as TCP/IP timeouts. `mysqlnd` now uses the same very long timeout. The value is configurable through a new php.ini setting: `mysqlnd.net_read_timeout`. `mysqlnd.net_read_timeout` gets used by any extension (`ext/mysql`, `ext/mysqli`, `PDO_MySQL`) that uses `mysqlnd`. `mysqlnd` tells PHP Streams to use `mysqlnd.net_read_timeout`. Please note that there may be subtle differences between `MYSQL_OPT_READ_TIMEOUT` from the MySQL Client Library and PHP Streams, for example `MYSQL_OPT_READ_TIMEOUT` is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt.
`mysqlnd.net_cmd_buffer_size` int
  `mysqlnd` allocates an internal command/network buffer of `mysqlnd.net_cmd_buffer_size` (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, `COM_QUERY` (normal query), does not fit into the buffer, `mysqlnd` will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, `command_buffer_too_small` will be incremented by one. If `mysqlnd` has to grow the buffer beyond its initial size of `mysqlnd.net_cmd_buffer_size` bytes for almost every connection, you should consider increasing the default size to avoid re-allocations. The default buffer size is 4096 bytes, which is the smallest value possible. The value can also be set using `mysqli_options(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size)`.
`mysqlnd.net_read_buffer_size` int
  Maximum read chunk size in bytes when reading the body of a MySQL command packet. The MySQL client server protocol encapsulates all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. `mysqlnd` reads the body in chunks of `MIN(header.size, mysqlnd.net_read_buffer_size)` bytes. If a packet body is larger than `mysqlnd.net_read_buffer_size` bytes, `mysqlnd` has to call `read()` multiple times. The value can also be set using `mysqli_options(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size)`.
`mysqlnd.sha256_server_public_key` string
  SHA-256 Authentication Plugin related. File with the MySQL server public RSA key. Clients can either omit setting a public RSA key, specify the key through this PHP configuration setting or set the key at runtime using mysqli_options(). If not public RSA key file is given by the client, then the key will be exchanged as part of the standard SHA-256 Authentication Plugin authentication procedure.
`mysqlnd.trace_alloc` string
`mysqlnd.fetch_data_copy` int
  Enforce copying result sets from the internal result set buffers into PHP variables instead of using the default reference and copy-on-write logic. Please, see the memory management implementation notes for further details. Copying result sets instead of having PHP variables reference them allows releasing the memory occupied for the PHP variables earlier. Depending on the user API code, the actual database quries and the size of their result sets this may reduce the memory footprint of mysqlnd. Do not set if using PDO_MySQL. PDO_MySQL has not yet been updated to support the new fetch mode.

  > Note: Removed as of PHP 8.1.0

# Incompatibilities

MySQL Native Driver is in most cases compatible with MySQL Client Library (`libmysql`). This section documents incompatibilities between these libraries.

- Values of `bit` data type are returned as binary strings (e.g. "\0" or "\x1F") with `libmysql` and as decimal strings (e.g. "0" or "31") with `mysqlnd`. If you want the code to be compatible with both libraries then always return bit fields as numbers from MySQL with a query like this: `SELECT bit + 0 FROM table`.

# Persistent Connections

Using Persistent Connections

If `mysqli` is used with `mysqlnd`, when a persistent connection is created it generates a `COM_CHANGE_USER` (`mysql_change_user()`) call on the server. This ensures that re-authentication of the connection takes place.

As there is some overhead associated with the `COM_CHANGE_USER` call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a `COM_PING` (`mysql_ping`) call to simply test the connection is reusable.

Generation of `COM_CHANGE_USER` can be switched off with the compile flag `MYSQLI_NO_CHANGE_USER_ON_PCONNECT`. For example:

    shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" ./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql/bin/mysql_config --enable-debug && make clean && make -j6

Or alternatively:

    shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT"
    shell# configure --whatever-option
    shell# make clean
    shell# make

Note that only `mysqli` on `mysqlnd` uses `COM_CHANGE_USER`. Other extension-driver combinations use `COM_PING` on initial use of a persistent connection.

# Statistics

MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of two main types:

- Client statistics
- Connection statistics

When using the mysqli extension, these statistics can be obtained through two API calls:

- mysqli_get_client_stats()
- mysqli_get_connection_stats()

> Note: Statistics are aggregated among all extensions that use the MySQL Native Driver. For example, if the mysqli extension and the PDO MySQL driver are both set-up to use MySQLnd, then function calls from mysqli and method calls from PDO will affect the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic.

## Retrieving statistics

Client statistics can be retrieved by calling the mysqli_get_client_stats() function.

Connection statistics can be retrieved by calling the mysqli_get_connection_stats() function.

Both functions return an associative array, where the name of a statistic is the key for the corresponding statistical data.

## MySQL Native Driver Statistics

Most statistics are associated to a connection, but some are associated to the process in which case this will be mentioned.

The following statistics are produced by the MySQL Native Driver:

Network Related Statistics
`bytes_sent`
  Number of bytes sent from PHP to the MySQL server.
`bytes_received`
  Number of bytes received from the MySQL server.
`packets_sent`
  Number of packets sent by the MySQL Client Server protocol.
`packets_received`
  Number of packets received from the MySQL Client Server protocol.
`protocol_overhead_in`
  MySQL Client Server protocol overhead in bytes for incoming traffic. Currently only the Packet Header (4 bytes) is considered as overhead. `protocol_overhead_in = packets_received * 4`
`protocol_overhead_out`
  MySQL Client Server protocol overhead in bytes for outgoing traffic. Currently only the Packet Header (4 bytes) is considered as overhead. `protocol_overhead_out = packets_received * 4`
`bytes_received_ok_packet`
  Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_ok`
  Number of MySQL Client Server protocol OK packets received.
`bytes_received_eof_packet`
  Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_eof`
  Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message.
`bytes_received_rset_header_packet`
  Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (`LOAD LOCAL INFILE`, `INSERT`, `UPDATE`, `SELECT`, error message).

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_rset_header`
  Number of MySQL Client Server protocol result set header packets.
`bytes_received_rset_field_meta_packet`
  Total size in bytes of MySQL Client Server protocol result set metadata (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_rset_field_meta`
  Number of MySQL Client Server protocol result set metadata (field information) packets.
`bytes_received_rset_row_packet`
  Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an EOF packet. One can compute the number of error and EOF packets by subtracting `rows_fetched_from_server_normal` and `rows_fetched_from_server_ps` from `bytes_received_rset_row_packet`.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_rset_row`
  Number of MySQL Client Server protocol result set row data packets.
`bytes_received_prepare_response_packet`
  Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_prepare_response`
  Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets).
`bytes_received_change_user_packet`
  Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF.

  > Note: The total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).

`packets_received_change_user`
  Number of MySQL Client Server protocol COM_CHANGE_USER packets.
`packets_sent_command`
  Number of MySQL Client Server protocol commands sent from PHP to MySQL. There is no way to know which specific commands and how many of them have been sent.
`bytes_received_real_data_normal`
  Number of bytes of payload fetched by the PHP client from `mysqlnd` using the text protocol. This is the size of the actual data contained in result sets that do not originate from prepared statements and which have been fetched by the PHP client. Note that although a full result set may have been pulled from MySQL by `mysqlnd`, this statistic only counts actual data pulled from `mysqlnd` by the PHP client.

  An example of a code sequence that will increase the value is as follows:

      $mysqli = new mysqli();
      $res = $mysqli->query("SELECT 'abc'");
      $res->fetch_assoc();
      $res->close();

  Every fetch operation will increase the value.

  However, the statistic will not be increased if the result set is only buffered on the client, but not fetched, such as in the following example:

      $mysqli = new mysqli();
      $res = $mysqli->query("SELECT 'abc'");
      $res->close();

`bytes_received_real_data_ps`
  Number of bytes of the payload fetched by the PHP client from `mysqlnd` using the prepared statement protocol. This is the size of the actual data contained in result sets that originate from prepared statements and which have been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. Note that although a full result set may have been pulled from MySQL by `mysqlnd`, this statistic only counts actual data pulled from `mysqlnd` by the PHP client. See also `bytes_received_real_data_normal`.

Result Set Related Statistics
`result_set_queries`
  Number of queries that have generated a result set. Examples of queries that generate a result set: `SELECT`, `SHOW`. The statistic will not be incremented if there is an error reading the result set header packet from the line.

  > Note: This statistic can be used as an indirect measure for the number of queries PHP has sent to MySQL. This could help identifying a client that causes a high database load.

`non_result_set_queries`
  Number of queries that did not generate a result set. Examples of queries that do not generate a result set: `INSERT`, `UPDATE`, `LOAD DATA`. The statistic will not be incremented if there is an error reading the result set header packet from the line.

  > Note: This statistic can be used as an indirect measure for the number of queries PHP has sent to MySQL. This could help identifying a client that causes a high database load.

`no_index_used`
  Number of queries that have generated a result set but did not use an index. (See also the mysqld start option `--log-queries-not-using-indexes`).

  > Note: Those queries can be reported via an exception by calling `mysqli_report(MYSQLI_REPORT_INDEX);`. It is possible to have them be reported via a warning instead by calling `mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT);`.

`bad_index_used`
  Number of queries that have generated a result set and did not use a good index. (See also the mysqld start option `--log-slow-queries`).

  > Note: Those queries can be reported via an exception by calling `mysqli_report(MYSQLI_REPORT_INDEX);`. It is possible to have them be reported via a warning instead by calling `mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT);`.

`slow_queries`
  SQL statements that took more than `long_query_time` seconds to execute and required at least `min_examined_row_limit` rows to be examined.
  Caution

  Not reported through mysqli_report().

`buffered_sets`
  Number of buffered result sets returned by normal (i.e. not via a prepared statement) queries.

  Examples of API calls that will buffer result sets on the client: mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result()

`unbuffered_sets`
  Number of unbuffered result sets returned by normal (i.e. not via a prepared statement) queries.

  Examples of API calls that will not buffer result sets on the client: mysqli_use_result()

`ps_buffered_sets`
  Number of buffered result sets returned by prepared statements.

  Examples of API calls that will buffer result sets on the client: mysqli_stmt_store_result()

`ps_unbuffered_sets`
  Number of unbuffered result sets returned by prepared statements. By default prepared statements are unbuffered, thus most prepared statements will be accounted in this statistic.
`flushed_normal_sets`
  Number of result sets returned by normal (i.e. not via a prepared statement) queries with unread data that have been silently flushed.

  > Note: Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also `rows_skipped_normal`, `rows_skipped_ps`.

  > Some possible causes for an implicit flush:

  > - Faulty client application
  > - Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed
  > - Client application has stopped unexpectedly

`flushed_ps_sets`
  Number of result sets from prepared statements with unread data that have been silently flushed.

  > Note: Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also `rows_skipped_normal`, `rows_skipped_ps`.

  > Some possible causes for an implicit flush:

  > - Faulty client application
  > - Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed
  > - Client application has stopped unexpectedly

`ps_prepared_never_executed`
  Number of statements prepared but never executed.
`ps_prepared_once_executed`
  Number of prepared statements executed only once.
`rows_fetched_from_server_normal`
`rows_fetched_from_server_ps`
  Total number of result set rows fetched from the server. This includes the rows which were not read by the client but had been implicitly fetched due to flushed unbuffered result sets. See also `packets_received_rset_row`.
`rows_buffered_from_client_normal`
  Total number of buffered rows originating from a normal query. This is the number of rows that have been fetched from MySQL and buffered on client.

  Examples of queries that will buffer results:

  - mysqli_query()
  - mysqli_store_result()
`rows_buffered_from_client_ps`
  Same as `rows_buffered_from_client_normal` but for prepared statements.
`rows_fetched_from_client_normal_buffered`
  Total number of rows fetched by the client from a buffered result set created by a normal query.
`rows_fetched_from_client_ps_buffered`
  Total number of rows fetched by the client from a buffered result set created by a prepared statement.
`rows_fetched_from_client_normal_unbuffered`
  Total number of rows fetched by the client from an unbuffered result set created by a normal query.
`rows_fetched_from_client_ps_unbuffered`
  Total number of rows fetched by the client from an unbuffered result set created by a prepared statement.
`rows_fetched_from_client_ps_cursor`
  Total number of rows fetch by the client from a cursor created by a prepared statement.
`rows_skipped_normal`
`rows_skipped_ps`
  Reserved for future use (currently not supported).
`copy_on_write_saved`
`copy_on_write_performed`
  This is a process level scope statistic. With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If the data are not changed, the fetched data is kept only once in memory. However, any modification to the data will require mysqlnd to perform a copy-on-write operation.
`explicit_free_result`
`implicit_free_result`
  This is a connection and process level scope statistic. Total number of freed result sets.
`proto_text_fetched_null`
  Total number of columns of type `MYSQL_TYPE_NULL` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_null`
  Total number of columns of type `MYSQL_TYPE_NULL` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_bit`
  Total number of columns of type `MYSQL_TYPE_BIT` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_bit`
  Total number of columns of type `MYSQL_TYPE_BIT` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_tinyint`
  Total number of columns of type `MYSQL_TYPE_TINY` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_tinyint`
  Total number of columns of type `MYSQL_TYPE_TINY` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_short`
  Total number of columns of type `MYSQL_TYPE_SHORT` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_short`
  Total number of columns of type `MYSQL_TYPE_SHORT` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_int24`
  Total number of columns of type `MYSQL_TYPE_INT24` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_int24`
  Total number of columns of type `MYSQL_TYPE_INT24` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_int`
  Total number of columns of type `MYSQL_TYPE_LONG` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_int`
  Total number of columns of type `MYSQL_TYPE_LONG` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_bigint`
  Total number of columns of type `MYSQL_TYPE_LONGLONG` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_bigint`
  Total number of columns of type `MYSQL_TYPE_LONGLONG` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_decimal`
  Total number of columns of type `MYSQL_TYPE_DECIMAL`, or `MYSQL_TYPE_NEWDECIMAL` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_decimal`
  Total number of columns of type `MYSQL_TYPE_DECIMAL`, or `MYSQL_TYPE_NEWDECIMAL` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_float`
  Total number of columns of type `MYSQL_TYPE_FLOAT` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_float`
  Total number of columns of type `MYSQL_TYPE_FLOAT` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_double`
  Total number of columns of type `MYSQL_TYPE_DOUBLE` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_double`
  Total number of columns of type `MYSQL_TYPE_DOUBLE` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_date`
  Total number of columns of type `MYSQL_TYPE_DATE`, or `MYSQL_TYPE_NEWDATE` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_date`
  Total number of columns of type `MYSQL_TYPE_DATE`, or `MYSQL_TYPE_NEWDATE` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_year`
  Total number of columns of type `MYSQL_TYPE_YEAR` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_year`
  Total number of columns of type `MYSQL_TYPE_YEAR` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_time`
  Total number of columns of type `MYSQL_TYPE_TIME` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_time`
  Total number of columns of type `MYSQL_TYPE_TIME` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_datetime`
  Total number of columns of type `MYSQL_TYPE_DATETIME` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_datetime`
  Total number of columns of type `MYSQL_TYPE_DATETIME` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_timestamp`
  Total number of columns of type `MYSQL_TYPE_TIMESTAMP` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_timestamp`
  Total number of columns of type `MYSQL_TYPE_TIMESTAMP` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_string`
  Total number of columns of type `MYSQL_TYPE_STRING`, `MYSQL_TYPE_VARSTRING`, or `MYSQL_TYPE_VARCHAR` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_string`
  Total number of columns of type `MYSQL_TYPE_STRING`, `MYSQL_TYPE_VARSTRING`, or `MYSQL_TYPE_VARCHAR` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_blob`
  Total number of columns of type `MYSQL_TYPE_TINY_BLOB`, `MYSQL_TYPE_MEDIUM_BLOB`, `MYSQL_TYPE_LONG_BLOB`, or `MYSQL_TYPE_BLOB` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_blob`
  Total number of columns of type `MYSQL_TYPE_TINY_BLOB`, `MYSQL_TYPE_MEDIUM_BLOB`, `MYSQL_TYPE_LONG_BLOB`, or `MYSQL_TYPE_BLOB` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_enum`
  Total number of columns of type `MYSQL_TYPE_ENUM` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_enum`
  Total number of columns of type `MYSQL_TYPE_ENUM` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_set`
  Total number of columns of type `MYSQL_TYPE_SET` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_set`
  Total number of columns of type `MYSQL_TYPE_SET` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_geometry`
  Total number of columns of type `MYSQL_TYPE_GEOMETRY` fetched from a normal query (MySQL text protocol).
`proto_binary_fetched_geometry`
  Total number of columns of type `MYSQL_TYPE_GEOMETRY` fetched from a prepared statement (MySQL binary protocol).
`proto_text_fetched_other`
  Total number of columns of types `MYSQL_TYPE_*` not listed previously fetched from a normal query (MySQL text protocol).

  > Note: In theory, this should always be `0`.

`proto_binary_fetched_other`
  Total number of columns of type `MYSQL_TYPE_*` not listed previously fetched from a prepared statement (MySQL binary protocol).

  > Note: In theory, this should always be `0`.

Connection Related Statistics
`connect_success`
  Total number of successful connection attempts.

  > Note: `connect_success` holds the sum of successful persistent and non-persistent connection attempts. Therefore, the number of successful non-persistent connection attempts is `connect_success - pconnect_success`.

`pconnect_success`
  Total number of successful persistent connection attempts.
`connect_failure`
  Total number of failed connection attempts.
`reconnect`
  This is a process level scope statistic.
`active_connections`
  This is a process level scope statistic. Total number of active persistent and non-persistent connections.

  > Note: The total number of active non-persistent connections is `active_connections - active_persistent_connections`.

`active_persistent_connections`
  This is a process level scope statistic. Total number of active persistent connections.
`explicit_close`
  Total number of explicitly closed connections.

  Example #1 Examples of code snippets that cause an explicit close

  -     $link = new mysqli(/* ... */);
        $link->close(/* ... */);

  -     $link = new mysqli(/* ... */);
        $link->connect(/* ... */);

`implicit_close`
  Total number of implicitly closed connections.

  Example #2 Examples of code snippets that cause an implicit close

  -     $link = new mysqli(/* ... */);
        $link->real_connect(/* ... */);

  - `unset($link)`
  - Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options
  - Persistent connection: ping/change_user fails and ext/mysqli closes the connection
  - End of script execution: close connections that have not been closed by the user
`disconnect_close`
  Connection failures indicated by the C API call `mysql_real_connect` during an attempt to establish a connection.
`in_middle_of_command_close`
  This is a process level scope statistic. A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA).
  Warning

  Unless asynchronous queries are used, this should only happen if the PHP application terminated unexpectedly, and PHP shuts down the connection automatically.

`init_command_executed_count`
  Total number of init command executions. For example: `mysqli_options(MYSQLI_INIT_COMMAND , $value)`. The number of successful executions is `init_command_executed_count - init_command_failed_count`.
`init_command_failed_count`
  Total number of failed init commands.

`COM_*` Command Related Statistics
`com_quit`
`com_init_db`
`com_query`
`com_field_list`
`com_create_db`
`com_drop_db`
`com_refresh`
`com_shutdown`
`com_statistics`
`com_process_info`
`com_connect`
`com_process_kill`
`com_debug`
`com_ping`
`com_time`
`com_delayed_insert`
`com_change_user`
`com_binlog_dump`
`com_table_dump`
`com_connect_out`
`com_register_slave`
`com_stmt_prepare`
`com_stmt_execute`
`com_stmt_send_long_data`
`com_stmt_close`
`com_stmt_reset`
`com_stmt_set_option`
`com_stmt_fetch`
`com_daemon`
  Total number of attempts to send a certain `COM_*` command from PHP to MySQL. The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet.
  Caution

  If MySQLnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure MySQLnd emits a PHP warning Error while sending %s packet. PID=%d.

  Example #3 Usage examples

  - Check if PHP sends certain commands to MySQL, for example, check if a client sends `COM_PROCESS_KILL`
  - Calculate the average number of prepared statement executions by comparing `COM_EXECUTE` with `COM_PREPARE`
  - Check if PHP has run any non-prepared SQL statements by checking if `COM_QUERY` is zero
  - Identify PHP scripts that run an excessive number of SQL statements by checking `COM_QUERY` and `COM_EXECUTE`

Miscellaneous Statistics
`explicit_stmt_close`
`implicit_stmt_close`
  This is a process level scope statistic. Total number of closed prepared statements.

  > Note: A prepared statement is always explicitly closed. The only time it's closed implicitly is when preparing it fails.

`mem_emalloc_count`
`mem_emalloc_ammount`
`mem_ecalloc_count`
`mem_ecalloc_ammount`
`mem_realloc_count`
`mem_realloc_ammount`
`mem_efree_count`
`mem_malloc_count`
`mem_malloc_ammount`
`mem_calloc_count`
`mem_calloc_ammount`
`mem_ealloc_count`
`mem_ealloc_ammount`
`mem_free_count`
  This is a process level scope statistic. Memory management calls.
`command_buffer_too_small`
  Number of network command buffer extensions while sending commands from PHP to MySQL. MySQLnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size bytes for every connection. If a MySQL Client Server protocol command, e.g. `COM_QUERY` (normal query), does not fit into the buffer, MySQLnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection `command_buffer_too_small` will be incremented by one. If MySQLnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, considerations to increase the default size should be made to avoid re-allocations.
`connection_reused`
  The total number of times a persistent connection has been reused.

# Notes

This section provides a collection of miscellaneous notes on MySQL Native Driver usage.

- Using `mysqlnd` means using PHP streams for underlying connectivity. For `mysqlnd`, the PHP streams documentation (Streams) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.

# Memory management

Introduction

The MySQL Native Driver manages memory different than the MySQL Client Library. The libraries differ in the way memory is allocated and released, how memory is allocated in chunks while reading results from MySQL, which debug and development options exist, and how results read from MySQL are linked to PHP user variables.

The following notes are intended as an introduction and summary to users interested at understanding the MySQL Native Driver at the C code level.

Memory management functions used

All memory allocation and deallocation is done using the PHP memory management functions. Therefore, the memory consumption of mysqlnd can be tracked using PHP API calls, such as memory_get_usage(). Because memory is allocated and released using the PHP memory management, the changes may not immediately become visible at the operating system level. The PHP memory management acts as a proxy which may delay releasing memory towards the system. Due to this, comparing the memory usage of the MySQL Native Driver and the MySQL Client Library is difficult. The MySQL Client Library is using the operating system memory management calls directly, hence the effects can be observed immediately at the operating system level.

Any memory limit enforced by PHP also affects the MySQL Native Driver. This may cause out of memory errors when fetching large result sets that exceed the size of the remaining memory made available by PHP. Because the MySQL Client Library is not using PHP memory management functions, it does not comply to any PHP memory limit set. If using the MySQL Client Library, depending on the deployment model, the memory footprint of the PHP process may grow beyond the PHP memory limit. But also PHP scripts may be able to process larger result sets as parts of the memory allocated to hold the result sets are beyond the control of the PHP engine.

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier.

Handling of result sets

The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets. Unbuffered result sets are transferred row-by-row from MySQL to the client as the client iterates over the results. Buffered results are fetched in their entirety by the client library before passing them on to the client.

The MySQL Native Driver is using PHP Streams for the network communication with the MySQL Server. Results sent by MySQL are fetched from the PHP Streams network buffers into the result buffer of mysqlnd. The result buffer is made of zvals. In a second step the results are made available to the PHP script. This final transfer from the result buffer into PHP variables impacts the memory consumption and is mostly noticeable when using buffered result sets.

By default the MySQL Native Driver tries to avoid holding buffered results twice in memory. Results are kept only once in the internal result buffers and their zvals. When results are fetched into PHP variables by the PHP script, the variables will reference the internal result buffers. Database query results are not copied and kept in memory only once. Should the user modify the contents of a variable holding the database results a copy-on-write must be performed to avoid changing the referenced internal result buffer. The contents of the buffer must not be modified because the user may decide to read the result set a second time. The copy-on-write mechanism is implemented using an additional reference management list and the use of standard zval reference counters. Copy-on-write must also be done if the user reads a result set into PHP variables and frees a result set before the variables are unset.

Generally speaking, this pattern works well for scripts that read a result set once and do not modify variables holding results. Its major drawback is the memory overhead caused by the additional reference management which comes primarily from the fact that user variables holding results cannot be entirely released until the mysqlnd reference management stops referencing them. The MySQL Native driver removes the reference to the user variables when the result set is freed or a copy-on-write is performed. An observer will see the total memory consumption grow until the result set is released. Use the statistics to check whether a script does release result sets explicitly or the driver does implicit releases and thus memory is used for a time longer than necessary. Statistics also help to see how many copy-on-write operations happened.

A PHP script reading many small rows of a buffered result set using a code snippet equal or equivalent to `while ($row = $res->fetch_assoc()) { ... }` may optimize memory consumption by requesting copies instead of references. Albeit requesting copies means keeping results twice in memory, it allows PHP to free the copy contained in `$row` as the result set is being iterated and prior to releasing the result set itself. On a loaded server optimizing peak memory usage may help improving the overall system performance although for an individual script the copy approach may be slower due to additional allocations and memory copy operations.

Monitoring and debugging

There are multiple ways of tracking the memory usage of the MySQL Native Driver. If the goal is to get a quick high level overview or to verify the memory efficiency of PHP scripts, then check the statistics collected by the library. The statistics allow you, for example, to catch SQL statements which generate more results than are processed by a PHP script.

The debug trace log can be configured to record memory management calls. This helps to see when memory is allocated or free'd. However, the size of the requested memory chunks may not be listed.

Some, recent versions of the MySQL Native Driver feature the emulation of random out of memory situations. This feature is meant to be used by the C developers of the library or mysqlnd plugin authors only. Please, search the source code for corresponding PHP configuration settings and further details. The feature is considered private and may be modified at any time without prior notice.

# MySQL Native Driver Plugin API

## Table of Contents

- A comparison of mysqlnd plugins with MySQL Proxy
- Obtaining the mysqlnd plugin API
- MySQL Native Driver Plugin Architecture
- The mysqlnd plugin API
- Getting started building a mysqlnd plugin

The MySQL Native Driver Plugin API is a feature of MySQL Native Driver, or `mysqlnd`. `Mysqlnd` plugins operate in the layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates on a layer between any MySQL client application, for example, a PHP application and, the MySQL server. `Mysqlnd` plugins can undertake typical MySQL Proxy tasks such as load balancing, monitoring and performance optimizations. Due to the different architecture and location, `mysqlnd` plugins do not have some of MySQL Proxy's disadvantages. For example, with plugins, there is no single point of failure, no dedicated proxy server to deploy, and no new programming language to learn (Lua).

A `mysqlnd` plugin can be thought of as an extension to `mysqlnd`. Plugins can intercept the majority of `mysqlnd` functions. The `mysqlnd` functions are called by the PHP MySQL extensions such as `ext/mysql`, `ext/mysqli`, and `PDO_MYSQL`. As a result, it is possible for a `mysqlnd` plugin to intercept all calls made to these extensions from the client application.

Internal `mysqlnd` function calls can also be intercepted, or replaced. There are no restrictions on manipulating `mysqlnd` internal function tables. It is possible to set things up so that when certain `mysqlnd` functions are called by the extensions that use `mysqlnd`, the call is directed to the appropriate function in the `mysqlnd` plugin. The ability to manipulate `mysqlnd` internal function tables in this way allows maximum flexibility for plugins.

`Mysqlnd` plugins are in fact PHP Extensions, written in C, that use the `mysqlnd` plugin API (which is built into MySQL Native Driver, `mysqlnd`). Plugins can be made 100% transparent to PHP applications. No application changes are needed because plugins operate on a different layer. The `mysqlnd` plugin can be thought of as operating in a layer below `mysqlnd`.

The following list represents some possible applications of `mysqlnd` plugins.

- Load Balancing
  - Read/Write Splitting. An example of this is the PECL/mysqlnd_ms (Master Slave) extension. This extension splits read/write queries for a replication setup.
  - Failover
  - Round-Robin, least loaded
- Monitoring
  - Query Logging
  - Query Analysis
  - Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. This extension inspects queries and executes only those that are allowed according to a ruleset.
- Performance
  - Caching. An example of this is the PECL/mysqlnd_qc (Query Cache) extension.
  - Throttling
  - Sharding. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. This extension will attempt to split a SELECT statement into n-parts, using SELECT ... LIMIT part_1, SELECT LIMIT part_n. It sends the queries to distinct MySQL servers and merges the result at the client.

MySQL Native Driver Plugins Available

There are a number of mysqlnd plugins already available. These include:

- PECL/mysqlnd_mc - Multi Connect plugin.
- PECL/mysqlnd_ms - Master Slave plugin.
- PECL/mysqlnd_qc - Query Cache plugin.
- PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin.
- PECL/mysqlnd_sip - SQL Injection Protection plugin.
- PECL/mysqlnd_uh - User Handler plugin.

## A comparison of mysqlnd plugins with MySQL Proxy

`Mysqlnd` plugins and MySQL Proxy are different technologies using different approaches. Both are valid tools for solving a variety of common tasks such as load balancing, monitoring, and performance enhancements. An important difference is that MySQL Proxy works with all MySQL clients, whereas `mysqlnd` plugins are specific to PHP applications.

As a PHP Extension, a `mysqlnd` plugin gets installed on the PHP application server, along with the rest of PHP. MySQL Proxy can either be run on the PHP application server or can be installed on a dedicated machine to handle multiple PHP application servers.

Deploying MySQL Proxy on the application server has two advantages:

1. No single point of failure
2. Easy to scale out (horizontal scale out, scale by client)

MySQL Proxy (and `mysqlnd` plugins) can solve problems easily which otherwise would have required changes to existing applications.

However, MySQL Proxy does have some disadvantages:

- MySQL Proxy is a new component and technology to master and deploy.
- MySQL Proxy requires knowledge of the Lua scripting language.

MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A `mysqlnd` plugin can be written in C. It is also possible to write plugins in PHP using » PECL/mysqlnd_uh.

MySQL Proxy runs as a daemon - a background process. MySQL Proxy can recall earlier decisions, as all state can be retained. However, a `mysqlnd` plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can also share one-time computed results among multiple application servers. A `mysqlnd` plugin would need to store data in a persistent medium to be able to do this. Another daemon would need to be used for this purpose, such as Memcache. This gives MySQL Proxy an advantage in this case.

MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to those that can be achieved by manipulating the communication protocol. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well.

`Mysqlnd` plugins work on top of the C API, which mirrors the `libmysqlclient` client. This C API is basically a wrapper around the MySQL Client Server protocol, or wire protocol, as it is sometimes called. You can intercept all C API calls. PHP makes use of the C API, therefore you can hook all PHP calls, without the need to program at the level of the wire protocol.

`Mysqlnd` implements the wire protocol. Plugins can therefore parse, reverse engineer, manipulate and even replace the communication protocol. However, this is usually not required.

As plugins allow you to create implementations that use two levels (C API and wire protocol), they have greater flexibility than MySQL Proxy. If a `mysqlnd` plugin is implemented using the C API, any subsequent changes to the wire protocol do not require changes to the plugin itself.

## Obtaining the mysqlnd plugin API

The `mysqlnd` plugin API is simply part of the MySQL Native Driver PHP extension, `ext/mysqlnd`. Development started on the `mysqlnd` plugin API in December 2009. It is developed as part of the PHP source repository, and as such is available to the public either via Git, or through source snapshot downloads.

Plugin developers can determine the `mysqlnd` version through accessing `MYSQLND_VERSION`, which is a string of the format mysqlnd 8.3.17, or through `MYSQLND_VERSION_ID`, which is an integer such as 50007. Developers can calculate the version number as follows:

MYSQLND_VERSION_ID calculation table
Version (part) | Example
--- | ---
Major*10000 | 5*10000 = 50000
Minor*100 | 0*100 = 0
Patch | 7 = 7
MYSQLND_VERSION_ID | 50007

During development, developers should refer to the `mysqlnd` version number for compatibility and version tests, as several iterations of `mysqlnd` could occur during the lifetime of a PHP development branch with a single PHP version number.

## MySQL Native Driver Plugin Architecture

This section provides an overview of the `mysqlnd` plugin architecture.

MySQL Native Driver Overview

Before developing `mysqlnd` plugins, it is useful to know a little of how `mysqlnd` itself is organized. `Mysqlnd` consists of the following modules:

The mysqlnd organization chart, per module
Modules Statistics | mysqlnd_statistics.c
--- | ---
Connection | mysqlnd.c
Resultset | mysqlnd_result.c
Resultset Metadata | mysqlnd_result_meta.c
Statement | mysqlnd_ps.c
Network | mysqlnd_net.c
Wire protocol | mysqlnd_wireprotocol.c

C Object-Oriented Paradigm

At the code level, `mysqlnd` uses a C pattern for implementing object orientation.

In C you use a `struct` to represent an object. Members of the struct represent object properties. Struct members pointing to functions represent methods.

Unlike with other languages such as C++ or Java, there are no fixed rules on inheritance in the C object-oriented paradigm. However, there are some conventions that need to be followed that will be discussed later.

The PHP Life Cycle

When considering the PHP life cycle there are two basic cycles:

- PHP engine startup and shutdown cycle
- Request cycle

When the PHP engine starts up it will call the module initialization (MINIT) function of each registered extension. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension.

During the lifetime of the PHP engine it will receive a number of requests. Each request constitutes another life cycle. On each request the PHP engine will call the request initialization function of each extension. The extension can perform any variable setup and resource allocation required for request processing. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required.

How a plugin works

A `mysqlnd` plugin works by intercepting calls made to `mysqlnd` by extensions that use `mysqlnd`. This is achieved by obtaining the `mysqlnd` function table, backing it up, and replacing it by a custom function table, which calls the functions of the plugin as required.

The following code shows how the `mysqlnd` function table is replaced:

    /* a place to store original function table */
    struct st_mysqlnd_conn_methods org_methods;

    void minit_register_hooks(TSRMLS_D) {
      /* active function table */
      struct st_mysqlnd_conn_methods * current_methods
        = mysqlnd_conn_get_methods();

      /* backup original function table */
      memcpy(&org_methods, current_methods,
        sizeof(struct st_mysqlnd_conn_methods);

      /* install new methods */
      current_methods->query = MYSQLND_METHOD(my_conn_class, query);
    }

Connection function table manipulations must be done during Module Initialization (MINIT). The function table is a global shared resource. In an multi-threaded environment, with a TSRM build, the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.

> Note: Do not use any fixed-size logic when manipulating the `mysqlnd` function table: new methods may be added at the end of the function table. The function table may change at any time in the future.

Calling parent methods

If the original function table entries are backed up, it is still possible to call the original function table entries - the parent methods.

In some cases, such as for `Connection::stmt_init()`, it is vital to call the parent method prior to any other activity in the derived method.

    MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn,
      const char *query, unsigned int query_len TSRMLS_DC) {

      php_printf("my_conn_class::query(query = %s)\n", query);

      query = "SELECT 'query rewritten' FROM DUAL";
      query_len = strlen(query);

      return org_methods.query(conn, query, query_len); /* return with call to parent */
    }

Extending properties

A `mysqlnd` object is represented by a C struct. It is not possible to add a member to a C struct at run time. Users of `mysqlnd` objects cannot simply add properties to the objects.

Arbitrary data (properties) can be added to a `mysqlnd` objects using an appropriate function of the `mysqlnd_plugin_get_plugin_<object>_data()` family. When allocating an object `mysqlnd` reserves space at the end of the object to hold a `void *` pointer to arbitrary data. `mysqlnd` reserves space for one `void *` pointer per plugin.

The following table shows how to calculate the position of the pointer for a specific plugin:

Pointer calculations for mysqlnd
Memory address | Contents
--- | ---
0 | Beginning of the mysqlnd object C struct
n | End of the mysqlnd object C struct
n + (m x sizeof(void*)) | void* to object data of the m-th plugin

If you plan to subclass any of the `mysqlnd` object constructors, which is allowed, you must keep this in mind!

The following code shows extending properties:

    /* any data we want to associate */
    typedef struct my_conn_properties {
      unsigned long query_counter;
    } MY_CONN_PROPERTIES;

    /* plugin id */
    unsigned int my_plugin_id;

    void minit_register_hooks(TSRMLS_D) {
      /* obtain unique plugin ID */
      my_plugin_id = mysqlnd_plugin_register();
      /* snip - see Extending Connection: methods */
    }

    static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) {
      MY_CONN_PROPERTIES** props;
      props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data(
        conn, my_plugin_id);
      if (!props || !(*props)) {
        *props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent);
        (*props)->query_counter = 0;
      }
      return props;
    }

The plugin developer is responsible for the management of plugin data memory.

Use of the `mysqlnd` memory allocator is recommended for plugin data. These functions are named using the convention: `mnd_*loc()`. The `mysqlnd` allocator has some useful features, such as the ability to use a debug allocator in a non-debug build.

When and how to subclass
| When to subclass? | Each instance has its own private function table? | How to subclass?
--- | --- | --- | ---
Connection (MYSQLND) | MINIT | No | mysqlnd_conn_get_methods()
Resultset (MYSQLND_RES) | MINIT or later | Yes | mysqlnd_result_get_methods() or object method function table manipulation
Resultset Meta (MYSQLND_RES_METADATA) | MINIT | No | mysqlnd_result_metadata_get_methods()
Statement (MYSQLND_STMT) | MINIT | No | mysqlnd_stmt_get_methods()
Network (MYSQLND_NET) | MINIT or later | Yes | mysqlnd_net_get_methods() or object method function table manipulation
Wire protocol (MYSQLND_PROTOCOL) | MINIT or later | Yes | mysqlnd_protocol_get_methods() or object method function table manipulation

You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table.

Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. To avoid chaos, in particular in threaded environments, such function tables must only be manipulated during MINIT.

Other classes use copies of a globally shared function table. The class function table copy is created together with the object. Each object uses its own function table. This gives you two options: you can manipulate the default function table of an object at MINIT, and you can additionally refine methods of an object without impacting other instances of the same class.

The advantage of the shared function table approach is performance. There is no need to copy a function table for each and every object.

Constructor status
Type | Allocation, construction, reset | Can be modified? | Caller
--- | --- | --- | ---
Connection (MYSQLND) | mysqlnd_init() | No | mysqlnd_connect()
Resultset(MYSQLND_RES) | Allocation: Connection::result_init() Reset and re-initialized during: Result::use_result() Result::store_result | Yes, but call parent! | Connection::list_fields() Statement::get_result() Statement::prepare() (Metadata only) Statement::resultMetaData()
Resultset Meta (MYSQLND_RES_METADATA) | Connection::result_meta_init() | Yes, but call parent! | Result::read_result_metadata()
Statement (MYSQLND_STMT) | Connection::stmt_init() | Yes, but call parent! | Connection::stmt_init()
Network (MYSQLND_NET) | mysqlnd_net_init() | No | Connection::init()
Wire protocol (MYSQLND_PROTOCOL) | mysqlnd_protocol_init() | No | Connection::init()

It is strongly recommended that you do not entirely replace a constructor. The constructors perform memory allocations. The memory allocations are vital for the `mysqlnd` plugin API and the object logic of `mysqlnd`. If you do not care about warnings and insist on hooking the constructors, you should at least call the parent constructor before doing anything in your constructor.

Regardless of all warnings, it can be useful to subclass constructors. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables, such as Resultset, Network, Wire Protocol.

Destruction status
Type | Derived method must call parent? | Destructor
--- | --- | ---
Connection | yes, after method execution | free_contents(), end_psession()
Resultset | yes, after method execution | free_result()
Resultset Meta | yes, after method execution | free()
Statement | yes, after method execution | dtor(), free_stmt_content()
Network | yes, after method execution | free()
Wire protocol | yes, after method execution | free()

The destructors are the appropriate place to free properties, `mysqlnd_plugin_get_plugin_<object>_data()`.

The listed destructors may not be equivalent to the actual `mysqlnd` method freeing the object itself. However, they are the best possible place for you to hook in and free your plugin data. As with constructors you may replace the methods entirely but this is not recommended. If multiple methods are listed in the above table you will need to hook all of the listed methods and free your plugin data in whichever method is called first by `mysqlnd`.

The recommended method for plugins is to simply hook the methods, free your memory and call the parent implementation immediately following this.

## The mysqlnd plugin API

The following is a list of functions provided in the `mysqlnd` plugin API:

- mysqlnd_plugin_register()
- mysqlnd_plugin_count()
- mysqlnd_plugin_get_plugin_connection_data()
- mysqlnd_plugin_get_plugin_result_data()
- mysqlnd_plugin_get_plugin_stmt_data()
- mysqlnd_plugin_get_plugin_net_data()
- mysqlnd_plugin_get_plugin_protocol_data()
- mysqlnd_conn_get_methods()
- mysqlnd_result_get_methods()
- mysqlnd_result_meta_get_methods()
- mysqlnd_stmt_get_methods()
- mysqlnd_net_get_methods()
- mysqlnd_protocol_get_methods()

There is no formal definition of what a plugin is and how a plugin mechanism works.

Components often found in plugins mechanisms are:

- A plugin manager
- A plugin API
- Application services (or modules)
- Application service APIs (or module APIs)

The `mysqlnd` plugin concept employs these features, and additionally enjoys an open architecture.

No Restrictions

A plugin has full access to the inner workings of `mysqlnd`. There are no security limits or restrictions. Everything can be overwritten to implement friendly or hostile algorithms. It is recommended you only deploy plugins from a trusted source.

As discussed previously, plugins can use pointers freely. These pointers are not restricted in any way, and can point into another plugin's data. Simple offset arithmetic can be used to read another plugin's data.

It is recommended that you write cooperative plugins, and that you always call the parent method. The plugins should always cooperate with `mysqlnd` itself.

Issues: an example of chaining and cooperation
Extension | mysqlnd.query() pointer | call stack if calling parent
--- | --- | ---
ext/mysqlnd | mysqlnd.query() | mysqlnd.query
ext/mysqlnd_cache | mysqlnd_cache.query() | mysqlnd_cache.query() mysqlnd.query
ext/mysqlnd_monitor | mysqlnd_monitor.query() | mysqlnd_monitor.query() mysqlnd_cache.query() mysqlnd.query

In this scenario, a cache (`ext/mysqlnd_cache`) and a monitor (`ext/mysqlnd_monitor`) plugin are loaded. Both subclass `Connection::query()`. Plugin registration happens at `MINIT` using the logic shown previously. PHP calls extensions in alphabetical order by default. Plugins are not aware of each other and do not set extension dependencies.

By default the plugins call the parent implementation of the query method in their derived version of the method.

PHP Extension Recap

This is a recap of what happens when using an example plugin, `ext/mysqlnd_plugin`, which exposes the `mysqlnd` C plugin API to PHP:

- Any PHP MySQL application tries to establish a connection to 192.168.2.29
- The PHP application will either use `ext/mysql`, `ext/mysqli` or `PDO_MYSQL`. All three PHP MySQL extensions use `mysqlnd` to establish the connection to 192.168.2.29.
- `Mysqlnd` calls its connect method, which has been subclassed by `ext/mysqlnd_plugin`.
- `ext/mysqlnd_plugin` calls the userspace hook `proxy::connect()` registered by the user.
- The userspace hook changes the connection host IP from 192.168.2.29 to 127.0.0.1 and returns the connection established by `parent::connect()`.
- `ext/mysqlnd_plugin` performs the equivalent of `parent::connect(127.0.0.1)` by calling the original `mysqlnd` method for establishing a connection.
- `ext/mysqlnd` establishes a connection and returns to `ext/mysqlnd_plugin`. `ext/mysqlnd_plugin` returns as well.
- Whatever PHP MySQL extension had been used by the application, it receives a connection to 127.0.0.1. The PHP MySQL extension itself returns to the PHP application. The circle is closed.

## Getting started building a mysqlnd plugin

It is important to remember that a `mysqlnd` plugin is itself a PHP extension.

The following code shows the basic structure of the MINIT function that will be used in the typical `mysqlnd` plugin:

    /* my_php_mysqlnd_plugin.c */

     static PHP_MINIT_FUNCTION(mysqlnd_plugin) {
      /* globals, ini entries, resources, classes */

      /* register mysqlnd plugin */
      mysqlnd_plugin_id = mysqlnd_plugin_register();

      conn_m = mysqlnd_get_conn_methods();
      memcpy(org_conn_m, conn_m,
        sizeof(struct st_mysqlnd_conn_methods));

      conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn, query);
      conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn, connect);
    }

    /* my_mysqlnd_plugin.c */

     enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) {
      /* ... */
    }
    enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) {
      /* ... */
    }

Task analysis: from C to userspace

     class proxy extends mysqlnd_plugin_connection {
      public function connect($host, ...) { .. }
    }
    mysqlnd_plugin_set_conn_proxy(new proxy());

Process:

1. PHP: user registers plugin callback
2. PHP: user calls any PHP MySQL API to connect to MySQL
3. C: ext/*mysql* calls mysqlnd method
4. C: mysqlnd ends up in ext/mysqlnd_plugin

5. C: ext/mysqlnd_plugin

   1. Calls userspace callback
   2. Or original `mysqlnd` method, if userspace callback not set

You need to carry out the following:

1. Write a class "mysqlnd_plugin_connection" in C
2. Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()"
3. Call userspace proxy methods from C (optimization - zend_interfaces.h)

Userspace object methods can either be called using `call_user_function()` or you can operate at a level closer to the Zend Engine and use `zend_call_method()`.

Optimization: calling methods from C using zend_call_method

The following code snippet shows the prototype for the `zend_call_method` function, taken from zend_interfaces.h.

     ZEND_API zval* zend_call_method(
      zval **object_pp, zend_class_entry *obj_ce,
      zend_function **fn_proxy, char *function_name,
      int function_name_len, zval **retval_ptr_ptr,
      int param_count, zval* arg1, zval* arg2 TSRMLS_DC
    );

Zend API supports only two arguments. You may need more, for example:

     enum_func_status (*func_mysqlnd_conn__connect)(
      MYSQLND *conn, const char *host,
      const char * user, const char * passwd,
      unsigned int passwd_len, const char * db,
      unsigned int db_len, unsigned int port,
      const char * socket, unsigned int mysql_flags TSRMLS_DC
    );

To get around this problem you will need to make a copy of `zend_call_method()` and add a facility for additional parameters. You can do this by creating a set of `MY_ZEND_CALL_METHOD_WRAPPER` macros.

Calling PHP userspace

This code snippet shows the optimized method for calling a userspace function from C:

    /* my_mysqlnd_plugin.c */

    MYSQLND_METHOD(my_conn_class,connect)(
      MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) {
      enum_func_status ret = FAIL;
      zval * global_user_conn_proxy = fetch_userspace_proxy();
      if (global_user_conn_proxy) {
        /* call userspace proxy */
        ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/);
      } else {
        /* or original mysqlnd method = do nothing, be transparent */
        ret = org_methods.connect(conn, host, user, passwd,
              passwd_len, db, db_len, port,
              socket, mysql_flags TSRMLS_CC);
      }
      return ret;
    }

Calling userspace: simple arguments

    /* my_mysqlnd_plugin.c */

     MYSQLND_METHOD(my_conn_class,connect)(
      /* ... */, const char *host, /* ...*/) {
      /* ... */
      if (global_user_conn_proxy) {
        /* ... */
        zval* zv_host;
        MAKE_STD_ZVAL(zv_host);
        ZVAL_STRING(zv_host, host, 1);
        MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_host /*, ...*/);
        zval_ptr_dtor(&zv_host);
        /* ... */
      }
      /* ... */
    }

Calling userspace: structs as arguments

    /* my_mysqlnd_plugin.c */

    MYSQLND_METHOD(my_conn_class, connect)(
      MYSQLND *conn, /* ...*/) {
      /* ... */
      if (global_user_conn_proxy) {
        /* ... */
        zval* zv_conn;
        ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn);
        MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/);
        zval_ptr_dtor(&zv_conn);
        /* ... */
      }
      /* ... */
    }

The first argument of many `mysqlnd` methods is a C "object". For example, the first argument of the connect() method is a pointer to `MYSQLND`. The struct MYSQLND represents a `mysqlnd` connection object.

The `mysqlnd` connection object pointer can be compared to a standard I/O file handle. Like a standard I/O file handle a `mysqlnd` connection object shall be linked to the userspace using the PHP resource variable type.

From C to userspace and back

     class proxy extends mysqlnd_plugin_connection {
      public function connect($conn, $host, ...) {
        /* "pre" hook */
        printf("Connecting to host = '%s'\n", $host);
        debug_print_backtrace();
        return parent::connect($conn);
      }

      public function query($conn, $query) {
        /* "post" hook */
        $ret = parent::query($conn, $query);
        printf("Query = '%s'\n", $query);
        return $ret;
      }
    }
    mysqlnd_plugin_set_conn_proxy(new proxy());

PHP users must be able to call the parent implementation of an overwritten method.

As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks.

Built-in class: mysqlnd_plugin_connection::connect()

    /*  my_mysqlnd_plugin_classes.c */

     PHP_METHOD("mysqlnd_plugin_connection", connect) {
      /* ... simplified! ... */
      zval* mysqlnd_rsrc;
      MYSQLND* conn;
      char* host; int host_len;
      if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
        &mysqlnd_rsrc, &host, &host_len) == FAILURE) {
        RETURN_NULL();
      }
      ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1,
        "Mysqlnd Connection", le_mysqlnd_plugin_conn);
      if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC))
        RETVAL_TRUE;
      else
        RETVAL_FALSE;
    }

- Overview
- Installation
- Runtime Configuration
- Incompatibilities
- Persistent Connections
- Statistics
- Notes
- Memory management
- MySQL Native Driver Plugin API
  - A comparison of mysqlnd plugins with MySQL Proxy
  - Obtaining the mysqlnd plugin API
  - MySQL Native Driver Plugin Architecture
  - The mysqlnd plugin API
  - Getting started building a mysqlnd plugin

- Overview of the MySQL PHP drivers
  - Terminology overview
  - Choosing an API
  - Choosing a library
  - Concepts
- MySQLi — MySQL Improved Extension
  - Overview
  - Quick start guide
  - Installing/Configuring
  - The mysqli Extension and Persistent Connections
  - Predefined Constants
  - Notes
  - The MySQLi Extension Function Summary
  - mysqli — The mysqli class
  - mysqli_stmt — The mysqli_stmt class
  - mysqli_result — The mysqli_result class
  - mysqli_driver — The mysqli_driver class
  - mysqli_warning — The mysqli_warning class
  - mysqli_sql_exception — The mysqli_sql_exception class
  - Aliases and deprecated Mysqli Functions
  - Changelog
- Mysql_xdevapi
  - Installing/Configuring
  - Predefined Constants
  - Changelog
  - Examples
  - Mysql_xdevapi Functions
  - mysql_xdevapi\BaseResult — BaseResult interface
  - mysql_xdevapi\Client — Client class
  - mysql_xdevapi\Collection — Collection class
  - mysql_xdevapi\CollectionAdd — CollectionAdd class
  - mysql_xdevapi\CollectionFind — CollectionFind class
  - mysql_xdevapi\CollectionModify — CollectionModify class
  - mysql_xdevapi\CollectionRemove — CollectionRemove class
  - mysql_xdevapi\ColumnResult — ColumnResult class
  - mysql_xdevapi\CrudOperationBindable — CrudOperationBindable interface
  - mysql_xdevapi\CrudOperationLimitable — CrudOperationLimitable interface
  - mysql_xdevapi\CrudOperationSkippable — CrudOperationSkippable interface
  - mysql_xdevapi\CrudOperationSortable — CrudOperationSortable interface
  - mysql_xdevapi\DatabaseObject — DatabaseObject interface
  - mysql_xdevapi\DocResult — DocResult class
  - mysql_xdevapi\Exception — Exception class
  - mysql_xdevapi\Executable — Executable interface
  - mysql_xdevapi\ExecutionStatus — ExecutionStatus class
  - mysql_xdevapi\Expression — Expression class
  - mysql_xdevapi\Result — Result class
  - mysql_xdevapi\RowResult — RowResult class
  - mysql_xdevapi\Schema — Schema class
  - mysql_xdevapi\SchemaObject — SchemaObject interface
  - mysql_xdevapi\Session — Session class
  - mysql_xdevapi\SqlStatement — SqlStatement class
  - mysql_xdevapi\SqlStatementResult — SqlStatementResult class
  - mysql_xdevapi\Statement — Statement class
  - mysql_xdevapi\Table — Table class
  - mysql_xdevapi\TableDelete — TableDelete class
  - mysql_xdevapi\TableInsert — TableInsert class
  - mysql_xdevapi\TableSelect — TableSelect class
  - mysql_xdevapi\TableUpdate — TableUpdate class
  - mysql_xdevapi\Warning — Warning class
- MySQL (Original) — Original MySQL API
  - Installing/Configuring
  - Changelog
  - Predefined Constants
  - Examples
  - MySQL Functions
- Mysqlnd — MySQL Native Driver
  - Overview
  - Installation
  - Runtime Configuration
  - Incompatibilities
  - Persistent Connections
  - Statistics
  - Notes
  - Memory management
  - MySQL Native Driver Plugin API

# Oracle OCI8

# Introduction

Warning

This extension is UNBUNDLED as of PHP 8.4.0.

These functions allow you to access Oracle Database. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Testing
- Runtime Configuration

## Requirements

OCI8 3.0 is included with PHP 8. It is also available from » PECL. For PHP 7, use OCI8 2.2 from » PECL. OCI8 requires Oracle 10g or later Oracle client libraries.

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries and header files. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the `Basic` or `Basic Light` Oracle Instant Client ZIP file, RPM package, or DMG package. When building OCI8 from source code, also install the Instant Client `SDK`.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

> Note:

> Oracle's standard client-server network interoperability allows connections between different versions of Oracle Client and Oracle Database. For certified configurations see Oracle Support's Doc ID 207303.1. In summary, Oracle Client 19, 18 and 12.2 can connect to Oracle Database 11.2 or greater. Oracle Client 12.1 can connect to Oracle Database 10.2 or greater. Oracle Client 11.2 can connect to Oracle Database 9.2 or greater.

> Note:

> Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.

## Installation

## Configuring PHP with OCI8

Review the previous Requirements section before configuring OCI8.

Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables must be set before any PHP process starts.

The PHP binary must link with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 19 libraries, then PHP should also be deployed and run with Oracle 19 libraries. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.

## Installing OCI8 from PECL Using the pecl Command

The OCI8 extension can be added to an existing PHP installation by using the » PECL repository.

- If you are behind a firewall, set PEAR's proxy, for example:

      pear config-set http_proxy http://my-proxy.example.com:80/

- Run

      pecl install oci8

  For PHP 7, use `pecl install oci8-2.2.0`

- When prompted, enter either the value of `$ORACLE_HOME`, or `instantclient,/path/to/instant/client/lib`.

  Note: Do not enter variable names like `$ORACLE_HOME` or `$HOME` because `pecl` will not expand them. Instead, enter an expanded path, for example `/opt/oracle/product/19c/dbhome_1` or `instantclient,/Users/myname/Downloads/instantclient_19_8`

- If you get an error `oci8_dtrace_gen.h: No such file or directory`, it means PHP was built with DTrace Dynamic Tracing enabled. Install using:

      $ export PHP_DTRACE=yes
      $ pecl install oci8

- Edit your php.ini file and add the line:

      extension=oci8.so

  Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

## Installing OCI8 from PECL Using phpize

To install OCI8 on an existing PHP installation when the `pecl` command is not available, manually download the » PECL OCI8 package, e.g. oci8-3.0.0.tgz.

- Extract the package:

      tar -zxf oci8-3.0.0.tgz
      cd oci8-3.0.0

- Prepare the package:

      phpize

- Configure the package, either using `$ORACLE_HOME` or Instant Client

      ./configure -with-oci8=shared,$ORACLE_HOME

  or

      ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib

- Install the package:

      make install

- If you get an error `oci8_dtrace_gen.h: No such file or directory`, it means PHP was built with DTrace Dynamic Tracing enabled. Re-run the `configure` and `make` commands after setting this environment variable:

      $ export PHP_DTRACE=yes

- Edit your php.ini file and add the line:

      extension=oci8.so

  Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

## Installing OCI8 as a Shared Extension when Building PHP

If you are building PHP from source code, the configuration `shared` option can be used to build OCI8 as a shared library that can be dynamically loaded into PHP. Building a shared extension allows OCI8 to be upgraded easily without impacting the rest of PHP.

Configure OCI8 using one of the following configure options.

- If using the free » Oracle Instant Client libraries, then do:

      ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib

  If Instant Client 12.2 (or earlier) is installed from ZIP files, make sure to create the library symbolic link first, for example `ln -s libclntsh.so.12.1 libclntsh.so`.

  If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:

      ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib

  For example, --with-oci8=shared,instantclient,/usr/lib/oracle/19.9/client/lib

- If using an Oracle database or full Oracle Client installation then do:

      ./configure --with-oci8=shared,$ORACLE_HOME

  Make sure the web server user (`nobody`, `www`) has access to the libraries, initialization files and tnsnames.ora (if used) under the `$ORACLE_HOME` directory. With Oracle 10gR2, you may need to run the $ORACLE_HOME/install/changePerm.sh utility to give directory access.

After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.

To complete installation of OCI8, edit php.ini and add the line:

    extension=oci8.so

## Installing OCI8 as a Statically Compiled Extension when Building PHP

If you are building PHP from source code, you can configure PHP to include OCI8 as a static extension using one of the following configure options.

- If using Oracle Instant Client, then do:

      ./configure --with-oci8=instantclient,/path/to/instant/client/lib

- If using an Oracle database or full Oracle Client installation then do:

      ./configure --with-oci8=$ORACLE_HOME

After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.

## Installing OCI8 on Windows

The OCI8 extension can be added to an existing PHP installation by using the DLLs from » PECL repository or the libraries in your PHP installation's `ext` directory.

With Oracle 12c (or later) libraries, uncomment one of the php.ini lines `extension=php_oci8_12c.dll` or `extension=php_oci8_11g.dll` or `extension=php_oci8.dll`. Only one of these DLLs may be enabled at a time. DLLs with higher versions may contain more functionality. Not all DLLs may be available for all versions of PHP. Make sure extension_dir is set to the directory containing the PHP extension DLLs.

If using Instant Client, set the system PATH environment variable to the Oracle library directory.

## Setting the Oracle Environment

Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.

> Note:

> Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.

On Red Hat Linux and variants, export variables at the end of /etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars script in the Apache bin directory. A third option, the Apache `SetEnv` directive in httpd.conf, may work in some systems but is known to be insufficient in others.

To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.

The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the available variables.

Common Oracle Environment Variables
Name | Purpose
--- | ---
ORACLE_HOME | Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems.
ORACLE_SID | Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect().
LD_LIBRARY_PATH | Set this (or its platform equivalent, such as `LIBPATH`, or `SHLIB_PATH`) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/18.5/client/lib. Note with Instant Client ZIP files on Linux it is more reliable to use ldconfig instead, see the Instant Client installation instructions. With Instant Client 19 (or later) RPM files, `ldconfig` is automatically run for you. Some users use `LD_PRELOAD` instead of `LD_LIBRARY_PATH`.
NLS_LANG | This is the primary variable for setting the character set and globalization information used by the Oracle libraries.
ORA_SDTZ | Sets the Oracle session timezone.
TNS_ADMIN | Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as `localhost/XE`. Not needed if the network configuration files are in one of the default locations such as /usr/lib/oracle/VERSION/client/lib/network/admin, $ORACLE_HOME/network/admin or /etc.

Less frequently used Oracle environment variables include `TWO_TASK`, `ORA_TZFILE`, and the various Oracle globalization settings like `NLS*` and the `ORA_NLS_*` variables.

## Troubleshooting

The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.

While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.

On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.

A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.

> Note: If the web server doesn't start or crashes at startup

> Check that Apache is linked with the pthread library:

>     # ldd /www/apache/bin/httpd
>       libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
>       libm.so.6 => /lib/libm.so.6 (0x4002f000)
>       libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
>       libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
>       libc.so.6 => /lib/libc.so.6 (0x4007e000)
>       /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

> If the libpthread is not listed, then reinstall Apache:

>     # cd /usr/src/apache_1.3.xx
>     # make clean
>     # LIBS=-lpthread ./config.status
>     # make
>     # make install

> Please note that on some systems like UnixWare, it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.

## Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the `SYSTEM` account. Some tests will fail if the test user does not have equivalent permissions.

If Oracle Database Resident Connection Pooling is being tested, set $test_drcp to `true` and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

        $ export PHP_OCI8_TEST_USER=system
        $ export PHP_OCI8_TEST_PASS=oracle
        $ export PHP_OCI8_TEST_DB=localhost/XE
        $ export PHP_OCI8_TEST_DRCP=FALSE

Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. If you are running PHP on the same machines as Oracle Database, you can run:

        $ . /usr/local/bin/oraenv

With Oracle 11gR2 XE do:

        $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

Some shells require that php.ini has `E` in the variables_order parameter, for example:

        variables_order = "EGPCS"

Run all the PHP tests with:

        $ cd your_php_src_directory
        $ make test

or run only the OCI8 tests with

        $ cd your_php_src_directory
        $ make test TESTS=ext/oci8

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable `TEST_TIMEOUT` to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database `PROCESSES` parameter using the following steps:

Connect as the oracle software owner:

        $ su - oracle

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase `PROCESSES`

        $ sqlplus / as sysdba
        SQL> alter system set processes=100 scope=spfile

Restart the database:

        SQL> startup force

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OCI8 Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
oci8.connection_class | "" | `INI_ALL` |
oci8.default_prefetch | "100" | `INI_SYSTEM` |
oci8.events | Off | `INI_SYSTEM` |
oci8.max_persistent | "-1" | `INI_SYSTEM` |
oci8.old_oci_close_semantics | Off | `INI_SYSTEM` | Deprecated as of PHP 8.1.0.
oci8.persistent_timeout | "-1" | `INI_SYSTEM` |
oci8.ping_interval | "60" | `INI_SYSTEM` |
oci8.prefetch_lob_size | "0" | `INI_SYSTEM` | Available since PECL OCI8 3.2.
oci8.privileged_connect | Off | `INI_SYSTEM` |
oci8.statement_cache_size | "20" | `INI_SYSTEM` |

Here's a short explanation of the configuration directives.

`oci8.connection_class` string

  This user defined text should always be set when using Oracle Database Resident Connection Pooling (DRCP). It allows sub-partitioning of the DRCP connection pool, allowing OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

  The value can be set at runtime with ini_set() prior to connecting.

  To use DRCP, OCI8 must be linked with Oracle 11g (or later) libraries and the database must be Oracle 11g (or later). The DRCP connection pool must be enabled in the database, the `oci8.connection_class` should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server. The application should use persistent connections.

`oci8.default_prefetch` int

  This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of `0` turns off prefetching.

  The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

  The value can be set per-statement with oci_set_prefetch() prior to statement execution.

  When using Oracle Database 12c (or later), the prefetch value set by PHP can be overridden by Oracle's client `oraaccess.xml` configuration file. Refer to Oracle documentation for more detail.

  > Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

`oci8.events` bool

  Using `On` allows PHP to be notified of database Fast Application Notification (FAN) events.

  Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

  When using `On`, the database must also be configured to post FAN events.

  FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

`oci8.max_persistent` int

  The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

`oci8.old_oci_close_semantics` bool

  This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.

`oci8.persistent_timeout` int

  The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

  > Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that `oci8.max_persistent` and `oci8.persistent_timeout` previously attempted to overcome.

`oci8.ping_interval` int

  The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

  > Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

`oci8.prefetch_lob_size` int

  This is a tuning parameter affecting internal buffering of LOB data. Increasing this value can improve the performance of fetching smaller LOBs by reducing round-trips between PHP and the database. Memory usage will change.

  The value affects LOBs returned as OCILob instances and also those returned using `OCI_RETURN_LOBS`.

  The value can be set per-statement with oci_set_prefetch_lob() prior to statement execution.

  > Note: Use with Oracle Database 12.2 or later.

`oci8.privileged_connect` bool

  This option allows connections to use the privileged external credentials `OCI_SYSOPER` or `OCI_SYSDBA`.

  > Note: Seting this `On` can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

`oci8.statement_cache_size` int

  This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

  Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

  Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

  This option is of most use with persistent connections.

  When using Oracle Database 12c (or later), this value can be overridden and automatically tuned by Oracle's client `oraaccess.xml` file. Refer to Oracle documentation for more detail.

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

OCI8 Function and Method Modes
Constant | Description
--- | ---
`OCI_ASSOC` | Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
`OCI_BOTH` | Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
`OCI_COMMIT_ON_SUCCESS` | Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
`OCI_CRED_EXT` | Used with oci_connect() for using Oracles' External or OS authentication.
`OCI_DEFAULT` | See `OCI_NO_AUTO_COMMIT`.
`OCI_DESCRIBE_ONLY` | Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
`OCI_EXACT_FETCH` | Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
`OCI_FETCHSTATEMENT_BY_COLUMN` | Default mode of oci_fetch_all().
`OCI_FETCHSTATEMENT_BY_ROW` | Alternative mode of oci_fetch_all().
`OCI_LOB_BUFFER_FREE` | Used with OCILob::flush to free buffers used.
`OCI_NO_AUTO_COMMIT` | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. For readability in new code, use this value instead of the older, equivalent `OCI_DEFAULT` constant.
`OCI_NUM` | Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
`OCI_RETURN_LOBS` | Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
`OCI_RETURN_NULLS` | Used with oci_fetch_array() to get empty array elements if the row items value is `null`.
`OCI_SEEK_CUR` | Used with OCILob::seek to set the seek position.
`OCI_SEEK_END` | Used with OCILob::seek to set the seek position.
`OCI_SEEK_SET` | Used with OCILob::seek to set the seek position.
`OCI_SYSDATE` | Obsolete.
`OCI_SYSDBA` | Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
`OCI_SYSOPER` | Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
`OCI_TEMP_BLOB` | Used with OCILob::writeTemporary to indicate that a temporary BLOB should be created.
`OCI_TEMP_CLOB` | Used with OCILob::writeTemporary to indicate that a temporary CLOB should be created.

OCI8 Bind and Define Types
Constant | Description
--- | ---
`OCI_B_BFILE` | Used with oci_bind_by_name() when binding BFILEs.
`OCI_B_BIN` | Used with oci_bind_by_name() to bind RAW values.
`OCI_B_BLOB` | Used with oci_bind_by_name() when binding BLOBs.
`OCI_B_BOL` | Used with oci_bind_by_name() to bind a PL/SQL BOOLEAN variable.
`OCI_B_CFILEE` | Used with oci_bind_by_name() when binding CFILEs.
`OCI_B_CLOB` | Used with oci_bind_by_name() when binding CLOBs.
`OCI_B_CURSOR` | Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
`OCI_B_INT` | Used with oci_bind_array_by_name() to bind arrays of INTEGER.
`OCI_B_NTY` | Used with oci_bind_by_name() when binding named data types.
`OCI_B_NUM` | Used with oci_bind_array_by_name() to bind arrays of NUMBER.
`OCI_B_ROWID` | Used with oci_bind_by_name() when binding ROWIDs.
`SQLT_AFC` | Used with oci_bind_array_by_name() to bind arrays of CHAR.
`SQLT_AVC` | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
`SQLT_BDOUBLE` | Not supported.
`SQLT_BFILEE` | The same as `OCI_B_BFILE`.
`SQLT_BFLOAT` | Not supported.
`SQLT_BIN` | The same as `OCI_B_BIN`.
`SQLT_BLOB` | The same as `OCI_B_BLOB`.
`SQLT_BOL` | The same as `OCI_B_BOL`.
`SQLT_CFILEE` | The same as `OCI_B_CFILEE`.
`SQLT_CHR` | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
`SQLT_CLOB` | The same as `OCI_B_CLOB`.
`SQLT_FLT` | Used with oci_bind_array_by_name() to bind arrays of FLOAT.
`SQLT_INT` | The same as `OCI_B_INT`.
`SQLT_LBI` | Used with oci_bind_by_name() to bind LONG RAW values.
`SQLT_LNG` | Used with oci_bind_by_name() to bind LONG values.
`SQLT_LVC` | Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
`SQLT_NTY` | The same as `OCI_B_NTY`.
`SQLT_NUM` | The same as `OCI_B_NUM`.
`SQLT_ODT` | Used with oci_bind_array_by_name() to bind arrays of LONG.
`SQLT_RDD` | The same as `OCI_B_ROWID`.
`SQLT_RSET` | The same as `OCI_B_CURSOR`.
`SQLT_STR` | Used with oci_bind_array_by_name() to bind arrays of STRING.
`SQLT_UIN` | Not supported.
`SQLT_VCS` | Used with oci_bind_array_by_name() to bind arrays of VARCHAR.

OCI8 Descriptor Types
Constant | Description
--- | ---
`OCI_DTYPE_FILE` | This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
`OCI_DTYPE_LOB` | This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
`OCI_DTYPE_ROWID` | This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
`OCI_D_FILE` | The same as `OCI_DTYPE_FILE`.
`OCI_D_LOB` | The same as `OCI_DTYPE_LOB`.
`OCI_D_ROWID` | The same as `OCI_DTYPE_ROWID`.

Constants | Description
--- | ---
OCI8 Transparent Application Failover (TAF) Constants
`OCI_FO_ABORT` (int) | Failover was unsuccessful and there is no option of retrying.
`OCI_FO_BEGIN` (int) | Failover has detected a lost connection and failover is starting.
`OCI_FO_END` (int) | Failover completed successfully.
`OCI_FO_ERROR` (int) | Failover was unsuccessful but it gives the application the opportunity to handle the error and return `OCI_FO_RETRY` to retry failover.
`OCI_FO_NONE` (int) | The user has not requested a failover type.
`OCI_FO_REAUTH` (int) | An Oracle user has been re-authenticated.
`OCI_FO_RETRY` (int) | The failover should be attempted again by Oracle. In case of an error while failing over to a new connection, TAF is able to retry the failover. Typically, the application code should sleep for a while before returning `OCI_FO_RETRY`.
`OCI_FO_SELECT` (int) | The user has requested SELECT failover as well. It allows users with open cursors to continue fetching from them after failure.
`OCI_FO_SESSION` (int) | The user has requested only session failover. For example, if a user's connection is lost, then a new session is automatically created for the user on the backup. This type of failover does not attempt to recover SELECTs.
`OCI_FO_TXNAL` (int) | The user has requested a transaction failover.

# Examples

These examples connect as the `HR` user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the `XE` database on your machine. Change the connect string to your database before running the examples.

Example #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

`<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');
$id = 60;
$data = 'Some data';
oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);
$r = oci_execute($stid); // executes and commits
if ($r) {
print "One row inserted";
}
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 Binding in the WHERE clause of a query

This shows a single scalar bind.

`<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}
// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa
oci_free_statement($stid);
oci_close($conn);
?>`

Example #4 Inserting and fetching a CLOB

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

`<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$mykey = 12343; // arbitrary key for this example;
$sql = "INSERT INTO mytable (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";
$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT);
$clob->save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';
?>`

Example #5 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

`<?php
/*
Before running the PHP program, create a stored function in
SQL*Plus or SQL Developer:
CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
BEGIN
RETURN p * 3;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p = 8;
$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);
oci_execute($stid);
print "$r\n"; // prints 24
oci_free_statement($stid);
oci_close($conn);
?>`

Example #6 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

`<?php
/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:
CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p1 = 8;
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>`

Example #7 Calling a PL/SQL function that returns a `REF CURSOR`

Each returned value from the query is a `REF CURSOR` that can be fetched from.

`<?php
/*
Create the PL/SQL stored function as:
CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
rc SYS_REFCURSOR;
BEGIN
OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
RETURN rc;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
echo "<tr>\n";
$rc = $row['MFRC'];
oci_execute($rc); // returned column value from the query is a ref cursor
while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
echo " <td>" . $rc_row['CITY'] . "</td>\n";
}
oci_free_statement($rc);
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing
// Bern
// Bombay
// Geneva
oci_free_statement($stid);
oci_close($conn);
?>`

# OCI8 Connection Handling and Connection Pooling

## Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of database credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle Database Resident Connection Pooling (in Oracle Database 11g or later), or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FPM, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

Persistent connections can be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

The automatic re-establishment of PHP persistent connections after an Apache or FPM process respawns means Oracle Database `LOGON` triggers are only recommended for setting session attributes and not for per-application user connection requests.

## DRCP Connection Pooling

PHP supports Oracle Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default `Dedicated` database server processes, or use `Shared` servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g or greater.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, install the OCI8 extension and Oracle 11g (or later) libraries and then follow these steps:

- As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

          SQL> execute dbms_connection_pool.start_pool;

- Optionally use `dbms_connection_pool.alter_param()` to configure DRCP settings. The current pool settings can be queried from the `DBA_CPOOL_INFO` view.

- Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like `MYDB`:

          $c = oci_pconnect("myuser", "mypassword", "MYDB");

  modify the tnsnames.ora file and add a `(SERVER=POOLED)` clause, for example:

          MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
                 (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
                 (SERVER=POOLED)))

  Alternatively, modify the Easy Connect syntax in PHP and add `:POOLED` after the service name:

          $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");

- Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

          oci8.connection_class = "MY_APPLICATION_NAME"

- Run the application, connecting to the 11g (or later) database.

> Note:

> Applications using Oracle Client libraries 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle `Shared` servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

> Note:

> Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

# OCI8 Fast Application Notification (FAN) Support

FAN support gives fast connection failover, an Oracle Database high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or later.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is `On`, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP OCI8, build PHP OCI8 with Oracle 10gR2 or later libraries and then follow these steps:

- As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

          SQL> execute dbms_service.modify_service(
                         SERVICE_NAME        => 'sales',
                         AQ_HA_NOTIFICATIONS => TRUE);

- Edit php.ini and add

          oci8.events = On

- If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
- Run the application, connecting to Oracle Database 10gR2 or later.

# OCI8 Transparent Application Failover (TAF) Support

TAF is an Oracle Database feature that provides high availability. It enables PHP OCI8 applications to automatically reconnect to a preconfigured database when database connectivity fails due to instance or network failure.

In a configured Oracle Database system, TAF occurs when the PHP application detects that the database instance is down or unreachable. It establishes a connection to another node in an Oracle » RAC configuration, a hot standby database, or the same database instance itself. See » Oracle Call Interface Programmer's Guide for more information about OCI TAF.

An application callback can be registered with oci_register_taf_callback(). During failover, normal application processing stops and the registered callback is invoked. The callback notifies the application of the failover events. If the failover succeeds, normal processing will be resumed. If the failover aborts, any following database operations in the application will fail due to no connection being available.

When a connection fails over to another database, the callback can reset any necessary connection state, for example replaying any necessary ALTER SESSION commands if the database service did not have -failover_restore enabled.

An application callback can be removed by calling oci_unregister_taf_callback().

## Configuring Transparent Application Failover

TAF can be configured on the PHP OCI8 side or in the database configuration. If both are configured, database-side settings take precedence.

Configure TAF in PHP OCI8 (the client side) by including the FAILOVER_MODE parameter in the CONNECT_DATA portion of a connect descriptor. See Configuring Transparent Application Failover in » Oracle Database Net Services Administrator's Guide for more information about client side configuration of TAF.

An example tnsnames.ora to configure TAF reconnecting to the same database instance:

        ORCL =
          (DESCRIPTION =
            (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
            (CONNECT_DATA =
              (SERVICE_NAME = orclpdb1)
              (FAILOVER_MODE =
                (TYPE = SELECT)
                (METHOD = BASIC)
                (RETRIES = 20)
                (DELAY = 15))))

Alternatively configure TAF on the database side by modifying the target service with » srvctl (for RAC) or the » DBMS_SERVICE.MODIFY_SERVICE packaged procedure (for single instance databases).

## Using TAF Callbacks in OCI8

A TAF callback is an application function that can be registered to be called during failover. It is called several times while re-establishing the application's connection.

Callback first occurs when a loss of connection is detected. This allows the application to act accordingly for the upcoming delay of the failover. If the failover is successful, the callback is invoked after connection is re-established and usable. At this time, the application can resynchronize session settings and take actions such as informing the user that failover occurred. If failover is unsuccessful, a callback occurs to inform the application that a failover did not take place and the connection is unusable.

The interface of a TAF user-defined callback function is as follows:

userCallbackFn(resource `$connection`, int `$event`, int `$type`): int

`connection`

  The Oracle connection on which the TAF callback was registered via oci_register_taf_callback(). The connection is not valid until the failover completes successfully.

`event`

  The failover event indicates the current status of the failover.

  - `OCI_FO_BEGIN` indicates that failover has detected a lost connection and failover is starting.

  - `OCI_FO_END` indicates successful completion of failover.

  - `OCI_FO_ABORT` indicates that failover was unsuccessful, and there is no option of retrying.

  - `OCI_FO_ERROR` also indicates that failover was unsuccessful, but it gives the application the opportunity to handle the error and return OCI_FO_RETRY to retry failover.

  - `OCI_FO_REAUTH` indicates that an Oracle user has been re-authenticated.

`type`

  The failover type. This lets the callback know what type of failover the application has requested. The usual values are as follows:

  - `OCI_FO_SESSION` indicates that the user has requested only session failover. For example, if a user's connection is lost, then a new session is automatically created for the user on the backup. This type of failover does not attempt to recover SELECTs.

  - `OCI_FO_SELECT` indicates that the user has requested SELECT failover as well. It allows users with open cursors to continue fetching from them after failure.

`return value`

  - `0` indicates the failover steps should continue normally.

  - `OCI_FO_RETRY` indicates that the failover should be attempted again by Oracle. In case of an error while failing over to a new connection, TAF is able to retry the failover. Typically, the application code should sleep for a while before returning OCI_FO_RETRY.

Example #1 Registering a TAF callback

`<?php
// Define userspace callback
class MyClass {
public static $retry_count;
public static function TAFCallback($conn, $event, $type)
{
switch ($event) {
case OCI_FO_BEGIN:
printf(" Failing Over ... Please stand by\n");
printf(" Failover type was found to be %s \n",
(($type==OCI_FO_SESSION) ? "SESSION"
:(($type==OCI_FO_SELECT) ? "SELECT" : "UNKNOWN!")));
self::$retry_count = 0;
break;
case OCI_FO_ABORT:
// The application cannot continue using the database
printf(" Failover aborted. Failover will not take place.\n");
break;
case OCI_FO_END:
// Failover completes successfully. Inform users a failover occurs.
printf(" Failover ended ... resuming services\n");
break;
case OCI_FO_REAUTH:
printf(" Failed over user ... resuming services\n");
// Replay any ALTER SESSION commands associated with this connection
// eg. oci_parse($conn, ‘ALTER SESSION …’) ;
break;
case OCI_FO_ERROR:
// Stop retrying if we have already attempted for 20 times.
if (self::$retry_count >= 20)
return 0;
printf(" Failover error received. Sleeping...\n");
sleep(10);
self::$retry_count++;
return OCI_FO_RETRY; // retry failover
break;
default:
printf("Bad Failover Event: %d.\n", $event);
break;
}
return 0;
}
}
$fn_name = 'MyClass::TAFCallback';
$conn = oci_connect('hr', 'welcome', 'orcl');
$sysconn = oci_connect('system', 'oracle', 'orcl');
// Use a privileged connection to construct a SQL statement that will initiate failover
$sql = <<< 'END'
select unique 'alter system disconnect session '''||sid||','||serial#||''''
from v$session_connect_info
where sid = sys_context('USERENV', 'SID')
END;
$s = oci_parse($conn, $sql);
oci_execute($s);
$r = oci_fetch_array($s);
$disconnectssql = $r[0];
oci_register_taf_callback($conn, $fn_name); // Register TAFCallback to Oracle TAF
print "Parsing user query\n";
$sql = "select systimestamp from dual";
$stmt = oci_parse($conn, $sql);
// For example, if a connection loss occurs at this point, oci_execute() will
// detect the loss and failover begins. During failover, oci_execute() will
// invoke the TAF callback function several times. If the failover is successful,
// a new connection is transparently created and oci_execute() will continue as
// usual. The connection session settings can be reset in the TAF callback
// function. If the failover is aborted, oci_execute() will return an error
// because a valid connection is not available.
// Disconnect the user, which initiates failover
print "Disconnecting the user\n";
$discsql = oci_parse($sysconn, $disconnectssql);
oci_execute($discsql);
print "Executing user query\n";
$e = oci_execute($stmt);
if (!$e) {
$m = oci_error($stmt);
trigger_error("Could not execute statement: ". $m['message'], E_USER_ERROR);
}
$row = oci_fetch_array($stmt);
print $row[0] . "\n";
// do other SQL statements with the new connection, if it is valid
// $stmt = oci_parse($conn, . . .);
?>`

## See Also

- oci_register_taf_callback()
- oci_unregister_taf_callback()

# OCI8 and DTrace Dynamic Tracing

OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.

## Installing OCI8 with DTrace Support

To enable DTrace support in PHP OCI8, build OCI8 as a shared extension after setting `PHP_DTRACE`.

    $ export PHP_DTRACE=yes
    $ pecl install oci8

Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:

    extension=oci8.so

If you install PHP OCI8 from PECL using phpize and configure (instead of pecl), you will still need to set `PHP_DTRACE=yes`. This is because the `--enable-dtrace` option will be ignored by the limited configure script of a PECL bundle.

See Installation of PECL extensions for general PECL installation instructions.

## DTrace Static Probes in PHP OCI8

The following static probes are available in PHP OCI8
Probe Name | Probe Description | Probe Arguments
--- | --- | ---
`oci8-connect-entry` | Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. | char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive
`oci8-connect-return` | Fires at the end of connection. | void *connection
`oci8-check-connection` | Fires if an Oracle error might have caused the connection to become invalid. | void *connection, char *client_id, int is_open, long errcode, unsigned long server_status
`oci8-sqltext` | Fires when oci_parse() is executed. | void *connection, char *client_id, void *statement, char *sql
`oci8-connection-close` | Fires when the connection to the database is completely destroyed. | void *connection
`oci8-error` | Fires if an Oracle error occurs. | int status, long errcode
`oci8-execute-mode` | Fires at oci_execute() to show the execution mode. | void *connection, char *client_id, void *statement, unsigned int mode

These probes are useful for tracing OCI8 scripts.

The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.

The client_id is the value set by oci_set_client_identifier().

Core PHP also has static probes. See DTrace Static Probes in Core PHP.

Internal Debugging DTrace Probes in OCI8
Probe Name
`oci8-connect-expiry`
`oci8-connect-lookup`
`oci8-connect-p-dtor-close`
`oci8-connect-p-dtor-release`
`oci8-connect-type`
`oci8-sesspool-create`
`oci8-sesspool-stats`
`oci8-sesspool-type`

These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.

## Listing DTrace Static Probes in PHP OCI8

To list available probes, start a PHP process and then run:

    # dtrace -l

The output will be similar to:

       ID   PROVIDER            MODULE                          FUNCTION NAME
       [ . . . ]
       17 phpoci22116           oci8.so   php_oci_dtrace_check_connection oci8-check-connection
       18 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-entry
       19 phpoci22116           oci8.so         php_oci_persistent_helper oci8-connect-expiry
       20 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-lookup
       21 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
       22 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
       23 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-return
       24 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-type
       25 phpoci22116           oci8.so          php_oci_connection_close oci8-connection-close
       26 phpoci22116           oci8.so                     php_oci_error oci8-error
       27 phpoci22116           oci8.so         php_oci_statement_execute oci8-execute-mode
       28 phpoci22116           oci8.so              php_oci_create_spool oci8-sesspool-create
       29 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-stats
       30 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-type
       31 phpoci22116           oci8.so          php_oci_statement_create oci8-sqltext

The Provider column values consist of `phpoci` and the process id of the currently running PHP 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.

## DTrace with PHP OCI8 Example

This example shows the basics of the DTrace D scripting language.

Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace

    #!/usr/sbin/dtrace -Zs

    #pragma D option quiet

    php*:::oci8-connect-entry
    {
        printf("%lld: PHP connect-entry\n", walltimestamp);
        printf("  credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
        printf("  charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
        printf("  session_mode=%ld\n", (long)arg3);
        printf("  persistent=%d\n", (int)arg4);
        printf("  exclusive=%d\n", (int)arg5);
    }

    php*:::oci8-connect-return
    {
        printf("%lld: PHP oci8-connect-return\n", walltimestamp);
        printf("  connection=0x%p\n", (void *)arg0);
    }

    php*:::oci8-connection-close
    {
        printf("%lld: PHP oci8-connect-close\n", walltimestamp);
        printf("  connection=0x%p\n", (void *)arg0);
    }

    php*:::oci8-error
    {
        printf("%lld: PHP oci8-error\n", walltimestamp);
        printf("  status=%d\n", (int)arg0);
        printf("  errcode=%ld\n", (long)arg1);
    }

    php*:::oci8-check-connection
    {
        printf("%lld: PHP oci8-check-connection\n", walltimestamp);
        printf("  connection=0x%p\n", (void *)arg0);
        printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
        printf("  is_open=%d\n", arg2);
        printf("  errcode=%ld\n", (long)arg3);
        printf("  server_status=%lu\n", (unsigned long)arg4);
    }

    php*:::oci8-sqltext
    {
        printf("%lld: PHP oci8-sqltext\n", walltimestamp);
        printf("  connection=0x%p\n", (void *)arg0);
        printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
        printf("  statement=0x%p\n", (void *)arg2);
        printf("  sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
    }

    php*:::oci8-execute-mode
    {
        printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
        printf("  connection=0x%p\n", (void *)arg0);
        printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
        printf("  statement=0x%p\n", (void *)arg2);
        printf("  mode=0x%x\n", arg3);
    }

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 when no PHP executable was running because it knows none of the probes to be monitored are in existence.

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 helps reduce confusion.

The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:

    # ./user_oci8_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:

    1381794982092854582: PHP connect-entry
      credentials="hr@localhost/pdborcl"
      charset=""
      session_mode=0
      persistent=0
      exclusive=0
    1381794982183158766: PHP oci8-connect-return
      connection=0x7f4a7907bfb8
    1381794982183594576: PHP oci8-sqltext
      connection=0x7f4a7907bfb8
      client_id="Chris"
      statement=0x7f4a7907c2a0
      sql="select * from employees"
    1381794982183783706: PHP oci8-execute-mode
      connection=0x7f4a7907bfb8
      client_id="Chris"
      statement=0x7f4a7907c2a0
      mode=0x20
    1381794982444344390: PHP oci8-connect-close
      connection=0x7f4a7907bfb8

When monitoring is complete, the D script can be terminated with a ``CTRL`+`C``.

## See Also

- DTrace Dynamic Tracing

# Supported Datatypes

The driver supports the following types when binding parameters using the oci_bind_by_name() function:
Type | Mapping
--- | ---
`SQLT_NTY` | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
`SQLT_BFILEE` | Maps a native descriptor, such as those created by oci_new_descriptor().
`SQLT_CFILEE` | Maps a native descriptor, such as those created by oci_new_descriptor().
`SQLT_CLOB` | Maps a native descriptor, such as those created by oci_new_descriptor().
`SQLT_BLOB` | Maps a native descriptor, such as those created by oci_new_descriptor().
`SQLT_RDD` | Maps a native descriptor, such as those created by oci_new_descriptor().
`SQLT_NUM` | Converts the PHP parameter to a 'C' long type, and binds to that value.
`SQLT_RSET` | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
`SQLT_BOL` | Bind the PHP parameter to a PL/SQL BOOLEAN
`SQLT_CHR` and any other type | Converts the PHP parameter to a string type and binds as a string.

The following types are supported when retrieving columns from a result set:
Type | Mapping
--- | ---
`SQLT_RSET` | Creates an oci statement resource to represent the cursor.
`SQLT_RDD` | Creates a ROWID object.
`SQLT_BLOB` | Creates a LOB object.
`SQLT_CLOB` | Creates a LOB object.
`SQLT_BFILE` | Creates a LOB object.
`SQLT_LNG` | Bound as SQLT_CHR, returned as a string
`SQLT_LBI` | Bound as `SQLT_BIN`, returned as a string
Any other type | Bound as `SQLT_CHR`, returned as a string

# OCI8 Functions

# oci_bind_array_by_name

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter

### Description

oci_bind_array_by_name(
resource `$statement`,
string `$param`,
array `&$var`,
int `$max_array_length`,
int `$max_item_length` = -1,
int `$type` = `SQLT_AFC`
): bool

Binds the PHP array `var` to the Oracle placeholder `param`, which points to an Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

### Parameters

`statement`

  A valid OCI statement identifier.

`param`

  The Oracle placeholder.

`var`

  An array.

`max_array_length`

  Sets the maximum length both for incoming and result arrays.

`max_item_length`

  Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will find the longest element in the incoming array and will use it as the maximum length.

`type`

  Should be used to set the type of PL/SQL array items. See list of available types below:

  - `SQLT_NUM` - for arrays of NUMBER.

  - `SQLT_INT` - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but `SQLT_NUM` type won't work in this case even though they are synonyms).

  - `SQLT_FLT` - for arrays of FLOAT.

  - `SQLT_AFC` - for arrays of CHAR.

  - `SQLT_CHR` - for arrays of VARCHAR2.

  - `SQLT_VCS` - for arrays of VARCHAR.

  - `SQLT_AVC` - for arrays of CHARZ.

  - `SQLT_STR` - for arrays of STRING.

  - `SQLT_LVC` - for arrays of LONG VARCHAR.

  - `SQLT_ODT` - for arrays of DATE.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 oci_bind_array_by_name() example

`<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$stid = oci_parse($conn, $create);
oci_execute($stid);
$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg);
oci_execute($stid);
$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
CURSOR CUR IS SELECT name FROM bind_example;
PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
BEGIN
-- Bulk Insert
FORALL i IN INDICES OF c1
INSERT INTO bind_example VALUES (c1(i));
-- Fetch and reverse
IF NOT CUR%ISOPEN THEN
OPEN CUR;
END IF;
FOR i IN REVERSE 1..5 LOOP
FETCH CUR INTO c1(i);
IF CUR%NOTFOUND THEN
CLOSE CUR;
EXIT;
END IF;
END LOOP;
END iobind;
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg_body);
oci_execute($stid);
$stid = oci_parse($conn, "BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one", "two", "three", "four", "five");
oci_bind_array_by_name($stid, ":c1", $array, 5, -1, SQLT_CHR);
oci_execute($stid);
var_dump($array);
?>`

# oci_bind_by_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_bind_by_name — Binds a PHP variable to an Oracle placeholder

### Description

oci_bind_by_name(
resource `$statement`,
string `$param`,
mixed `&$var`,
int `$max_length` = -1,
int `$type` = 0
): bool

Binds a PHP variable `var` to the Oracle bind variable placeholder `param`. Binding is important for Oracle database performance and also as a way to avoid SQL Injection security issues.

Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.

PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.

In Oracle, bind variables are commonly divided into `IN` binds for values that are passed into the database, and `OUT` binds for values that are returned to PHP. A bind variable may be both `IN` and `OUT`. Whether a bind variable will be used for input or output is determined at run-time.

You must specify `max_length` when using an `OUT` bind so that PHP allocates enough memory to hold the returned value.

For `IN` binds it is recommended to set the `max_length` length if the statement is re-executed multiple times with different values for the PHP variable. Otherwise Oracle may truncate data to the length of the initial PHP variable value. If you don't know what the maximum length will be, then re-call oci_bind_by_name() with the current data size prior to each oci_execute() call. Binding an unnecessarily large length will have an impact on process memory in the database.

A bind call tells Oracle which memory address to read data from. For `IN` binds that address needs to contain valid data when oci_execute() is called. This means that the variable bound must remain in scope until execution. If it doesn't, unexpected results or errors such as "ORA-01460: unimplemented or unreasonable conversion requested" may occur. For `OUT` binds one symptom is no value being set in the PHP variable.

For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.

### Parameters

`statement`

  A valid OCI8 statement identifier.

`param`

  The colon-prefixed bind variable placeholder used in the statement. The colon is optional in `param`. Oracle does not use question marks for placeholders.

`var`

  The PHP variable to be associated with `param`

`max_length`

  Sets the maximum length for the data. If you set it to -1, this function will use the current length of `var` to set the maximum length. In this case the `var` must exist and contain data when oci_bind_by_name() is called.

`type`

  The datatype that Oracle will treat the data as. The default `type` used is `SQLT_CHR`. Oracle will convert the data between this type and the database column (or PL/SQL variable type), when possible.

  If you need to bind an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using the oci_new_descriptor() function. The `length` is not used for abstract datatypes and should be set to -1.

  Possible values for `type` are:

  - `SQLT_BFILEE` or `OCI_B_BFILE` - for BFILEs;

  - `SQLT_CFILEE` or `OCI_B_CFILEE` - for CFILEs;

  - `SQLT_CLOB` or `OCI_B_CLOB` - for CLOBs;

  - `SQLT_BLOB` or `OCI_B_BLOB` - for BLOBs;

  - `SQLT_RDD` or `OCI_B_ROWID` - for ROWIDs;

  - `SQLT_NTY` or `OCI_B_NTY` - for named datatypes;

  - `SQLT_INT` or `OCI_B_INT` - for integers;

  - `SQLT_CHR` - for VARCHARs;

  - `SQLT_BIN` or `OCI_B_BIN` - for RAW columns;

  - `SQLT_LNG` - for LONG columns;

  - `SQLT_LBI` - for LONG RAW columns;

  - `SQLT_RSET` - for cursors created with oci_new_cursor();

  - `SQLT_BOL` or `OCI_B_BOL` - for PL/SQL BOOLEANs (Requires Oracle Database 12c)

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Inserting data with oci_bind_by_name()

`<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");
$id = 1;
$text = "Data to insert ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);
// Table now contains: 1, 'Data to insert '
?>`

Example #2 Binding once for multiple executions

`<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$a = array(1,3,5,7,11); // data to insert
$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
$r = oci_execute($stid, OCI_DEFAULT); // don't auto commit
}
oci_commit($conn); // commit everything at once
// Table contains five rows: 1, 3, 5, 7, 11
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 Binding with a `foreach` loop

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);
$ba = array(':dname' => 'IT Support', ':loc' => 1700);
foreach ($ba as $key => $val) {
// oci_bind_by_name($stid, $key, $val) does not work
// because it binds each placeholder to the same location: $val
// instead use the actual location of the data: $ba[$key]
oci_bind_by_name($stid, $key, $ba[$key]);
}
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
print $item."<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>`

Example #4 Binding in a WHERE clause

`<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}
// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa
oci_free_statement($stid);
oci_close($conn);
?>`

Example #5 Binding with a LIKE clause

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%'; // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// South Brunswick
// South San Francisco
// Southlake
oci_free_statement($stid);
oci_close($conn);
?>`

Example #6 Binding with REGEXP_LIKE

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// Beijing
// Singapore
oci_free_statement($stid);
oci_close($conn);
?>`

For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.

Example #7 Binding Multiple Values in an IN Clause

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
print $name ."<br>\n";
}
// Output is
// Ernst
// Hunold
oci_free_statement($stid);
oci_close($conn);
?>`

Example #8 Binding a ROWID returned by a query

`<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
// INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
// COMMIT;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];
// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);
// The table now contains 1, 100, CHRIS
oci_free_statement($stid);
oci_close($conn);
?>`

Example #9 Binding a ROWID on INSERT

`<?php
// This example inserts an id & name, and then updates the salary
// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
RETURNING ROWID INTO :rid";
$ins_stid = oci_parse($conn, $sql);
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv", $id, 10);
oci_bind_by_name($ins_stid, ":name_bv", $name, 32);
oci_bind_by_name($ins_stid, ":rid", $rowid, -1, OCI_B_ROWID);
$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary, 32);
// ids and names to insert
$data = array(1111 => "Larry",
2222 => "Bill",
3333 => "Jim");
// Salary of each person
$salary = 10000;
// Insert and immediately update each row
foreach ($data as $id => $name) {
oci_execute($ins_stid);
oci_execute($upd_stid);
}
$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);
// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
var_dump($row);
}
oci_free_statement($stid);
oci_close($conn);
?>`

Example #10 Binding for a PL/SQL stored function

`<?php
// Before running the PHP program, create a stored function in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
// BEGIN
// RETURN p * 3;
// END;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$p = 8;
$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);
oci_execute($stid);
print "$r\n"; // prints 24
oci_free_statement($stid);
oci_close($conn);
?>`

Example #11 Binding parameters for a PL/SQL stored procedure

`<?php
// Before running the PHP program, create a stored procedure in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
// BEGIN
// p2 := p1 * 2;
// END;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$p1 = 8;
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>`

Example #12 Binding a CLOB column

`<?php
// Before running, create the table:
// CREATE TABLE mytab (mykey NUMBER, myclob CLOB);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$mykey = 12343; // arbitrary key for this example;
$sql = "INSERT INTO mytab (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";
$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';
?>`

Example #13 Binding a PL/SQL BOOLEAN

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$plsql =
"begin
:output1 := true;
:output2 := false;
end;";
$s = oci_parse($c, $plsql);
oci_bind_by_name($s, ':output1', $output1, -1, OCI_B_BOL);
oci_bind_by_name($s, ':output2', $output2, -1, OCI_B_BOL);
oci_execute($s);
var_dump($output1); // true
var_dump($output2); // false
?>`

### Notes

Warning

Do not use addslashes() and oci_bind_by_name() simultaneously as no quoting is needed. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.

> Note:

> If you bind a string to a `CHAR` column in a `WHERE` clause, remember that Oracle uses blank-padded comparison semantics for `CHAR` columns. Your PHP variable should be blank padded to the same width as the column for the `WHERE` clause to succeed.

> Note:

> The PHP `var` argument is a reference. Some forms of loops do not work as expected:

> `<?php
> foreach ($myarray as $key => $value) {
> oci_bind_by_name($stid, $key, $value);
> }
> ?>`

> This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:

> `<?php
> foreach ($myarray as $key => $value) {
> oci_bind_by_name($stid, $key, $myarray[$key]);
> }
> ?>`

### See Also

- oci_bind_array_by_name() - Binds a PHP array to an Oracle PL/SQL array parameter
- oci_parse() - Prepares an Oracle statement for execution

# oci_cancel

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_cancel — Cancels reading from cursor

### Description

oci_cancel(resource `$statement`): bool

Invalidates a cursor, freeing all associated resources and cancels the ability to read from it.

### Parameters

`statement`

  An OCI statement.

### Return Values

Returns `true` on success or `false` on failure.

# oci_client_version

(PHP 5 >= 5.3.7, PHP 7, PHP 8, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

### Description

oci_client_version(): string

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

### Parameters

None

### Return Values

Returns the version number as a string.

### Examples

Example #1 oci_client_version() example

`<?php
echo "Client Version: " . oci_client_version(); // Client version: 19.9.0.0.0
?>`

### Notes

> Note:

> Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.

### See Also

- oci_server_version() - Returns the Oracle Database version

# oci_close

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_close — Closes an Oracle connection

### Description

oci_close(resource `$connection`): ?bool

Unsets `connection`. The underlying database connection is closed if no other resources are using it and if it was created with oci_connect() or oci_new_connect().

It is recommended to close connections that are no longer needed because this makes database resources available for other users.

### Parameters

`connection`

  An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

### Return Values

Returns `null` when oci8.old_oci_close_semantics is enabled, or `true` otherwise.

### Examples

Example #1 Closing a connection

Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);
// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 Database connections are not closed until all references are closed

The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM departments'); // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);
oci_close($conn);
// $conn is no longer usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn); // prints NULL
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);
// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);
?>`

Example #3 Closing a connection opened more than once

When database credentials are reused, both connections must be closed before the underlying database connection is closed.

`<?php
$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');
// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);
oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1); // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2); // displays that $conn2 is still a valid connection resource
?>`

Example #4 Connections are closed when variables go out of scope

When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.

`<?php
function myfunc() {
$conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
return "Finished";
}
$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.
print $r; // displays the function return value "Finished"
?>`

### Notes

> Note:

> Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.

> Note:

> The oci_close() function does not close the underlying database connections created with oci_pconnect().

### See Also

- oci_connect() - Connect to an Oracle database
- oci_free_statement() - Frees all resources associated with statement or cursor

# oci_commit

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_commit — Commits the outstanding database transaction

### Description

oci_commit(resource `$connection`): bool

Commits the outstanding transaction for the Oracle `connection`. A commit ends the current transaction and makes permanent all changes. It releases all locks held.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the `OCI_NO_AUTO_COMMIT` flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 oci_commit() example

`<?php
// Insert into several tables, rolling back the changes if an error occurs
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
// Commit the changes to both tables
$r = oci_commit($conn);
if (!$r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>`

### Notes

> Note:

> Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

> Any call to oci_execute() that uses `OCI_COMMIT_ON_SUCCESS` mode explicitly or by default will commit any previous uncommitted transaction.

> Any Oracle DDL statement such as `CREATE` or `DROP` will automatically commit any uncommitted transaction.

### See Also

- oci_execute() - Executes a statement
- oci_rollback() - Rolls back the outstanding database transaction

# oci_connect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

### Description

oci_connect(
string `$username`,
string `$password`,
?string `$connection_string` = `null`,
string `$encoding` = "",
int `$session_mode` = `OCI_DEFAULT`
): resource|false

Returns a connection identifier needed for most other OCI8 operations.

For performance, most applications should use persistent connections with oci_pconnect() instead of oci_connect(). See Connection Handling for general information on connection management and connection pooling.

The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.

### Parameters

`username`

  The Oracle user name.

`password`

  The password for `username`.

`connection_string`

  Contains the `Oracle instance` to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

  If not specified or `null`, PHP uses environment variables such as `TWO_TASK` (on Linux) or `LOCAL` (on Windows) and `ORACLE_SID` to determine the `Oracle instance` to connect to.

  To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Further options were introduced with Oracle 19c, including timeout and keep-alive settings. Refer to Oracle documentation. Service names can be found by running the Oracle utility `lsnrctl status` on the database server machine.

  The tnsnames.ora file can be in the Oracle Net search path, which includes /your/path/to/instantclient/network/admin, $ORACLE_HOME/network/admin and /etc. Alternatively set `TNS_ADMIN` so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

`encoding`

  Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

  If not specified, the Oracle Client libraries determine a character set from the `NLS_LANG` environment variable.

  Passing this parameter can reduce the time taken to connect.

`session_mode`

  This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: `OCI_DEFAULT`, `OCI_SYSOPER` and `OCI_SYSDBA`. If either `OCI_SYSOPER` or `OCI_SYSDBA` were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to `On`.

  PHP 5.3 (PECL OCI8 1.3.4) introduced the `OCI_CRED_EXT` mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The `OCI_CRED_EXT` flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be `On` or `Off`.

  `OCI_CRED_EXT` may be combined with the `OCI_SYSOPER` or `OCI_SYSDBA` modes.

  `OCI_CRED_EXT` is not supported on Windows for security reasons.

### Return Values

Returns a connection identifier or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `connection_string` is now nullable.

### Examples

Example #1 Basic oci_connect() using Easy Connect syntax

`<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

Example #2 Basic oci_connect() using a Network Connect name

`<?php
// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
// MYDB =
// (DESCRIPTION =
// (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
// (CONNECT_DATA =
// (SERVER = DEDICATED)
// (SERVICE_NAME = XE)
// )
// )
$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

Example #3 oci_connect() with an explicit character set

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

Example #4 Using multiple calls to oci_connect()

`<?php
$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');
// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";
function create_table($conn)
{
$stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
oci_execute($stmt);
echo "Created table<br>\n";
}
function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table hallo");
oci_execute($stmt);
echo "Dropped table<br>\n";
}
function insert_data($connname, $conn)
{
$stmt = oci_parse($conn, "insert into hallo
values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname inserted row without committing<br>\n";
}
function rollback($connname, $conn)
{
oci_rollback($conn);
echo "$connname rollback<br>\n";
}
function select_data($connname, $conn)
{
$stmt = oci_parse($conn, "select * from hallo");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname ----selecting<br>\n";
while (oci_fetch($stmt)) {
echo " " . oci_result($stmt, "TEST") . "<br>\n";
}
echo "$connname ----done<br>\n";
}
create_table($c1);
insert_data('c1', $c1); // Insert a row using c1
sleep(2); // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2); // Insert a row using c2
select_data('c1', $c1); // Results of both inserts are returned
select_data('c2', $c2); // Results of both inserts are returned
rollback('c1', $c1); // Rollback using c1
select_data('c1', $c1); // Both inserts have been rolled back
select_data('c2', $c2);
drop_table($c1);
// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";
// Output is:
// c1 is Resource id #5
// c2 is Resource id #5
// Created table
// c1 inserted row without committing
// c2 inserted row without committing
// c1 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c1 ----done
// c2 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c2 ----done
// c1 rollback
// c1 ----selecting
// c1 ----done
// c2 ----selecting
// c2 ----done
// Dropped table
// c1 is
// c2 is Resource id #5
?>`

### Notes

> Note:

> An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

### See Also

- oci_pconnect() - Connect to an Oracle database using a persistent connection
- oci_new_connect() - Connect to the Oracle server using a unique connection
- oci_close() - Closes an Oracle connection

# oci_define_by_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_define_by_name — Associates a PHP variable with a column for query fetches

### Description

oci_define_by_name(
resource `$statement`,
string `$column`,
mixed `&$var`,
int `$type` = 0
): bool

Associates a PHP variable with a column for query fetches using oci_fetch().

The oci_define_by_name() call must occur before executing oci_execute().

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

`column`

  The column name used in the query.

  Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.

`var`

  The PHP variable that will contain the returned column value.

`type`

  The data type to be returned. Generally not needed. Note that Oracle-style data conversions are not performed. For example, `SQLT_INT` will be ignored and the returned data type will still be `SQLT_CHR`.

  You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 oci_define_by_name() example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);
oci_execute($stid);
// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 oci_define_by_name() with case sensitive column names

`<?php
/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);
// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);
oci_execute($stid);
while (oci_fetch($stid)) {
echo "id $id is $mydesc<br>\n";
}
// Displays:
// id 1 is Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 oci_define_by_name() with LOB columns

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit); // $fruit will become a LOB descriptor
oci_execute($stid);
while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>`

Example #4 oci_define_by_name() with an explicit type

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);
oci_execute($stid);
while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_new_descriptor() - Initializes a new empty LOB or FILE descriptor

# oci_error

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

### Description

oci_error(?resource `$connection_or_statement` = `null`): array|false

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

### Parameters

`connection_or_statement`

  For most errors, `connection_or_statement` is the resource handle that was passed to the failing function call. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect() `null` should be passed.

### Return Values

If no error is found, oci_error() returns `false`. Otherwise, oci_error() returns the error information as an associative array.

oci_error() Array Description
Array key | Type | Description
--- | --- | ---
`code` | int | The Oracle error number.
`message` | string | The Oracle error text.
`offset` | int | The byte position of an error in the SQL statement. If there was no statement, this is `0`
`sqltext` | string | The SQL statement text. If there was no statement, this is an empty string.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `connection_or_statement` is now nullable.

### Examples

Example #1 Displaying the Oracle error message after a connection error

`<?php
$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
$e = oci_error(); // For oci_connect errors do not pass a handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>`

Example #2 Displaying the Oracle error message after a parsing error

`<?php
$stid = oci_parse($conn, "select ' from dual"); // note mismatched quote
if (!$stid) {
$e = oci_error($conn); // For oci_parse errors pass the connection handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>`

Example #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error

`<?php
$stid = oci_parse($conn, "select does_not_exist from dual");
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid); // For oci_execute errors pass the statement handle
print htmlentities($e['message']);
print "\n<pre>\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n</pre>\n";
}
?>`

# oci_execute

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_execute — Executes a statement

### Description

oci_execute(resource `$statement`, int `$mode` = `OCI_COMMIT_ON_SUCCESS`): bool

Executes a `statement` previously returned from oci_parse().

After execution, statements like `INSERT` will have data committed to the database by default. For statements like `SELECT`, execution performs the logic of the query. Query results can subsequently be fetched in PHP with functions like oci_fetch_array().

Each parsed statement may be executed multiple times, saving the cost of re-parsing. This is commonly used for `INSERT` statements when data is bound with oci_bind_by_name().

### Parameters

`statement`

  A valid OCI statement identifier.

`mode`

  An optional second parameter can be one of the following constants:

  Execution Modes
  Constant | Description
  --- | ---
  `OCI_COMMIT_ON_SUCCESS` | Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default.
  `OCI_DESCRIBE_ONLY` | Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail.
  `OCI_NO_AUTO_COMMIT` | Do not automatically commit changes.

  Using `OCI_NO_AUTO_COMMIT` mode starts or continues a transaction. Transactions are automatically rolled back when the connection is closed, or when the script ends. Explicitly call oci_commit() to commit a transaction, or oci_rollback() to abort it.

  When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

  If `OCI_NO_AUTO_COMMIT` mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use `OCI_NO_AUTO_COMMIT` mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 oci_execute() for queries

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

Example #2 oci_execute() without specifying a mode example

`<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid); // The row is committed and immediately visible to other users
?>`

Example #3 oci_execute() with `OCI_NO_AUTO_COMMIT` example

`<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
oci_execute($stid, OCI_NO_AUTO_COMMIT);
}
oci_commit($conn); // commits all new values: 1, 2, 3, 4, 5
?>`

Example #4 oci_execute() with different commit modes example

`<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT); // data not committed
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid); // commits both 123 and 456 values
?>`

Example #5 oci_execute() with `OCI_DESCRIBE_ONLY` example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
echo oci_field_name($stid, $i) . "<br>\n";
}
?>`

### Notes

> Note:

> Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.

> Any call to oci_execute() that uses `OCI_COMMIT_ON_SUCCESS` mode explicitly or by default will commit any previous uncommitted transaction.

> Any Oracle DDL statement such as `CREATE` or `DROP` will automatically commit any uncommitted transaction.

> Note:

> Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

### See Also

- oci_parse() - Prepares an Oracle statement for execution

# oci_fetch

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch — Fetches the next row from a query into internal buffers

### Description

oci_fetch(resource `$statement`): bool

Fetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().

See oci_fetch_array() for general information about fetching data.

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

### Return Values

Returns `true` on success or `false` if there are no more rows in the `statement`.

### Examples

Example #1 oci_fetch() with defined variables

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);
oci_execute($stid);
// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 oci_fetch() with oci_result()

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}
// Displays:
// 1000 is Roma
// 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> Will not return rows from Oracle Database Implicit Result Sets. Use oci_fetch_array() instead.

### See Also

- oci_define_by_name() - Associates a PHP variable with a column for query fetches
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_object() - Returns the next row from a query as an object
- oci_fetch_row() - Returns the next row from a query as a numeric array
- oci_result() - Returns field's value from the fetched row

# oci_fetch_all

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array

### Description

oci_fetch_all(
resource `$statement`,
array `&$output`,
int `$offset` = 0,
int `$limit` = -1,
int `$flags` = OCI_FETCHSTATEMENT_BY_COLUMN | OCI_ASSOC
): int

Fetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.

This function can be called only once for each query executed with oci_execute().

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

`output`

  The variable to contain the returned rows.

  LOB columns are returned as strings, where Oracle supports conversion.

  See oci_fetch_array() for more information on how data and types are fetched.

`offset`

  The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

`limit`

  The number of rows to return. The default is -1 meaning return all the rows from `offset` + 1 onwards.

`flags`

  Parameter `flags` indicates the array structure and whether associative arrays should be used.

  oci_fetch_all() Array Structure Modes
  Constant | Description
  --- | ---
  `OCI_FETCHSTATEMENT_BY_ROW` | The outer array will contain one sub-array per query row.
  `OCI_FETCHSTATEMENT_BY_COLUMN` | The outer array will contain one sub-array per query column. This is the default.

  Arrays can be indexed either by column heading or numerically. Only one index mode will be returned.

  oci_fetch_all() Array Index Modes
  Constant | Description
  --- | ---
  `OCI_NUM` | Numeric indexes are used for each column's array.
  `OCI_ASSOC` | Associative indexes are used for each column's array. This is the default.

  Use the addition operator "+" to choose a combination of array structure and index modes.

  Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on `output` to verify the appropriate case to use for each query.

  Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.

### Return Values

Returns the number of rows in `output`, which may be 0 or more.

### Examples

Example #1 oci_fetch_all() example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// var_dump output is:
// 2 rows fetched
// array(2) {
// ["POSTAL_CODE"]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(6) "10934x"
// }
// ["CITY"]=>
// array(2) {
// [0]=>
// string(4) "Roma"
// [1]=>
// string(6) "Venice"
// }
// }
// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 oci_fetch_all() example with `OCI_FETCHSTATEMENT_BY_ROW`

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "00989x"
// ["CITY"]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "10934x"
// ["CITY"]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 oci_fetch_all() with `OCI_NUM`

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// [0]=>
// string(6) "10934x"
// [1]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> Using `offset` is very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.

> Note:

> Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.

> Note:

> For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

> Note:

> Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_object() - Returns the next row from a query as an object
- oci_fetch_row() - Returns the next row from a query as a numeric array
- oci_set_prefetch() - Sets number of rows to be prefetched by queries

# oci_fetch_array

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

### Description

oci_fetch_array(resource `$statement`, int `$mode` = OCI_BOTH | OCI_RETURN_NULLS): array|false

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns `false`, indicating no more rows exist.

If `statement` corresponds to a PL/SQL block returning Oracle Database Implicit Result Sets, then rows from all sets are consecutively fetched. If `statement` is returned by oci_get_implicit_resultset(), then only the subset of rows for one child query are returned.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

  Can also be a statement identifier returned by oci_get_implicit_resultset().

`mode`

  An optional second parameter can be any combination of the following constants:

  oci_fetch_array() Modes
  Constant | Description
  --- | ---
  `OCI_BOTH` | Returns an array with both associative and numeric indices. This is the same as `OCI_ASSOC` + `OCI_NUM` and is the default behavior.
  `OCI_ASSOC` | Returns an associative array.
  `OCI_NUM` | Returns a numeric array.
  `OCI_RETURN_NULLS` | Creates elements for `null` fields. The element values will be a PHP `null`.
  `OCI_RETURN_LOBS` | Returns the contents of LOBs instead of the LOB descriptors.

  The default `mode` is `OCI_BOTH`.

  Use the addition operator "+" to specify more than one mode at a time.

### Return Values

Returns an array with associative and/or numeric indices. If there are no more rows in the `statement` then `false` is returned.

By default, `LOB` columns are returned as LOB descriptors.

`DATE` columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as `NLS_LANG` or by a previously executed `ALTER SESSION SET NLS_DATE_FORMAT` command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

The table name is not included in the array index. If your query contains two different columns with the same name, use `OCI_NUM` or add a column alias to the query to ensure name uniqueness, see example #7. Otherwise only one column will be returned via PHP.

### Examples

Example #1 oci_fetch_array() with `OCI_BOTH`

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
// Use the uppercase column names for the associative array indices
echo $row[0] . " and " . $row['DEPARTMENT_ID'] . " are the same<br>\n";
echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 oci_fetch_array() with `OCI_NUM`

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_NUM)) != false) {
echo $row[0] . "<br>\n";
echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 oci_fetch_array() with `OCI_ASSOC`

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>`

Example #4 oci_fetch_array() with `OCI_RETURN_NULLS`

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC)) != false) { // Ignore NULLs
var_dump($row);
}
/*
The above code prints:
array(1) {
[1]=>
string(1) "1"
}
*/
$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { // Fetch NULLs
var_dump($row);
}
/*
The above code prints:
array(2) {
[1]=>
string(1) "1"
["NULL"]=>
NULL
}
*/
?>`

Example #5 oci_fetch_array() with `OCI_RETURN_LOBS`

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
// Output is:
// 1
// A very long string
oci_free_statement($stid);
oci_close($conn);
?>`

Example #6 oci_fetch_array() with case sensitive column names

`<?php
/*
Before running, create the table:
CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index. However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n"; // prints Chris
print $row['CITY'] . "<br>\n"; // prints Melbourne
oci_free_statement($stid);
oci_close($conn);
?>`

Example #7 oci_fetch_array() with columns having duplicate names

`<?php
/*
Before running, create the tables:
CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
INSERT INTO mycity (id, name) values (1, 'Melbourne');
CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
INSERT INTO mycountry (id, name) values (1, 'Australia');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT mycity.name, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);
// Output only contains one "NAME" entry:
// array(1) {
// ["NAME"]=>
// string(9) "Australia"
// }
// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);
// Output now contains both columns selected:
// array(2) {
// ["CTNM"]=>
// string(9) "Melbourne"
// ["NAME"]=>
// string(9) "Australia"
// }
oci_free_statement($stid);
oci_close($conn);
?>`

Example #8 oci_fetch_array() with `DATE` columns

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);
$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n"; // prints 1997-06-14
oci_free_statement($stid);
oci_close($conn);
?>`

Example #9 oci_fetch_array() with `REF CURSOR`

`<?php
/*
Create the PL/SQL stored procedure as:
CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>`

Example #10 Pagination with oci_fetch_array() using a `LIMIT`-like query

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Find the version of the database
preg_match('/Release ([0-9]+)\./', oci_server_version($conn), $matches);
$oracleversion = $matches[1];
// This is the query you want to "page" through
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';
if ($oracleversion >= 12) {
// Make use of Oracle 12c OFFSET / FETCH NEXT syntax
$sql = $sql . ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
// Older Oracle versions need a nested query selecting a subset
// from $sql. Or, if the SQL statement is known at development
// time, consider using a row_number() function instead of this
// nested solution. In production environments, be careful to
// avoid SQL Injection issues with concatenation.
$sql = "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
FROM ($sql) a
WHERE ROWNUM <= :offset + :numrows)
WHERE my_rnum > :offset";
}
$offset = 0; // skip this many rows
$numrows = 5; // return 5 rows
$stid = oci_parse($conn, $sql);
oci_bind_by_name($stid, ':numrows', $numrows);
oci_bind_by_name($stid, ':offset', $offset);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// Geneva 1730
// Hiroshima 6823
oci_free_statement($stid);
oci_close($conn);
?>`

Example #11 oci_fetch_array() with Oracle Database Implicit Result Sets

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Requires OCI8 2.0 (or later) and Oracle Database 12c (or later)
// Also see oci_get_implicit_resultset()
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

> Note:

> For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

> Note:

> The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_object() - Returns the next row from a query as an object
- oci_fetch_row() - Returns the next row from a query as a numeric array
- oci_set_prefetch() - Sets number of rows to be prefetched by queries

# oci_fetch_assoc

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

### Description

oci_fetch_assoc(resource `$statement`): array|false

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns `false`, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with `OCI_ASSOC` + `OCI_RETURN_NULLS`.

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

### Return Values

Returns an associative array. If there are no more rows in the `statement` then `false` is returned.

### Examples

Example #1 oci_fetch_assoc() Example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_assoc($stid)) != false) {
echo $row['DEPARTMENT_ID'] . " " . $row['DEPARTMENT_NAME'] . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> See oci_fetch_array() for more examples of fetching rows.

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_object() - Returns the next row from a query as an object
- oci_fetch_row() - Returns the next row from a query as a numeric array

# oci_fetch_object

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

### Description

oci_fetch_object(resource `$statement`, int `$mode` = OCI_ASSOC | OCI_RETURN_NULLS): stdClass|false

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns `false`, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

### Return Values

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the `statement` then `false` is returned.

Any `LOB` columns are returned as LOB descriptors.

`DATE` columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as `NLS_LANG` or by a previously executed `ALTER SESSION SET NLS_DATE_FORMAT` command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case for attribute access.

Attribute values will be `null` for any `NULL` data fields.

### Examples

Example #1 oci_fetch_object() example

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
echo $row->DESCRIPTION . "<br>\n";
}
// Output is:
// 1
// Fish and Chips
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 oci_fetch_object() with case sensitive column names

`<?php
/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
// Use the exact case for the case sensitive column name
echo $row->MyDescription . "<br>\n";
}
// Output is:
// 1
// Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 oci_fetch_object() with LOBs

`<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
echo $row->ID . "<br>\n";
// The following will output the first 11 bytes from DESCRIPTION
echo $row->DESCRIPTION->read(11) . "<br>\n";
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_row() - Returns the next row from a query as a numeric array

# oci_fetch_row

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

### Description

oci_fetch_row(resource `$statement`): array|false

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns `false`, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with `OCI_NUM` + `OCI_RETURN_NULLS`.

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

### Return Values

Returns a numerically indexed array. If there are no more rows in the `statement` then `false` is returned.

### Examples

Example #1 oci_fetch_row() Example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_row($stid)) != false) {
echo $row[0] . " " . $row[1] . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> See oci_fetch_array() for more examples of fetching rows.

### See Also

- oci_fetch() - Fetches the next row from a query into internal buffers
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_object() - Returns the next row from a query as an object

# oci_field_is_null

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if a field in the currently fetched row is `null`

### Description

oci_field_is_null(resource `$statement`, string|int `$column`): bool

Checks if the given `column` from the current row of `statement` is `null`.

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns `true` if `column` is `null`, `false` otherwise.

### Examples

Example #1 oci_field_name() example

`<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER);
// INSERT INTO mytab VALUES (1);
// INSERT INTO mytab VALUES (NULL);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) != false) {
$ncols = oci_num_fields($stid);
for ($col = 1; $col <= $ncols; $col++) {
var_dump(oci_field_is_null($stid, $col));
}
}
// Outputs:
// bool(false)
// bool(true)
oci_free_statement($stid);
oci_close($conn);
?>`

# oci_field_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

### Description

oci_field_name(resource `$statement`, string|int `$column`): string|false

Returns the name of the `column`.

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns the name as a string, or `false` on failure

### Examples

Example #1 oci_field_name() example

`<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type
// NUMBER_COL NUMBER
// VARCHAR2_COL VARCHAR2
// CLOB_COL CLOB
// DATE_COL DATE
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_num_fields() - Returns the number of result columns in a statement
- oci_field_type() - Returns a field's data type name
- oci_field_size() - Returns field's size

# oci_field_precision

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

### Description

oci_field_precision(resource `$statement`, string|int `$column`): int|false

Returns precision of the `column`.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns the precision as an integer, or `false` on failure

### Examples

Example #1 oci_field_precision() Example

`<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}
// Outputs:
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_field_scale() - Tell the scale of the field
- oci_field_type() - Returns a field's data type name

# oci_field_scale

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

### Description

oci_field_scale(resource `$statement`, string|int `$column`): int|false

Returns the scale of the column with `column` index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns the scale as an integer, or `false` on failure

### Examples

Example #1 oci_field_scale() Example

`<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}
// Outputs:
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_field_precision() - Tell the precision of a field
- oci_field_type() - Returns a field's data type name

# oci_field_size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_size — Returns field's size

### Description

oci_field_size(resource `$statement`, string|int `$column`): int|false

Returns the size of a `column`.

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns the size of a `column` in bytes, or `false` on failure

### Examples

Example #1 oci_field_size() example

`<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_num_fields() - Returns the number of result columns in a statement
- oci_field_name() - Returns the name of a field from the statement

# oci_field_type

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_type — Returns a field's data type name

### Description

oci_field_type(resource `$statement`, string|int `$column`): string|int|false

Returns a field's data type name.

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns the field data type as a string or an int, or `false` on failure

### Examples

Example #1 oci_field_type() example

`<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_num_fields() - Returns the number of result columns in a statement
- oci_field_name() - Returns the name of a field from the statement
- oci_field_size() - Returns field's size

# oci_field_type_raw

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_type_raw — Tell the raw Oracle data type of the field

### Description

oci_field_type_raw(resource `$statement`, string|int `$column`): int|false

Returns Oracle's raw "SQLT" data type of the `column`.

If you want a field's type name, then use oci_field_type() instead.

### Parameters

`statement`

  A valid OCI statement identifier.

`column`

  Can be the field's index (1-based) or name.

### Return Values

Returns Oracle's raw data type as a number, or `false` on failure

### Examples

Example #1 oci_field_type_raw() Example

`<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$n = oci_num_fields($stid);
for ($i = 1; $i <= $n; ++$i) {
echo oci_field_name($stid, $i) . " is raw type: " . oci_field_type_raw($stid, $i) . "<br>\n";
}
// Output is:
// NUMBER_COL is raw type: 2
// VARCHAR2_COL is raw type: 1
// CLOB_COL is raw type: 112
// DATE_COL is raw type: 12
oci_free_statement($stid);
oci_close($conn);
?>`

# oci_free_descriptor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_free_descriptor — Frees a descriptor

### Description

oci_free_descriptor(OCILob `$lob`): bool

Frees a descriptor allocated by oci_new_descriptor().

### Parameters

`lob`

  Descriptor allocated by oci_new_descriptor().

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note:

> This function is commonly used as a method OCILOB::free.

### See Also

- OCILOB::free

# oci_free_statement

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_free_statement — Frees all resources associated with statement or cursor

### Description

oci_free_statement(resource `$statement`): bool

Frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.

### Parameters

`statement`

  A valid OCI statement identifier.

### Return Values

Returns `true` on success or `false` on failure.

# oci_get_implicit_resultset

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL OCI8 >= 2.0.0)

oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets

### Description

oci_get_implicit_resultset(resource `$statement`): resource|false

Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with the Oracle Database 12 (or later) DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.

The child statement can be used with any of the OCI8 fetching functions: oci_fetch(), oci_fetch_all(), oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() or oci_fetch_row()

Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.

### Return Values

Returns a statement handle for the next child statement available on `statement`. Returns `false` when child statements do not exist, or all child statements have been returned by previous calls to oci_get_implicit_resultset().

### Examples

Example #1 Fetching Implicit Result Sets in a loop

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (($stid_c = oci_get_implicit_resultset($stid))) {
echo "<h2>New Implicit Result Set:</h2>\n";
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}
// Output is:
// New Implicit Result Set:
// Beijing 190518
// Bern 3095
// Bombay 490231
// New Implicit Result Set:
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 Getting child statement handles individually

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$stid_1 = oci_get_implicit_resultset($stid);
$stid_2 = oci_get_implicit_resultset($stid);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
// Output is:
// array(2) {
// ["CITY"]=>
// string(7) "Beijing"
// ["POSTAL_CODE"]=>
// string(6) "190518"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CN"
// }
// array(2) {
// ["CITY"]=>
// string(4) "Bern"
// ["POSTAL_CODE"]=>
// string(4) "3095"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CH"
// }
oci_free_statement($stid);
oci_close($conn);
?>`

Example #3 Explicitly setting the Prefetch Count

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$stid_c = oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c, 200); // Set the prefetch before fetching from the child statement
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>`

Example #4 Implicit Result Set example without using oci_get_implicit_resultset()

All results from all queries are returned consecutively.

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

# oci_lob_copy

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

### Description

oci_lob_copy(OCILob `$to`, OCILob `$from`, ?int `$length` = `null`): bool

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use OCILob::seek() to move LOB internal pointers.

### Parameters

`to`

  The destination LOB.

`from`

  The copied LOB.

`length`

  Indicates the length of data to be copied.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `length` is now nullable.

### Notes

> Note:

> The OCILob class was called OCI-Lob prior to PHP 8 and PECL OCI8 3.0.0.

# oci_lob_is_equal

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

### Description

oci_lob_is_equal(OCILob `$lob1`, OCILob `$lob2`): bool

Compares two LOB/FILE locators.

### Parameters

`lob1`

  A LOB identifier.

`lob2`

  A LOB identifier.

### Return Values

Returns `true` if these objects are equal, `false` otherwise.

### Notes

> Note:

> The OCILob class was called OCI-Lob prior to PHP 8 and PECL OCI8 3.0.0.

# oci_new_collection

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

### Description

oci_new_collection(resource `$connection`, string `$type_name`, ?string `$schema` = `null`): OCICollection|false

Allocates a new collection object.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

`type_name`

  Should be a valid named type (uppercase).

`schema`

  Should point to the scheme, where the named type was created. The name of the current user is used when `null` is passed.

### Return Values

Returns a new OCICollection object or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `schema` is now nullable.

### Notes

> Note:

> The OCICollection class was called OCI-Collection prior to PHP 8 and OCI8 3.0.0.

# oci_new_connect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_connect — Connect to the Oracle server using a unique connection

### Description

oci_new_connect(
string `$username`,
string `$password`,
?string `$connection_string` = `null`,
string `$encoding` = "",
int `$session_mode` = `OCI_DEFAULT`
): resource|false

Establishes a new connection to an Oracle server and logs on.

Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.

### Parameters

`username`

  The Oracle user name.

`password`

  The password for `username`.

`connection_string`

  Contains the `Oracle instance` to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

  If not specified or `null`, PHP uses environment variables such as `TWO_TASK` (on Linux) or `LOCAL` (on Windows) and `ORACLE_SID` to determine the `Oracle instance` to connect to.

  To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Further options were introduced with Oracle 19c, including timeout and keep-alive settings. Refer to Oracle documentation. Service names can be found by running the Oracle utility `lsnrctl status` on the database server machine.

  The tnsnames.ora file can be in the Oracle Net search path, which includes /your/path/to/instantclient/network/admin, $ORACLE_HOME/network/admin and /etc. Alternatively set `TNS_ADMIN` so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

`encoding`

  Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

  If not specified, the Oracle Client libraries determine a character set from the `NLS_LANG` environment variable.

  Passing this parameter can reduce the time taken to connect.

`session_mode`

  This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: `OCI_DEFAULT`, `OCI_SYSOPER` and `OCI_SYSDBA`. If either `OCI_SYSOPER` or `OCI_SYSDBA` were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to `On`.

  PHP 5.3 (PECL OCI8 1.3.4) introduced the `OCI_CRED_EXT` mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The `OCI_CRED_EXT` flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be `On` or `Off`.

  `OCI_CRED_EXT` may be combined with the `OCI_SYSOPER` or `OCI_SYSDBA` modes.

  `OCI_CRED_EXT` is not supported on Windows for security reasons.

### Return Values

Returns a connection identifier or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `connection_string` is now nullable.

### Examples

The following demonstrates how you can separate connections.

Example #1 oci_new_connect() example

`<?php
// create table mytab (mycol number);
function query($name, $c)
{
echo "Querying $name\n";
$s = oci_parse($c, "select * from mytab");
oci_execute($s, OCI_NO_AUTO_COMMIT);
$row = oci_fetch_array($s, OCI_ASSOC);
if (!$row) {
echo "No rows\n";
} else {
do {
foreach ($row as $item)
echo $item . " ";
echo "\n";
} while (($row = oci_fetch_array($s, OCI_ASSOC)) != false);
}
}
$c1 = oci_connect("hr", "welcome", "localhost/orcl");
$c2 = oci_new_connect("hr", "welcome", "localhost/orcl");
$s = oci_parse($c1, "insert into mytab values(1234)");
oci_execute($s, OCI_NO_AUTO_COMMIT);
query("basic connection", $c1);
query("new connection", $c2);
oci_commit($c1);
query("new connection after commit", $c2);
// Output is:
// Querying basic connection
// 1234
// Querying new connection
// No rows
// Querying new connection after commit
// 1234
?>`

See oci_connect() for further examples of parameter usage.

### See Also

- oci_connect() - Connect to an Oracle database
- oci_pconnect() - Connect to an Oracle database using a persistent connection

# oci_new_cursor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_cursor — Allocates and returns a new cursor (statement handle)

### Description

oci_new_cursor(resource `$connection`): resource|false

Allocates a new statement handle on the specified connection.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

### Return Values

Returns a new statement handle, or `false` on error.

### Examples

Example #1 Binding a REF CURSOR in an Oracle stored procedure call

`<?php
// Precreate:
// create or replace procedure myproc(myrc out sys_refcursor) as
// begin
// open myrc for select first_name from employees;
// end;
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$curs = oci_new_cursor($conn);
$stid = oci_parse($conn, "begin myproc(:cursbv); end;");
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);
oci_execute($curs); // Execute the REF CURSOR like a normal statement id
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo $row['FIRST_NAME'] . "<br />\n";
}
oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);
?>`

# oci_new_descriptor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_descriptor — Initializes a new empty LOB or FILE descriptor

### Description

oci_new_descriptor(resource `$connection`, int `$type` = `OCI_DTYPE_LOB`): ?OCILob

Allocates resources to hold descriptor or LOB locator.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

`type`

  Valid values for `type` are: `OCI_DTYPE_FILE`, `OCI_DTYPE_LOB` and `OCI_DTYPE_ROWID`.

### Return Values

Returns a new LOB or FILE descriptor on success, or `null` on failure.

### Examples

Example #1 oci_new_descriptor() example

`<?php
/* This script is designed to be called from a HTML form.
* It expects $user, $password, $table, $where, and $commitsize
* to be passed in from the form. The script then deletes
* the selected rows using the ROWID and commits after each
* set of $commitsize rows. (Use with care, there is no rollback)
*/
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
$nrows = oci_num_rows($stmt);
$delete = oci_parse($conn, "delete from $table where ROWID = :rid");
oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
oci_execute($delete);
echo "$nrows\n";
if (($nrows % $commitsize) == 0) {
oci_commit($conn);
}
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>`
`<?php
/* This script demonstrates file upload to LOB columns
* The formfield used for this example looks like this
* <form action="upload.php" method="post" enctype="multipart/form-data">
* <input type="file" name="lob_upload" />
* ...
*/
if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
} else {
// $lob_upload contains the temporary filename of the uploaded file
// see also the features section on file upload,
// if you would like to use secure uploads
$conn = oci_connect($user, $password);
$lob = oci_new_descriptor($conn, OCI_D_LOB);
$stmt = oci_parse($conn, "insert into $table (id, the_blob)
values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
oci_execute($stmt, OCI_DEFAULT);
if ($lob->savefile($lob_upload)){
oci_commit($conn);
echo "Blob successfully uploaded\n";
}else{
echo "Couldn't upload Blob\n";
}
$lob->free();
oci_free_statement($stmt);
oci_close($conn);
}
?>`

Example #2 oci_new_descriptor() example

`<?php
/* Calling PL/SQL stored procedures which contain clobs as input
* parameters.
* Example PL/SQL stored procedure signature is:
*
* PROCEDURE save_data
* Argument Name Type In/Out Default?
* ------------------------------ ----------------------- ------ --------
* KEY NUMBER(38) IN
* DATA CLOB IN
*
*/
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>`

### See Also

- oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder

# oci_num_fields

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_num_fields — Returns the number of result columns in a statement

### Description

oci_num_fields(resource `$statement`): int

Gets the number of columns in the given `statement`.

### Parameters

`statement`

  A valid OCI statement identifier.

### Return Values

Returns the number of columns as an int.

### Examples

Example #1 oci_num_fields() example

`<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, quantity NUMBER);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " " . oci_field_type($stid, $i) . "<br>\n";
}
// Outputs:
// ID NUMBER
// QUANTITY NUMBER
oci_free_statement($stid);
oci_close($conn);
?>`

# oci_num_rows

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_num_rows — Returns number of rows affected during statement execution

### Description

oci_num_rows(resource `$statement`): int|false

Gets the number of rows affected during statement execution.

### Parameters

`statement`

  A valid OCI statement identifier.

### Return Values

Returns the number of rows affected as an integer, or `false` on failure

### Examples

Example #1 oci_num_rows() example

`<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "create table emp2 as select * from employees");
oci_execute($stid);
echo oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);
$stid = oci_parse($conn, "delete from emp2");
oci_execute($stid, OCI_DEFAULT);
echo oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);
$stid = oci_parse($conn, "drop table emp2");
oci_execute($stid);
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.

# oci_parse

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

### Description

oci_parse(resource `$connection`, string `$sql`): resource|false

Prepares `sql` using `connection` and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Statement identifiers can be freed with oci_free_statement() or by setting the variable to `null`.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`sql`

  The SQL or PL/SQL statement.

  SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").

### Return Values

Returns a statement handle on success, or `false` on error.

### Examples

Example #1 oci_parse() example for SQL statements

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

Example #2 oci_parse() example for PL/SQL statements

`<?php
/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:
CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p1 = 8;
// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>`

### Notes

> Note:

> This function does not validate `sql`. The only way to find out if `sql` is a valid SQL or PL/SQL statement is to execute it.

### See Also

- oci_execute() - Executes a statement
- oci_free_statement() - Frees all resources associated with statement or cursor

# oci_password_change

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_password_change — Changes password of Oracle's user

### Description

oci_password_change(
resource `$connection`,
string `$username`,
string `$old_password`,
string `$new_password`
): bool
oci_password_change(
string `$database_name`,
string `$username`,
string `$old_password`,
string `$new_password`
): resource

Changes password for user with `username`.

The oci_password_change() function is most useful for PHP command-line scripts, or when non-persistent connections are used throughout the PHP application.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

`username`

  The Oracle user name.

`old_password`

  The old password.

`new_password`

  The new password to be set.

`database_name`

  The database name.

### Return Values

When `database_name` is provided, oci_password_change() returns `true` on success, or `false` on failure. When `connection` is provided, oci_password_change() returns the connection resource on success, or `false` on failure.

### Examples

Example #1 oci_password_change() example changing the password of an already connected user

`<?php
$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';
$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "New password is : " . $new_pw . "\n";
?>`

Example #2 oci_password_change() example of connecting and changing the password in one step

`<?php
$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';
$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
$m = oci_error();
if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
// Login and reset password at the same time
$c = oci_password_change($dbase, $user, $current_pw, $new_pw);
if ($c) {
echo "New password is : " . $new_pw . "\n";
}
}
}
if (!$c) { // The original error wasn't 28001, or the password change failed
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
// Use the connection $c
// ...
?>`

### Notes

> Note:

> Changing the password either with this function or directly in Oracle should be done carefully. This is because PHP applications may continue to successfully reuse persistent connections by authenticating with the old password. The best practice is to restart all web servers whenever the user password is changed.

> Note:

> If upgrading the Oracle client libraries or the database from a release prior to 11.2.0.3 to version 11.2.0.3 or higher, oci_password_change() may give the error "ORA-1017: invalid username/password" unless both client and server versions are upgraded at the same time.

> Note:

> The second oci_password_change() syntax is available since OCI8 version 1.1.

# oci_pconnect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_pconnect — Connect to an Oracle database using a persistent connection

### Description

oci_pconnect(
string `$username`,
string `$password`,
?string `$connection_string` = `null`,
string `$encoding` = "",
int `$session_mode` = `OCI_DEFAULT`
): resource|false

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FPM process). See the OCI8 Connection Handling and Connection Pooling section for more information.

### Parameters

`username`

  The Oracle user name.

`password`

  The password for `username`.

`connection_string`

  Contains the `Oracle instance` to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

  If not specified or `null`, PHP uses environment variables such as `TWO_TASK` (on Linux) or `LOCAL` (on Windows) and `ORACLE_SID` to determine the `Oracle instance` to connect to.

  To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Further options were introduced with Oracle 19c, including timeout and keep-alive settings. Refer to Oracle documentation. Service names can be found by running the Oracle utility `lsnrctl status` on the database server machine.

  The tnsnames.ora file can be in the Oracle Net search path, which includes /your/path/to/instantclient/network/admin, $ORACLE_HOME/network/admin and /etc. Alternatively set `TNS_ADMIN` so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

`encoding`

  Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

  If not specified, the Oracle Client libraries determine a character set from the `NLS_LANG` environment variable.

  Passing this parameter can reduce the time taken to connect.

`session_mode`

  This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: `OCI_DEFAULT`, `OCI_SYSOPER` and `OCI_SYSDBA`. If either `OCI_SYSOPER` or `OCI_SYSDBA` were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to `On`.

  PHP 5.3 (PECL OCI8 1.3.4) introduced the `OCI_CRED_EXT` mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The `OCI_CRED_EXT` flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be `On` or `Off`.

  `OCI_CRED_EXT` may be combined with the `OCI_SYSOPER` or `OCI_SYSDBA` modes.

  `OCI_CRED_EXT` is not supported on Windows for security reasons.

### Return Values

Returns a connection identifier or `false` on error.

### Examples

Example #1 Basic oci_pconnect() Example using Easy Connect syntax

`<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_pconnect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>`

See oci_connect() for further examples of parameter usage.

### Notes

> Note: The lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

### See Also

- oci_connect() - Connect to an Oracle database
- oci_new_connect() - Connect to the Oracle server using a unique connection

# oci_register_taf_callback

(PHP 7.0 >= 7.0.21, PHP 8, PHP 7 >= 7.1.7, PHP 8, PECL OCI8 >= 2.1.7)

oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF

### Description

oci_register_taf_callback(resource `$connection`, ?callable `$callback`): bool

Registers a user-defined callback function to `connection`. If `connection` fails due to instance or network failure, the registered callback function will be invoked for several times during failover. See OCI8 Transparent Application Failover (TAF) Support for information.

When oci_register_taf_callback() is called multiple times, each registration overwrites the previous one.

Use oci_unregister_taf_callback() to explicitly unregister a user-defined callback.

TAF callback registration will NOT be saved across persistent connections, therefore the callback needs to be re-registered for a new persistent connection.

### Parameters

`connection`

  An Oracle connection identifier.

`callback`

  A user-defined callback to register for Oracle TAF. It can be a string of the function name or a Closure (anonymous function).

  The interface of a TAF user-defined callback function is as follows:

  userCallbackFn(resource `$connection`, int `$event`, int `$type`): int

  See the parameter description and an example on OCI8 Transparent Application Failover (TAF) Support page.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- oci_unregister_taf_callback() - Unregister a user-defined callback function for Oracle Database TAF

# oci_result

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_result — Returns field's value from the fetched row

### Description

oci_result(resource `$statement`, string|int `$column`): mixed

Returns the data from `column` in the current row, fetched by oci_fetch().

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

### Parameters

`statement`

`column`

  Can be either use the column number (1-based) or the column name. The case of the column name must be the case that Oracle meta data describes the column as, which is uppercase for columns created case insensitively.

### Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns `false` on error.

### Examples

Example #1 oci_fetch() with oci_result()

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}
// Displays:
// 1000 is Roma
// 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci_fetch_array() - Returns the next row from a query as an associative or numeric array
- oci_fetch_assoc() - Returns the next row from a query as an associative array
- oci_fetch_object() - Returns the next row from a query as an object
- oci_fetch_row() - Returns the next row from a query as a numeric array
- oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array

# oci_rollback

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_rollback — Rolls back the outstanding database transaction

### Description

oci_rollback(resource `$connection`): bool

Reverts all uncommitted changes for the Oracle `connection` and ends the transaction. It releases all locks held. All Oracle `SAVEPOINTS` are erased.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the `OCI_NO_AUTO_COMMIT` flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 oci_rollback() example

`<?php
// Insert into several tables, rolling back the changes if an error occurs
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>`

Example #2 Rolling back to a `SAVEPOINT` example

`<?php
$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
oci_commit($conn); // mytab now has id of 1111
?>`

### Notes

> Note:

> Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

> Any call to oci_execute() that uses `OCI_COMMIT_ON_SUCCESS` mode explicitly or by default will commit any previous uncommitted transaction.

> Any Oracle DDL statement such as `CREATE` or `DROP` will automatically commit any uncommitted transaction.

### See Also

- oci_commit() - Commits the outstanding database transaction
- oci_execute() - Executes a statement

# oci_server_version

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_server_version — Returns the Oracle Database version

### Description

oci_server_version(resource `$connection`): string|false

Returns a string with the Oracle Database version and available options

### Parameters

`connection`

### Return Values

Returns the version information as a string or `false` on error.

### Examples

Example #1 oci_server_version() example

`<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
echo "Server Version: " . oci_server_version($conn);
// Displays:
// Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
// With the Partitioning, OLAP, Data Mining and Real Application Testing option
oci_close($conn);
?>`

### See Also

- oci_client_version() - Returns the Oracle client library version

# oci_set_action

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

### Description

oci_set_action(resource `$connection`, string `$action`): bool

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The action name can subsequently be queried from database administration views such as `V$SESSION`. It can be used for tracing and monitoring such as with `V$SQLAREA` and `DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE`.

The value may be retained across persistent connections.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`action`

  User chosen string up to 32 bytes long.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the action

`<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the action
oci_set_action($c, 'Friend Lookup');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>`

    // While the script is running, the administrator can see the actions
    // being performed:

    sqlplus system/welcome
    SQL> select action from v$session;

### Notes

> Note: Oracle version requirement

> This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

# Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle `DBMS_APPLICATION_INFO` package. This is less efficient than using oci_set_client_info().

Caution

# Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

### See Also

- oci_set_module_name() - Sets the module name
- oci_set_client_info() - Sets the client information
- oci_set_client_identifier() - Sets the client identifier
- oci_set_db_operation() - Sets the database operation

# oci_set_call_timeout

(PHP 7.2 >= 7.2.14, PHP 8, PHP 7 >= 7.3.1, PHP 8, PECL OCI8 >= 2.2.0)

oci_set_call_timeout — Sets a millisecond timeout for database calls

### Description

oci_set_call_timeout(resource `$connection`, int `$timeout`): bool

Sets a timeout limiting the maximum time a database round-trip using this connection may take.

Each OCI8 operation may make zero or more calls to Oracle's client library. These internal calls may then may make zero or more round-trips to Oracle Database. If any one of those round-trips takes more than `time_out` milliseconds, then the operation is cancelled and an error is returned to the application.

The `time_out` value applies to each round-trip individually, not to the sum of all round-trips. Time spent processing in PHP OCI8 before or after the completion of each round-trip is not counted.

When a call is interrupted, Oracle will attempt to clean up the connection for reuse. This operation is allowed to run for another `time_out` period. Depending on the outcome of the cleanup, the connection may or may not be reusable.

When persistent connections are used, the timeout value will be retained across PHP requests.

The oci_set_call_timeout() function is available when OCI8 uses Oracle 18 (or later) Client libraries.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`timeout`

  The maximum time in milliseconds that any single round-trip between PHP and Oracle Database may take.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the timeout

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
oci_set_call_timeout($conn, 5000);
?>`

# oci_set_client_identifier

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

### Description

oci_set_client_identifier(resource `$connection`, string `$client_id`): bool

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The identifier can subsequently be queried, for example with `SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') FROM DUAL`. Database administration views such as `V$SESSION` will also contain the value. It can be used with `DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE` for tracing and can also be used for auditing.

The value may be retained across page requests that use the same persistent connection.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`client_id`

  User chosen string up to 64 bytes long.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the client identifier to the application user

`<?php
// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');
// Tell Oracle who that user is
oci_set_client_identifier($c, $un);
// The next round-trip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);
// ...
?>`

### Notes

Caution

# Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

### See Also

- oci_set_module_name() - Sets the module name
- oci_set_action() - Sets the action name
- oci_set_client_info() - Sets the client information
- oci_set_db_operation() - Sets the database operation

# oci_set_client_info

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

### Description

oci_set_client_info(resource `$connection`, string `$client_info`): bool

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The client information can subsequently be queried from database administration views such as `V$SESSION`.

The value may be retained across persistent connections.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`client_info`

  User chosen string up to 64 bytes long.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the client information

`<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the client information
oci_set_client_info($c, 'My Application Version 2');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>`

    // While the script is running, the administrator can see the client
    // information:

    sqlplus system/welcome
    SQL> select client_info from v$session;

### Notes

> Note: Oracle version requirement

> This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

# Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle `DBMS_APPLICATION_INFO` package. This is less efficient than using oci_set_client_info().

Caution

# Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

### See Also

- oci_set_module_name() - Sets the module name
- oci_set_action() - Sets the action name
- oci_set_client_identifier() - Sets the client identifier
- oci_set_db_operation() - Sets the database operation

# oci_set_db_operation

(PHP 7 >= 7.2.14, PHP 8, PHP 7 >= 7.3.1, PHP 8, PECL OCI8 >= 2.2.0)

oci_set_db_operation — Sets the database operation

### Description

oci_set_db_operation(resource `$connection`, string `$action`): bool

Sets the DBOP for Oracle tracing.

The database operation name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when a SQL statement is executed.

The database operation can subsequently be queried from database administration views such as `V$SQL_MONITOR`.

The oci_set_db_operation() function is available when OCI8 uses Oracle 12 (or later) Client libraries and Oracle Database 12 (or later).

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`action`

  User chosen string.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the DBOP

`<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the operation
oci_set_db_operation($c, 'main query');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>`

    // While the script is running, the administrator can see the database operations
    // being performed:

    sqlplus system/welcome
    SQL> select dbop_name from v$sql_monitor;

### Notes

Caution

# Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

### See Also

- oci_set_action() - Sets the action name
- oci_set_module_name() - Sets the module name
- oci_set_client_info() - Sets the client information
- oci_set_client_identifier() - Sets the client identifier

# oci_set_edition

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

### Description

oci_set_edition(string `$edition`): bool

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling oci_connect(), oci_pconnect() or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

### Parameters

`edition`

  Oracle Database edition name previously created with the SQL "`CREATE EDITION`" command.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Two scripts can use different versions of myfunc() at the same time

`<?php
// File 1
echo "Version 1 of application\n";
oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');
$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";
?>`
`<?php
// File 2
echo "Version 2 of application\n";
oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');
$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";
?>`

### Notes

> Note: Oracle version requirement

> This function is available from Oracle 11gR2 onwards.

Caution

# Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Caution

# DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.

# oci_set_module_name

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

### Description

oci_set_module_name(resource `$connection`, string `$name`): bool

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The name can subsequently be queried from database administration views such as `V$SESSION`. It can be used for tracing and monitoring such as with `V$SQLAREA` and `DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE`.

The value may be retained across persistent connections.

### Parameters

`connection`

  An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

`name`

  User chosen string up to 48 bytes long.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Setting the module name

`<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the module
oci_set_module_name($c, 'Home Page');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>`

    // While the script is running, the administrator can see the
    // modules in use:

    sqlplus system/welcome
    SQL> select module from v$session;

### Notes

> Note: Oracle version requirement

> This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

# Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle `DBMS_APPLICATION_INFO` package. This is less efficient than using oci_set_client_info().

Caution

# Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

### See Also

- oci_set_action() - Sets the action name
- oci_set_client_info() - Sets the client information
- oci_set_client_identifier() - Sets the client identifier
- oci_set_db_operation() - Sets the database operation

# oci_set_prefetch

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_set_prefetch — Sets number of rows to be prefetched by queries

### Description

oci_set_prefetch(resource `$statement`, int `$rows`): bool

Sets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.

Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.

Call oci_set_prefetch() before calling oci_execute().

A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.

Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 (or later) Client libraries. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2 or greater.

Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client `oraaccess.xml` configuration file. Refer to Oracle documentation for more detail.

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

`rows`

  The number of rows to be prefetched, >= 0

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Changing the default prefetch value for a query

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300); // Set before calling oci_execute()
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>`

Example #2 Changing the default prefetch for a REF CURSOR fetch

`<?php
/*
Create the PL/SQL stored procedure as:
CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 or later Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>`

If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back to a second PL/SQL procedure for further processing, then set the REF CURSOR prefetch count to `0` to avoid rows being "lost" from the result set. The prefetch value is the number of extra rows fetched in each OCI8 internal request to the database, so setting it to `0` means only fetch one row at a time.

Example #3 Setting the prefetch value when passing a REF CURSOR back to Oracle

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/orcl');
// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);
// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
?>`

### See Also

- oci8.default_prefetch ini option

# oci_set_prefetch_lob

(PHP 8.2, PECL OCI8 >= 3.2)

oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.

### Description

oci_set_prefetch_lob(resource `$statement`, int `$prefetch_lob_size`): bool

Sets the internal buffer size used to fetch each CLOB or BLOB value when the implementation gets the internal Oracle LOB locator from the database after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. Increasing this value can improve the performance of fetching smaller LOBs by reducing round-trips between PHP and the database. Memory usage will change.

The value affects LOBs returned as OCILob instances and also those returned using `OCI_RETURN_LOBS`.

Call oci_set_prefetch_lob() before calling oci_execute(). If it is not called, the value of oci8.prefetch_lob_size is used.

The LOB prefetch value should only be set with Oracle Database 12.2 or later.

### Parameters

`statement`

  A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a `REF CURSOR` statement identifier.

`prefetch_lob_size`

  The number of bytes of each LOB to be prefetched, >= 0

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Changing the LOB prefetch value for a query

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT myclob FROM mytable');
oci_set_prefetch_lob($stid, 100000); // Set before calling oci_execute()
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>`

### See Also

- oci8.prefetch_lob_size ini option

# oci_statement_type

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

### Description

oci_statement_type(resource `$statement`): string|false

Returns a keyword identifying the type of the OCI8 `statement`.

### Parameters

`statement`

  A valid OCI8 statement identifier from oci_parse().

### Return Values

Returns the type of `statement` as one of the following strings.

Statement type
Return String | Notes
--- | ---
`ALTER` |
`BEGIN` |
`CALL` |
`CREATE` |
`DECLARE` |
`DELETE` |
`DROP` |
`INSERT` |
`SELECT` |
`UPDATE` |
`UNKNOWN` |

Returns `false` on error.

### Examples

Example #1 oci_statement_type() example

`<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
oci_execute($stid); // delete the row
}
oci_free_statement($stid);
oci_close($conn);
?>`

# oci_unregister_taf_callback

(PHP 7.0 >= 7.0.23, PHP 8, PHP 7 >= 7.1.9, PHP 8, PECL OCI8 >= 2.1.7)

oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF

### Description

oci_unregister_taf_callback(resource `$connection`): bool

Unregister the user-defined callback function registered to `connection` by oci_register_taf_callback(). See OCI8 Transparent Application Failover (TAF) Support for information.

### Parameters

`connection`

  An Oracle connection identifier.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- oci_register_taf_callback() - Register a user-defined callback function for Oracle Database TAF

## Table of Contents

- oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
- oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
- oci_cancel — Cancels reading from cursor
- oci_client_version — Returns the Oracle client library version
- oci_close — Closes an Oracle connection
- oci_commit — Commits the outstanding database transaction
- oci_connect — Connect to an Oracle database
- oci_define_by_name — Associates a PHP variable with a column for query fetches
- oci_error — Returns the last error found
- oci_execute — Executes a statement
- oci_fetch — Fetches the next row from a query into internal buffers
- oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
- oci_fetch_array — Returns the next row from a query as an associative or numeric array
- oci_fetch_assoc — Returns the next row from a query as an associative array
- oci_fetch_object — Returns the next row from a query as an object
- oci_fetch_row — Returns the next row from a query as a numeric array
- oci_field_is_null — Checks if a field in the currently fetched row is null
- oci_field_name — Returns the name of a field from the statement
- oci_field_precision — Tell the precision of a field
- oci_field_scale — Tell the scale of the field
- oci_field_size — Returns field's size
- oci_field_type — Returns a field's data type name
- oci_field_type_raw — Tell the raw Oracle data type of the field
- oci_free_descriptor — Frees a descriptor
- oci_free_statement — Frees all resources associated with statement or cursor
- oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
- oci_lob_copy — Copies large object
- oci_lob_is_equal — Compares two LOB/FILE locators for equality
- oci_new_collection — Allocates new collection object
- oci_new_connect — Connect to the Oracle server using a unique connection
- oci_new_cursor — Allocates and returns a new cursor (statement handle)
- oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
- oci_num_fields — Returns the number of result columns in a statement
- oci_num_rows — Returns number of rows affected during statement execution
- oci_parse — Prepares an Oracle statement for execution
- oci_password_change — Changes password of Oracle's user
- oci_pconnect — Connect to an Oracle database using a persistent connection
- oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF
- oci_result — Returns field's value from the fetched row
- oci_rollback — Rolls back the outstanding database transaction
- oci_server_version — Returns the Oracle Database version
- oci_set_action — Sets the action name
- oci_set_call_timeout — Sets a millisecond timeout for database calls
- oci_set_client_identifier — Sets the client identifier
- oci_set_client_info — Sets the client information
- oci_set_db_operation — Sets the database operation
- oci_set_edition — Sets the database edition
- oci_set_module_name — Sets the module name
- oci_set_prefetch — Sets number of rows to be prefetched by queries
- oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.
- oci_statement_type — Returns the type of a statement
- oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF

# The OCICollection class

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

## Introduction

OCI8 Collection functionality.

> Note:

> The OCI-Collection class was renamed to OCICollection in PHP 8 OCI8 3.0.0 to align with PHP naming standards.

## Class synopsis

class OCICollection {
/* Methods */
public append(string `$value`): bool
public assign(OCICollection `$from`): bool
public assignElem(int `$index`, string `$value`): bool
public free(): bool
public getElem(int `$index`): string|float|null|false
public max(): int|false
public size(): int|false
public trim(int `$num`): bool
}

# OCICollection::append

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::append — Appends element to the collection

### Description

public OCICollection::append(string `$value`): bool

Appends element to the end of the collection.

### Parameters

`value`

  The value to be added to the collection.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::assign

# OCICollection::assign

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::assign — Assigns a value to the collection from another existing collection

### Description

public OCICollection::assign(OCICollection `$from`): bool

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

### Parameters

`from`

  An instance of OCICollection.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::append

# OCICollection::assignElem

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::assignElem — Assigns a value to the element of the collection

### Description

public OCICollection::assignElem(int `$index`, string `$value`): bool

Assigns a value to the element with index `index`.

### Parameters

`index`

  The element index. First index is 0.

`value`

  Can be a string or a number.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::getElem

# OCICollection::free

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::free — Frees the resources associated with the collection object

### Description

public OCICollection::free(): bool

Frees the resources associated with the collection object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- oci_new_collection

# OCICollection::getElem

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::getElem — Returns value of the element

### Description

public OCICollection::getElem(int `$index`): string|float|null|false

Returns element's value with the index `index` (0-based).

### Parameters

`index`

  The element index. First index is 0.

### Return Values

Returns `false` if such element doesn't exist; `null` if element is `null`; string if element is column of a string datatype or number if element is numeric field.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::assignElem

# OCICollection::max

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::max — Returns the maximum number of elements in the collection

### Description

public OCICollection::max(): int|false

Returns the maximum number of elements in the collection.

### Parameters

This function has no parameters.

### Return Values

Returns the maximum number as an integer, or `false` on errors.

If the returned value is 0, then the number of elements is not limited.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::size

# OCICollection::size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::size — Returns size of the collection

### Description

public OCICollection::size(): int|false

Returns the size of the collection.

### Parameters

This function has no parameters.

### Return Values

Returns the number of elements in the collection or `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::max

# OCICollection::trim

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::trim — Trims elements from the end of the collection

### Description

public OCICollection::trim(int `$num`): bool

Trims `num` of elements from the end of the collection.

### Parameters

`num`

  The number of elements to be trimmed.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

### See Also

- OCICollection::size

## Table of Contents

- OCICollection::append — Appends element to the collection
- OCICollection::assign — Assigns a value to the collection from another existing collection
- OCICollection::assignElem — Assigns a value to the element of the collection
- OCICollection::free — Frees the resources associated with the collection object
- OCICollection::getElem — Returns value of the element
- OCICollection::max — Returns the maximum number of elements in the collection
- OCICollection::size — Returns size of the collection
- OCICollection::trim — Trims elements from the end of the collection

# The OCILob class

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

## Introduction

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

> Note:

> The OCI-Lob class was renamed to OCILob in PHP 8 and PECL OCI8 3.0.0 to align with PHP naming standards.

## Class synopsis

class OCILob {
/* Methods */
public append(OCILob `$from`): bool
public close(): bool
public eof(): bool
public erase(?int `$offset` = `null`, ?int `$length` = `null`): int|false
public export(string `$filename`, ?int `$offset` = `null`, ?int `$length` = `null`): bool
public flush(int `$flag` = 0): bool
public free(): bool
public getBuffering(): bool
public import(string `$filename`): bool
public load(): string|false
public read(int `$length`): string|false
public rewind(): bool
public save(string `$data`, int `$offset` = 0): bool
public seek(int `$offset`, int `$whence` = `OCI_SEEK_SET`): bool
public setBuffering(bool `$mode`): bool
public size(): int|false
public tell(): int|false
public truncate(int `$length` = 0): bool
public write(string `$data`, ?int `$length` = `null`): int|false
public writeTemporary(string `$data`, int `$type` = `OCI_TEMP_CLOB`): bool
}

# OCILob::append

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::append — Appends data from the large object to another large object

### Description

public OCILob::append(OCILob `$from`): bool

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCILob::flush before disabling buffering.

### Parameters

`from`

  The copied LOB.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::flush
- OCILob::setBuffering
- OCILob::getBuffering

# OCILob::close

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::close — Closes LOB descriptor

### Description

public OCILob::close(): bool

Closes descriptor of LOB or FILE. This function should be used only with OCILob::writeTemporary.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::writeTemporary

# OCILob::eof

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::eof — Tests for end-of-file on a large object's descriptor

### Description

public OCILob::eof(): bool

Tells whether the internal pointer of large object is at the end of LOB.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if internal pointer of large object is at the end of LOB. Otherwise returns `false`.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### Notes

> Note:

> This function will return an Oracle error if OCILob::setBuffering is enabled on the LOB.

### See Also

- OCILob::size

# OCILob::erase

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::erase — Erases a specified portion of the internal LOB data

### Description

public OCILob::erase(?int `$offset` = `null`, ?int `$length` = `null`): int|false

Erases a specified portion of the internal LOB data starting at a specified `offset`. If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

### Parameters

`offset`

`length`

### Return Values

Returns the actual number of characters/bytes erased or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `offset` and `length` are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::truncate

# OCILob::export

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::export — Exports LOB's contents to a file

### Description

public OCILob::export(string `$filename`, ?int `$offset` = `null`, ?int `$length` = `null`): bool

Exports LOB contents to a file.

### Parameters

`filename`

  Path to the file.

`offset`

  Indicates from where to start exporting.

`length`

  Indicates the length of data to be exported.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `offset` and `length` are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::import

# OCILob::flush

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::flush — Flushes/writes buffer of the LOB to the server

### Description

public OCILob::flush(int `$flag` = 0): bool

OCILob::flush() actually writes data to the server.

### Parameters

`flag`

  By default, resources are not freed, but using flag `OCI_LOB_BUFFER_FREE` you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use `OCI_LOB_BUFFER_FREE` flag only when you are not going to work with the LOB anymore.

### Return Values

Returns `true` on success or `false` on failure.

Returns `false` if buffering was not enabled or an error occurred.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::getBuffering
- OCILob::setBuffering

# OCILob::free

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::free — Frees resources associated with the LOB descriptor

### Description

public OCILob::free(): bool

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

# OCILob::getBuffering

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::getBuffering — Returns current state of buffering for the large object

### Description

public OCILob::getBuffering(): bool

Tells whether the buffering for the large object is on or off.

### Parameters

This function has no parameters.

### Return Values

Returns `false` if buffering for the large object is off and `true` if buffering is used.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::setBuffering

# OCILob::import

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::import — Imports file data to the LOB

### Description

public OCILob::import(string `$filename`): bool

Writes data from the `filename` in to the current position of large object.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::export
- OCILob::write

# OCILob::load

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::load — Returns large object's contents

### Description

public OCILob::load(): string|false

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCILob::read instead.

### Parameters

This function has no parameters.

### Return Values

Returns the contents of the object, or `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::read

# OCILob::read

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::read — Reads part of the large object

### Description

public OCILob::read(int `$length`): string|false

Reads `length` of bytes (BLOB) or characters (CLOB) from the current position of LOB's internal pointer.

Reading stops when `length` of bytes have been read for a BLOB, when `length` of characters have been read for a CLOB, or when the end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes/characters read.

### Parameters

`length`

  The length of data to read, in bytes (BLOB) or characters (CLOB). Large values will be rounded down to 1 MB.

### Return Values

Returns the contents as a string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::load
- OCILob::write

# OCILob::rewind

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::rewind — Moves the internal pointer to the beginning of the large object

### Description

public OCILob::rewind(): bool

Sets the internal pointer to the beginning of the large object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::seek
- OCILob::tell

# OCILob::save

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::save — Saves data to the large object

### Description

public OCILob::save(string `$data`, int `$offset` = 0): bool

Saves `data` to the large object.

### Parameters

`data`

  The data to be saved.

`offset`

  Can be used to indicate offset from the beginning of the large object.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::write
- OCILob::import

# OCILob::saveFile

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::saveFile — Alias of OCILob::import()

### Description

This function is an alias of: OCILob::import().

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

# OCILob::seek

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::seek — Sets the internal pointer of the large object

### Description

public OCILob::seek(int `$offset`, int `$whence` = `OCI_SEEK_SET`): bool

Sets the internal pointer of the large object.

### Parameters

`offset`

  Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by `whence`.

`whence`

  May be one of:

  - `OCI_SEEK_SET` - sets the position equal to `offset`
  - `OCI_SEEK_CUR` - adds `offset` bytes to the current position
  - `OCI_SEEK_END` - adds `offset` bytes to the end of large object (use negative value to move to a position before the end of large object)

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::rewind
- OCILob::tell
- OCILob::eof

# OCILob::setBuffering

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::setBuffering — Changes current state of buffering for the large object

### Description

public OCILob::setBuffering(bool `$mode`): bool

Sets the buffering for the large object, depending on the value of the `mode` parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. OCILob::flush() should be used to flush buffers, when you have finished working with the large object.

### Parameters

`mode`

  `true` for on and `false` for off.

### Return Values

Returns `true` on success or `false` on failure. Repeated calls to this method with the same flag will return `true`.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::getBuffering

# OCILob::size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::size — Returns size of large object

### Description

public OCILob::size(): int|false

Gets the size of the large object.

### Parameters

This function has no parameters.

### Return Values

Returns length of large object value or `false` on failure. Empty objects have zero length.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

# OCILob::tell

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::tell — Returns the current position of internal pointer of large object

### Description

public OCILob::tell(): int|false

Gets the current position of a LOB's internal pointer.

### Parameters

This function has no parameters.

### Return Values

Returns current position of a LOB's internal pointer or `false` if an error occurred.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::rewind
- OCILob::size
- OCILob::eof

# OCILob::truncate

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::truncate — Truncates large object

### Description

public OCILob::truncate(int `$length` = 0): bool

Truncates the LOB.

### Parameters

`length`

  If provided, this method will truncate the LOB to `length` bytes. Otherwise, it will completely purge the LOB.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::erase

# OCILob::write

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::write — Writes data to the large object

### Description

public OCILob::write(string `$data`, ?int `$length` = `null`): int|false

Writes data from the parameter `data` into the current position of LOB's internal pointer.

### Parameters

`data`

  The data to write in the LOB.

`length`

  If this parameter is an integer, writing will stop after `length` bytes have been written or the end of `data` is reached, whichever comes first.

### Return Values

Returns the number of bytes written or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `length` is now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::read

# OCILob::writeTemporary

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::writeTemporary — Writes a temporary large object

### Description

public OCILob::writeTemporary(string `$data`, int `$type` = `OCI_TEMP_CLOB`): bool

Creates a temporary large object and writes `data` to it.

You should use OCILob::close when you are done with this object.

### Parameters

`data`

  The data to write.

`type`

  Can be one of the following:

  - `OCI_TEMP_BLOB` is used to create temporary BLOBs
  - `OCI_TEMP_CLOB` is used to create temporary CLOBs

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

### See Also

- OCILob::close

# OCILob::writeToFile

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::writeToFile — Alias of OCILob::export()

### Description

This function is an alias of: OCILob::export().

### Changelog

Version | Description
--- | ---
8.0.0, PECL OCI8 3.0.0 | `offset` and `length` are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

## Table of Contents

- OCILob::append — Appends data from the large object to another large object
- OCILob::close — Closes LOB descriptor
- OCILob::eof — Tests for end-of-file on a large object's descriptor
- OCILob::erase — Erases a specified portion of the internal LOB data
- OCILob::export — Exports LOB's contents to a file
- OCILob::flush — Flushes/writes buffer of the LOB to the server
- OCILob::free — Frees resources associated with the LOB descriptor
- OCILob::getBuffering — Returns current state of buffering for the large object
- OCILob::import — Imports file data to the LOB
- OCILob::load — Returns large object's contents
- OCILob::read — Reads part of the large object
- OCILob::rewind — Moves the internal pointer to the beginning of the large object
- OCILob::save — Saves data to the large object
- OCILob::saveFile — Alias of OCILob::import
- OCILob::seek — Sets the internal pointer of the large object
- OCILob::setBuffering — Changes current state of buffering for the large object
- OCILob::size — Returns size of large object
- OCILob::tell — Returns the current position of internal pointer of large object
- OCILob::truncate — Truncates large object
- OCILob::write — Writes data to the large object
- OCILob::writeTemporary — Writes a temporary large object
- OCILob::writeToFile — Alias of OCILob::export

# OCI8 Obsolete Aliases and Functions

# oci_internal_debug

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0, PECL OCI8 <= 2.2.0)

oci_internal_debug — Enables or disables internal debug output

### Description

oci_internal_debug(bool `$onoff`): void

Enables or disables internal debug output.

### Parameters

`onoff`

  Set this to `false` to turn debug output off or `true` to turn it on.

### Return Values

No value is returned.

### Notes

> Note:

> This function was removed in PHP 8 and PECL OCI8 3.0.

# ocibindbyname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocibindbyname — Alias of oci_bind_by_name()

### Description

Alias of oci_bind_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicancel

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicancel — Alias of oci_cancel()

### Description

Alias of oci_cancel()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicloselob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ocicloselob — Alias of OCILob::close()

### Description

Alias of OCILob::close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollappend — Alias of OCICollection::append()

### Description

Alias of OCICollection::append()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollassign

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollassign — Alias of OCICollection::assign()

### Description

Alias of OCICollection::assign()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias of OCICollection::assignElem()

### Description

Alias of OCICollection::assignElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias of OCICollection::getElem()

### Description

Alias of OCICollection::getElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollmax — Alias of OCICollection::max()

### Description

Alias of OCICollection::max()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollsize — Alias of OCICollection::size()

### Description

Alias of OCICollection::size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias of OCICollection::trim()

### Description

Alias of OCICollection::trim()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumnisnull

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Alias of oci_field_is_null()

### Description

Alias of oci_field_is_null()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumnname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnname — Alias of oci_field_name()

### Description

Alias of oci_field_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumnprecision

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Alias of oci_field_precision()

### Description

Alias of oci_field_precision()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumnscale

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnscale — Alias of oci_field_scale()

### Description

Alias of oci_field_scale()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumnsize

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnsize — Alias of oci_field_size()

### Description

Alias of oci_field_size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumntype

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumntype — Alias of oci_field_type()

### Description

Alias of oci_field_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicolumntyperaw

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Alias of oci_field_type_raw()

### Description

Alias of oci_field_type_raw()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocicommit

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicommit — Alias of oci_commit()

### Description

Alias of oci_commit()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocidefinebyname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocidefinebyname — Alias of oci_define_by_name()

### Description

Alias of oci_define_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocierror

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocierror — Alias of oci_error()

### Description

Alias of oci_error()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociexecute

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociexecute — Alias of oci_execute()

### Description

Alias of oci_execute()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifetch

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetch — Alias of oci_fetch()

### Description

Alias of oci_fetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifetchinto

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetchinto — Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

### Description

Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifetchstatement

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetchstatement — Alias of oci_fetch_all()

### Description

Alias of oci_fetch_all()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias of OCICollection::free()

### Description

Alias of OCICollection::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifreecursor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreecursor — Alias of oci_free_statement()

### Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifreedesc

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias of OCILob::free()

### Description

Alias of OCILob::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocifreestatement

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreestatement — Alias of oci_free_statement()

### Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociinternaldebug

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0, PECL OCI8 <= 2.2.0)

ociinternaldebug — Alias of oci_internal_debug()

### Description

Alias of oci_internal_debug()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociloadlob

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociloadlob — Alias of OCILob::load()

### Description

Alias of OCILob::load()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocilogoff

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocilogoff — Alias of oci_close()

### Description

Alias of oci_close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocilogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocilogon — Alias of oci_connect()

### Description

Alias of oci_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewcollection — Alias of oci_new_collection()

### Description

Alias of oci_new_collection()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocinewcursor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewcursor — Alias of oci_new_cursor()

### Description

Alias of oci_new_cursor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocinewdescriptor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Alias of oci_new_descriptor()

### Description

Alias of oci_new_descriptor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocinlogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinlogon — Alias of oci_new_connect()

### Description

Alias of oci_new_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocinumcols

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinumcols — Alias of oci_num_fields()

### Description

Alias of oci_num_fields()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociparse

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociparse — Alias of oci_parse()

### Description

Alias of oci_parse()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociplogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociplogon — Alias of oci_pconnect()

### Description

Alias of oci_pconnect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociresult

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociresult — Alias of oci_result()

### Description

Alias of oci_result()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocirollback

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocirollback — Alias of oci_rollback()

### Description

Alias of oci_rollback()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocirowcount

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocirowcount — Alias of oci_num_rows()

### Description

Alias of oci_num_rows()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocisavelob

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisavelob — Alias of OCILob::save()

### Description

Alias of OCILob::save()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocisavelobfile

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias of OCILob::import()

### Description

Alias of OCILob::import()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociserverversion

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociserverversion — Alias of oci_server_version()

### Description

Alias of oci_server_version()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocisetprefetch

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisetprefetch — Alias of oci_set_prefetch()

### Description

Alias of oci_set_prefetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ocistatementtype

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocistatementtype — Alias of oci_statement_type()

### Description

Alias of oci_statement_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociwritelobtofile

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias of OCILob::export()

### Description

Alias of OCILob::export()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

# ociwritetemporarylob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ociwritetemporarylob — Alias of OCILob::writeTemporary()

### Description

Alias of OCILob::writeTemporary()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

## Table of Contents

- oci_internal_debug — Enables or disables internal debug output
- ocibindbyname — Alias of oci_bind_by_name
- ocicancel — Alias of oci_cancel
- ocicloselob — Alias of OCILob::close
- ocicollappend — Alias of OCICollection::append
- ocicollassign — Alias of OCICollection::assign
- ocicollassignelem — Alias of OCICollection::assignElem
- ocicollgetelem — Alias of OCICollection::getElem
- ocicollmax — Alias of OCICollection::max
- ocicollsize — Alias of OCICollection::size
- ocicolltrim — Alias of OCICollection::trim
- ocicolumnisnull — Alias of oci_field_is_null
- ocicolumnname — Alias of oci_field_name
- ocicolumnprecision — Alias of oci_field_precision
- ocicolumnscale — Alias of oci_field_scale
- ocicolumnsize — Alias of oci_field_size
- ocicolumntype — Alias of oci_field_type
- ocicolumntyperaw — Alias of oci_field_type_raw
- ocicommit — Alias of oci_commit
- ocidefinebyname — Alias of oci_define_by_name
- ocierror — Alias of oci_error
- ociexecute — Alias of oci_execute
- ocifetch — Alias of oci_fetch
- ocifetchinto — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
- ocifetchstatement — Alias of oci_fetch_all
- ocifreecollection — Alias of OCICollection::free
- ocifreecursor — Alias of oci_free_statement
- ocifreedesc — Alias of OCILob::free
- ocifreestatement — Alias of oci_free_statement
- ociinternaldebug — Alias of oci_internal_debug
- ociloadlob — Alias of OCILob::load
- ocilogoff — Alias of oci_close
- ocilogon — Alias of oci_connect
- ocinewcollection — Alias of oci_new_collection
- ocinewcursor — Alias of oci_new_cursor
- ocinewdescriptor — Alias of oci_new_descriptor
- ocinlogon — Alias of oci_new_connect
- ocinumcols — Alias of oci_num_fields
- ociparse — Alias of oci_parse
- ociplogon — Alias of oci_pconnect
- ociresult — Alias of oci_result
- ocirollback — Alias of oci_rollback
- ocirowcount — Alias of oci_num_rows
- ocisavelob — Alias of OCILob::save
- ocisavelobfile — Alias of OCILob::import
- ociserverversion — Alias of oci_server_version
- ocisetprefetch — Alias of oci_set_prefetch
- ocistatementtype — Alias of oci_statement_type
- ociwritelobtofile — Alias of OCILob::export
- ociwritetemporarylob — Alias of OCILob::writeTemporary

- Installing/Configuring
  - Requirements
  - Installation
  - Testing
  - Runtime Configuration
- Predefined Constants
- Examples
- OCI8 Connection Handling and Connection Pooling
- OCI8 Fast Application Notification (FAN) Support
- OCI8 Transparent Application Failover (TAF) Support
- OCI8 and DTrace Dynamic Tracing
- Supported Datatypes
- OCI8 Functions
  - oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
  - oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
  - oci_cancel — Cancels reading from cursor
  - oci_client_version — Returns the Oracle client library version
  - oci_close — Closes an Oracle connection
  - oci_commit — Commits the outstanding database transaction
  - oci_connect — Connect to an Oracle database
  - oci_define_by_name — Associates a PHP variable with a column for query fetches
  - oci_error — Returns the last error found
  - oci_execute — Executes a statement
  - oci_fetch — Fetches the next row from a query into internal buffers
  - oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
  - oci_fetch_array — Returns the next row from a query as an associative or numeric array
  - oci_fetch_assoc — Returns the next row from a query as an associative array
  - oci_fetch_object — Returns the next row from a query as an object
  - oci_fetch_row — Returns the next row from a query as a numeric array
  - oci_field_is_null — Checks if a field in the currently fetched row is null
  - oci_field_name — Returns the name of a field from the statement
  - oci_field_precision — Tell the precision of a field
  - oci_field_scale — Tell the scale of the field
  - oci_field_size — Returns field's size
  - oci_field_type — Returns a field's data type name
  - oci_field_type_raw — Tell the raw Oracle data type of the field
  - oci_free_descriptor — Frees a descriptor
  - oci_free_statement — Frees all resources associated with statement or cursor
  - oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
  - oci_lob_copy — Copies large object
  - oci_lob_is_equal — Compares two LOB/FILE locators for equality
  - oci_new_collection — Allocates new collection object
  - oci_new_connect — Connect to the Oracle server using a unique connection
  - oci_new_cursor — Allocates and returns a new cursor (statement handle)
  - oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
  - oci_num_fields — Returns the number of result columns in a statement
  - oci_num_rows — Returns number of rows affected during statement execution
  - oci_parse — Prepares an Oracle statement for execution
  - oci_password_change — Changes password of Oracle's user
  - oci_pconnect — Connect to an Oracle database using a persistent connection
  - oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF
  - oci_result — Returns field's value from the fetched row
  - oci_rollback — Rolls back the outstanding database transaction
  - oci_server_version — Returns the Oracle Database version
  - oci_set_action — Sets the action name
  - oci_set_call_timeout — Sets a millisecond timeout for database calls
  - oci_set_client_identifier — Sets the client identifier
  - oci_set_client_info — Sets the client information
  - oci_set_db_operation — Sets the database operation
  - oci_set_edition — Sets the database edition
  - oci_set_module_name — Sets the module name
  - oci_set_prefetch — Sets number of rows to be prefetched by queries
  - oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.
  - oci_statement_type — Returns the type of a statement
  - oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF
- OCICollection — The OCICollection class
  - OCICollection::append — Appends element to the collection
  - OCICollection::assign — Assigns a value to the collection from another existing collection
  - OCICollection::assignElem — Assigns a value to the element of the collection
  - OCICollection::free — Frees the resources associated with the collection object
  - OCICollection::getElem — Returns value of the element
  - OCICollection::max — Returns the maximum number of elements in the collection
  - OCICollection::size — Returns size of the collection
  - OCICollection::trim — Trims elements from the end of the collection
- OCILob — The OCILob class
  - OCILob::append — Appends data from the large object to another large object
  - OCILob::close — Closes LOB descriptor
  - OCILob::eof — Tests for end-of-file on a large object's descriptor
  - OCILob::erase — Erases a specified portion of the internal LOB data
  - OCILob::export — Exports LOB's contents to a file
  - OCILob::flush — Flushes/writes buffer of the LOB to the server
  - OCILob::free — Frees resources associated with the LOB descriptor
  - OCILob::getBuffering — Returns current state of buffering for the large object
  - OCILob::import — Imports file data to the LOB
  - OCILob::load — Returns large object's contents
  - OCILob::read — Reads part of the large object
  - OCILob::rewind — Moves the internal pointer to the beginning of the large object
  - OCILob::save — Saves data to the large object
  - OCILob::saveFile — Alias of OCILob::import
  - OCILob::seek — Sets the internal pointer of the large object
  - OCILob::setBuffering — Changes current state of buffering for the large object
  - OCILob::size — Returns size of large object
  - OCILob::tell — Returns the current position of internal pointer of large object
  - OCILob::truncate — Truncates large object
  - OCILob::write — Writes data to the large object
  - OCILob::writeTemporary — Writes a temporary large object
  - OCILob::writeToFile — Alias of OCILob::export
- OCI8 Obsolete Aliases and Functions
  - oci_internal_debug — Enables or disables internal debug output
  - ocibindbyname — Alias of oci_bind_by_name
  - ocicancel — Alias of oci_cancel
  - ocicloselob — Alias of OCILob::close
  - ocicollappend — Alias of OCICollection::append
  - ocicollassign — Alias of OCICollection::assign
  - ocicollassignelem — Alias of OCICollection::assignElem
  - ocicollgetelem — Alias of OCICollection::getElem
  - ocicollmax — Alias of OCICollection::max
  - ocicollsize — Alias of OCICollection::size
  - ocicolltrim — Alias of OCICollection::trim
  - ocicolumnisnull — Alias of oci_field_is_null
  - ocicolumnname — Alias of oci_field_name
  - ocicolumnprecision — Alias of oci_field_precision
  - ocicolumnscale — Alias of oci_field_scale
  - ocicolumnsize — Alias of oci_field_size
  - ocicolumntype — Alias of oci_field_type
  - ocicolumntyperaw — Alias of oci_field_type_raw
  - ocicommit — Alias of oci_commit
  - ocidefinebyname — Alias of oci_define_by_name
  - ocierror — Alias of oci_error
  - ociexecute — Alias of oci_execute
  - ocifetch — Alias of oci_fetch
  - ocifetchinto — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
  - ocifetchstatement — Alias of oci_fetch_all
  - ocifreecollection — Alias of OCICollection::free
  - ocifreecursor — Alias of oci_free_statement
  - ocifreedesc — Alias of OCILob::free
  - ocifreestatement — Alias of oci_free_statement
  - ociinternaldebug — Alias of oci_internal_debug
  - ociloadlob — Alias of OCILob::load
  - ocilogoff — Alias of oci_close
  - ocilogon — Alias of oci_connect
  - ocinewcollection — Alias of oci_new_collection
  - ocinewcursor — Alias of oci_new_cursor
  - ocinewdescriptor — Alias of oci_new_descriptor
  - ocinlogon — Alias of oci_new_connect
  - ocinumcols — Alias of oci_num_fields
  - ociparse — Alias of oci_parse
  - ociplogon — Alias of oci_pconnect
  - ociresult — Alias of oci_result
  - ocirollback — Alias of oci_rollback
  - ocirowcount — Alias of oci_num_rows
  - ocisavelob — Alias of OCILob::save
  - ocisavelobfile — Alias of OCILob::import
  - ociserverversion — Alias of oci_server_version
  - ocisetprefetch — Alias of oci_set_prefetch
  - ocistatementtype — Alias of oci_statement_type
  - ociwritelobtofile — Alias of OCILob::export
  - ociwritetemporarylob — Alias of OCILob::writeTemporary

# PostgreSQL

# Introduction

PostgreSQL database is an open source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

To use PostgreSQL support, you need libpq (the PostgreSQL C client library). As of PHP 8.0.0, libpq 9.1 or later is required. As of PHP 8.4.0, libpq 10.0 or later is required. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at » http://www.postgresql.org/ and the » PostgreSQL Documentation.

## Installation

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. `DIR` is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PostgreSQL configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
pgsql.allow_persistent | "1" | `INI_SYSTEM` |
pgsql.max_persistent | "-1" | `INI_SYSTEM` |
pgsql.max_links | "-1" | `INI_SYSTEM` |
pgsql.auto_reset_persistent | "0" | `INI_SYSTEM` |
pgsql.ignore_notice | "0" | `INI_ALL` |
pgsql.log_notice | "0" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`pgsql.allow_persistent` bool

  Whether to allow persistent Postgres connections.

`pgsql.max_persistent` int

  The maximum number of persistent Postgres connections per process.

`pgsql.max_links` int

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

`pgsql.auto_reset_persistent` int

  Detect broken persistent links with pg_pconnect(). Needs a little overhead.

`pgsql.ignore_notice` int

  Whether or not to ignore PostgreSQL backend notices.

`pgsql.log_notice` int

  Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

## Resource Types

Prior to PHP 8.1.0, there were two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

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

`PGSQL_LIBPQ_VERSION` (string)
  Short libpq version that contains only numbers and dots.
`PGSQL_LIBPQ_VERSION_STR` (string)
  Prior to PHP 8.0.0, the long libpq version that includes compiler information. As of PHP 8.0.0, the value is identical to `PGSQL_LIBPQ_VERSION`, and using `PGSQL_LIBPQ_VERSION_STR` is deprecated.
`PGSQL_ASSOC` (int)
  Passed to pg_fetch_array(). Return an associative array of field names and values.
`PGSQL_NUM` (int)
  Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
`PGSQL_BOTH` (int)
  Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
`PGSQL_CONNECT_FORCE_NEW` (int)
  Passed to pg_connect() to force the creation of a new connection, rather than re-using an existing identical connection.
`PGSQL_CONNECT_ASYNC` (int)
  Passed to pg_connect() to create an asynchronous connection.
`PGSQL_CONNECTION_AUTH_OK` (int)
`PGSQL_CONNECTION_AWAITING_RESPONSE` (int)
`PGSQL_CONNECTION_BAD` (int)
  Returned by pg_connection_status() indicating that the database connection is in an invalid state.
`PGSQL_CONNECTION_MADE` (int)
`PGSQL_CONNECTION_OK` (int)
  Returned by pg_connection_status() indicating that the database connection is in a valid state.
`PGSQL_CONNECTION_SETENV` (int)
`PGSQL_CONNECTION_SSL_STARTUP` (int)
`PGSQL_CONNECTION_STARTED` (int)
`PGSQL_SEEK_SET` (int)
  Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
`PGSQL_SEEK_CUR` (int)
  Passed to pg_lo_seek(). Seek operation is to begin from the current position.
`PGSQL_SEEK_END` (int)
  Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
`PGSQL_EMPTY_QUERY` (int)
  Returned by pg_result_status(). The string sent to the server was empty.
`PGSQL_COMMAND_OK` (int)
  Returned by pg_result_status(). Successful completion of a command returning no data.
`PGSQL_TUPLES_OK` (int)
  Returned by pg_result_status(). Successful completion of a command returning data (such as a `SELECT` or `SHOW`).
`PGSQL_TUPLES_CHUNK` (int)
  Returned by pg_result_status(). Indicates the successful completion of a command returning data in chunked mode. Returned for `SELECT` commands when pg_set_chunked_rows_size() is set. The result set is divided into multiple chunks, each containing a predefined number of rows. Available as of PHP 8.4.0 and libpq 17.
`PGSQL_COPY_OUT` (int)
  Returned by pg_result_status(). Copy Out (from server) data transfer started.
`PGSQL_COPY_IN` (int)
  Returned by pg_result_status(). Copy In (to server) data transfer started.
`PGSQL_BAD_RESPONSE` (int)
  Returned by pg_result_status(). The server's response was not understood.
`PGSQL_NONFATAL_ERROR` (int)
  Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
`PGSQL_FATAL_ERROR` (int)
  Returned by pg_result_status(). A fatal error occurred.
`PGSQL_TRANSACTION_IDLE` (int)
  Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
`PGSQL_TRANSACTION_ACTIVE` (int)
  Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
`PGSQL_TRANSACTION_INTRANS` (int)
  Returned by pg_transaction_status(). The connection is idle, in a transaction block.
`PGSQL_TRANSACTION_INERROR` (int)
  Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
`PGSQL_TRANSACTION_UNKNOWN` (int)
  Returned by pg_transaction_status(). The connection is bad.
`PGSQL_DIAG_SEVERITY` (int)
  Passed to pg_result_error_field(). The severity; the field contents are `ERROR`, `FATAL`, or `PANIC` (in an error message), or `WARNING`, `NOTICE`, `DEBUG`, `INFO`, or `LOG` (in a notice message), or a localized translation of one of these. Always present.
`PGSQL_DIAG_SQLSTATE` (int)
  Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
`PGSQL_DIAG_MESSAGE_PRIMARY` (int)
  Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
`PGSQL_DIAG_MESSAGE_DETAIL` (int)
  Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
`PGSQL_DIAG_MESSAGE_HINT` (int)
  Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
`PGSQL_DIAG_STATEMENT_POSITION` (int)
  Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
`PGSQL_DIAG_INTERNAL_POSITION` (int)
  Passed to pg_result_error_field(). This is defined the same as the `PG_DIAG_STATEMENT_POSITION` field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The `PG_DIAG_INTERNAL_QUERY` field will always appear when this field appears.
`PGSQL_DIAG_INTERNAL_QUERY` (int)
  Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
`PGSQL_DIAG_CONTEXT` (int)
  Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
`PGSQL_DIAG_SOURCE_FILE` (int)
  Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
`PGSQL_DIAG_SOURCE_LINE` (int)
  Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
`PGSQL_DIAG_SOURCE_FUNCTION` (int)
  Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
`PGSQL_DIAG_SCHEMA_NAME` (int)
  Available since PHP 7.3.0.
`PGSQL_DIAG_TABLE_NAME` (int)
  Available since PHP 7.3.0.
`PGSQL_DIAG_COLUMN_NAME` (int)
  Available since PHP 7.3.0.
`PGSQL_DIAG_DATATYPE_NAME` (int)
  Available since PHP 7.3.0.
`PGSQL_DIAG_CONSTRAINT_NAME` (int)
  Available since PHP 7.3.0.
`PGSQL_ERRORS_TERSE` (int)
  Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
`PGSQL_ERRORS_DEFAULT` (int)
  Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
`PGSQL_ERRORS_VERBOSE` (int)
  Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
`PGSQL_ERRORS_SQLSTATE` (int)
  Passed to pg_set_error_verbosity(). Includes only the error severity and the `SQLSTATE` error code. If no error code is available, the output is like `PGSQL_ERRORS_TERSE` mode. Before PostgreSQL 11.1, the output is always the same as in `PGSQL_ERRORS_TERSE` mode.
`PGSQL_NOTICE_LAST` (int)
  Used by pg_last_notice(). Available since PHP 7.1.0.
`PGSQL_NOTICE_ALL` (int)
  Used by pg_last_notice(). Available since PHP 7.1.0.
`PGSQL_NOTICE_CLEAR` (int)
  Used by pg_last_notice(). Available since PHP 7.1.0.
`PGSQL_STATUS_LONG` (int)
  Passed to pg_result_status(). Indicates that numerical result code is desired.
`PGSQL_STATUS_STRING` (int)
  Passed to pg_result_status(). Indicates that textual result command tag is desired.
`PGSQL_CONV_IGNORE_DEFAULT` (int)
  Passed to pg_convert(). Ignore default values in the table during conversion.
`PGSQL_CONV_FORCE_NULL` (int)
  Passed to pg_convert(). Use SQL `NULL` in place of an empty string.
`PGSQL_CONV_IGNORE_NOT_NULL` (int)
  Passed to pg_convert(). Ignore conversion of `null` into SQL `NOT NULL` columns.
`PGSQL_DML_NO_CONV` (int)
  Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). All parameters passed as is. Manual escape is required if parameters contain user supplied data. Use pg_escape_string() for it.
`PGSQL_DML_EXEC` (int)
  Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute query by these functions.
`PGSQL_DML_ASYNC` (int)
  Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute asynchronous query by these functions.
`PGSQL_DML_STRING` (int)
  Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Return executed query string.
`PGSQL_DML_ESCAPE` (int)
  Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Apply escape to all parameters instead of calling pg_convert() internally. This option omits meta data look up. Query could be as fast as pg_query() and pg_send_query().
`PGSQL_POLLING_FAILED` (int)
  Returned by pg_connect_poll() to indicate that the connection attempt failed.
`PGSQL_POLLING_READING` (int)
  Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be readable.
`PGSQL_POLLING_WRITING` (int)
  Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be writable.
`PGSQL_POLLING_OK` (int)
  Returned by pg_connect_poll() to indicate that the connection is ready to be used.
`PGSQL_POLLING_ACTIVE` (int)
  Returned by pg_connect_poll() to indicate that the connection is currently active.
`PGSQL_DIAG_SEVERITY_NONLOCALIZED` (int)
  The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message). This is identical to the PG_DIAG_SEVERITY field except that the contents are never localized. This is present only in versions 9.6 and later / PHP 7.3.0 and later.
`PGSQL_SHOW_CONTEXT_NEVER` (int)
  To be used with pg_set_error_context_visibility(), the context is never shown. Available as of PHP 8.3.0.
`PGSQL_SHOW_CONTEXT_ERRORS` (int)
  To be used with pg_set_error_context_visibility(), the context's fields are included in error messages only. This is the default behaviour. Available as of PHP 8.3.0.
`PGSQL_SHOW_CONTEXT_ALWAYS` (int)
  To be used with pg_set_error_context_visibility(), the context's fields are included in error, notice and warning messages. Available as of PHP 8.3.0.
`PGSQL_TRACE_SUPPRESS_TIMESTAMPS` (int)
  To be used with pg_trace(), the timestamp is not included in the trace's messages. Available as of PHP 8.4.20.
`PGSQL_TRACE_REGRESS_MODE` (int)
  To be used with pg_trace(), fields such as OIDs are included in the trace's messages. Available as of PHP 8.3.0.

# Examples

## Table of Contents

- Basic usage
- Basic usage

## Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

`<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($dbconn, $query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>`

## Basic usage

These examples contain user defined functions similar to legacy MySQL functions.

Example #1 PostgreSQL user defined functions example

`<?php
// This function should be needed, since PostgreSQL connection binds database.
function pg_list_dbs($db)
{
assert(is_resource($db));
$query = '
SELECT
d.datname as "Name",
u.usename as "Owner",
pg_encoding_to_char(d.encoding) as "Encoding"
FROM
pg_database d LEFT JOIN pg_user u ON d.datdba = u.usesysid
ORDER BY 1;
';
return pg_query($db, $query);
}
// List tables.
function pg_list_tables($db)
{
assert(is_resource($db));
$query = "
SELECT
c.relname as \"Name\",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as \"Type\",
u.usename as \"Owner\"
FROM
pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
WHERE
c.relkind IN ('r','v','S','')
AND c.relname !~ '^pg_'
ORDER BY 1;
";
return pg_query($db, $query);
}
// See also pg_meta_data(). It returns field definition as array.
function pg_list_fields($db, $table)
{
assert(is_resource($db));
$query = "
SELECT
a.attname,
format_type(a.atttypid, a.atttypmod),
a.attnotnull,
a.atthasdef,
a.attnum
FROM
pg_class c,
pg_attribute a
WHERE
c.relname = '".$table."'
AND a.attnum > 0 AND a.attrelid = c.oid
ORDER BY a.attnum;
";
return pg_query($db, $query);
}
?>`

# PostgreSQL Functions

## Notes

> Note:

> Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

> Note:

> Most PostgreSQL functions accept `connection` as the optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return `false`.

> Note:

> PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

> Note:

> PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named `information_schema` containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

# pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_affected_rows — Returns number of affected records (tuples)

### Description

pg_affected_rows(PgSql\Result `$result`): int

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by `INSERT`, `UPDATE`, and `DELETE` queries.

The server also returns the number of SELECTed rows.

> Note:

> This function used to be called pg_cmdtuples().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

The number of rows affected by the query. If no tuple is affected, it will return `0`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_affected_rows() example

`<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");
$cmdtuples = pg_affected_rows($result);
echo $cmdtuples . " tuples are affected.\n";
?>`

The above example will output:

    1 tuples are affected.

### See Also

- pg_query() - Execute a query
- pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
- pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
- pg_num_rows() - Returns the number of rows in a result

# pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_cancel_query — Cancel an asynchronous query

### Description

pg_cancel_query(PgSql\Connection `$connection`): bool

pg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_cancel_query() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
// Cancel the currently running query. Will be the second query if it is
// still running.
pg_cancel_query($dbconn);
?>`

The above example will output:

    First call to pg_get_result(): Resource id #3
    Resource id #3 has 3 records

### See Also

- pg_send_query() - Sends asynchronous query
- pg_connection_busy() - Get connection is busy or not

# pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_client_encoding — Gets the client encoding

### Description

pg_client_encoding(?PgSql\Connection `$connection` = `null`): string

PostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.

> Note:

> If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns `SQL_ASCII`. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.

> The function used to be called pg_clientencoding().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

The client encoding.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_client_encoding() example

`<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);
echo "Client encoding is: ", $encoding, "\n";
?>`

The above example will output:

    Client encoding is: ISO-8859-1

### See Also

- pg_set_client_encoding() - Set the client encoding

# pg_close

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_close — Closes a PostgreSQL connection

### Description

pg_close(?PgSql\Connection `$connection` = `null`): true

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given `connection` instance.

> Note:

> Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.

If there is open PgSql\Lob instance on the connection, do not close the connection before closing all PgSql\Lob instances.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_close() example

`<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>`

The above example will output:

    Connected successfully

### See Also

- pg_connect() - Open a PostgreSQL connection

# pg_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_connect — Open a PostgreSQL connection

### Description

pg_connect(string `$connection_string`, int `$flags` = 0): PgSql\Connection|false

pg_connect() opens a connection to a PostgreSQL database specified by the `connection_string`.

If a second call is made to pg_connect() with the same `connection_string` as an existing connection, the existing connection will be returned unless you pass `PGSQL_CONNECT_FORCE_NEW` as `flags`.

The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

### Parameters

`connection_string`

  The `connection_string` can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form `keyword = value`. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., `keyword = 'a value'`. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

  The currently recognized parameter keywords are: `host`, `hostaddr`, `port`, `dbname` (defaults to value of `user`), `user`, `password`, `connect_timeout`, `options`, `tty` (ignored), `sslmode`, `requiressl` (deprecated in favor of `sslmode`), and `service`. Which of these arguments exist depends on your PostgreSQL version.

  The `options` parameter can be used to set command line parameters to be invoked by the server.

`flags`

  If `PGSQL_CONNECT_FORCE_NEW` is passed, then a new connection is created, even if the `connection_string` is identical to an existing connection.

  If `PGSQL_CONNECT_ASYNC` is given, then the connection is established asynchronously. The state of the connection can then be checked via pg_connect_poll() or pg_connection_status().

### Return Values

Returns an PgSql\Connection instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Connection instance now; previously, a resource was returned.

### Examples

Example #1 Using pg_connect()

`<?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"
$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"
$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>`

### See Also

- pg_pconnect() - Open a persistent PostgreSQL connection
- pg_close() - Closes a PostgreSQL connection
- pg_host() - Returns the host name associated with the connection
- pg_port() - Return the port number associated with the connection
- pg_tty() - Return the TTY name associated with the connection
- pg_options() - Get the options associated with the connection
- pg_dbname() - Get the database name

# pg_connect_poll

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt

### Description

pg_connect_poll(PgSql\Connection `$connection`): int

pg_connect_poll() polls the status of a PostgreSQL connection created by calling pg_connect() with the `PGSQL_CONNECT_ASYNC` option.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

Returns `PGSQL_POLLING_FAILED`, `PGSQL_POLLING_READING`, `PGSQL_POLLING_WRITING`, `PGSQL_POLLING_OK`, or `PGSQL_POLLING_ACTIVE`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

# pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_busy — Get connection is busy or not

### Description

pg_connection_busy(PgSql\Connection `$connection`): bool

pg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

Returns `true` if the connection is busy, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_connection_busy() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$bs = pg_connection_busy($dbconn);
if ($bs) {
echo 'connection is busy';
} else {
echo 'connection is not busy';
}
?>`

### See Also

- pg_connection_status() - Get connection status
- pg_get_result() - Get asynchronous query result

# pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_reset — Reset connection (reconnect)

### Description

pg_connection_reset(PgSql\Connection `$connection`): bool

pg_connection_reset() resets the connection. It is useful for error recovery.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_connection_reset() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$dbconn2 = pg_connection_reset($dbconn);
if ($dbconn2) {
echo "reset successful\n";
} else {
echo "reset failed\n";
}
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection
- pg_pconnect() - Open a persistent PostgreSQL connection
- pg_connection_status() - Get connection status

# pg_connection_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_status — Get connection status

### Description

pg_connection_status(PgSql\Connection `$connection`): int

pg_connection_status() returns the status of the specified `connection`.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

`PGSQL_CONNECTION_OK` or `PGSQL_CONNECTION_BAD`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_connection_status() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_connection_status($dbconn);
if ($stat === PGSQL_CONNECTION_OK) {
echo 'Connection status ok';
} else {
echo 'Connection status bad';
}
?>`

### See Also

- pg_connection_busy() - Get connection is busy or not

# pg_consume_input

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_consume_input — Reads input on the connection

### Description

pg_consume_input(PgSql\Connection `$connection`): bool

pg_consume_input() consumes any input waiting to be read from the database server.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

`true` if no error occurred, or `false` if there was an error. Note that `true` does not necessarily indicate that input was waiting to be read.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

# pg_convert

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_convert — Convert associative array values into forms suitable for SQL statements

### Description

pg_convert(
PgSql\Connection `$connection`,
string `$table_name`,
array `$values`,
int `$flags` = 0
): array|false

pg_convert() checks and converts the values in `values` into suitable values for use in an SQL statement. Precondition for pg_convert() is the existence of a table `table_name` which has at least as many columns as `values` has elements. The fieldnames in `table_name` must match the indices in `values` and the corresponding datatypes must be compatible. Returns an array with the converted values on success, `false` otherwise.

> Note:

> Boolean values are accepted and converted to PostgreSQL booleans. String representations of boolean values are also supported. `null` is converted to PostgreSQL NULL.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table against which to convert types.

`values`

  Data to be converted.

`flags`

  Any number of `PGSQL_CONV_IGNORE_DEFAULT`, `PGSQL_CONV_FORCE_NULL` or `PGSQL_CONV_IGNORE_NOT_NULL`, combined.

### Return Values

An array of converted values, or `false` on failure.

### Errors/Exceptions

A ValueError or TypeError is thrown when the value or type of field does not match properly with a PostgreSQL's type.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a ValueError or TypeError error when the value or type of field does not match properly with a PostgreSQL's type; previously an `E_WARNING` was emitted.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_convert() example

`<?php
$dbconn = pg_connect('dbname=foo');
$tmp = array(
'author' => 'Joe Thackery',
'year' => 2005,
'title' => 'My Life, by Joe Thackery'
);
$vals = pg_convert($dbconn, 'authors', $tmp);
?>`

### See Also

- pg_meta_data() - Get meta data for table
- pg_insert() - Insert array into table
- pg_select() - Select records
- pg_update() - Update table
- pg_delete() - Deletes records

# pg_copy_from

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_copy_from — Insert records into a table from an array

### Description

pg_copy_from(
PgSql\Connection `$connection`,
string `$table_name`,
array|Traversable `$rows`,
string `$separator` = "\t",
string `$null_as` = "\\\\N"
): bool

pg_copy_from() inserts records into a table from `rows`. It issues a `COPY FROM` SQL command internally to insert records.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table into which to copy the `rows`.

`rows`

  An iterable data to be copied into `table_name`. Each value in `rows` becomes a row in `table_name`. Each value in `rows` should be a delimited string of the values to insert into each field. Values should be linefeed terminated.

`separator`

  The token that separates values for each field in each element of `rows`. Default is `\t`.

`null_as`

  How SQL `NULL` values are represented in the `rows`. Default is `\\N` (`"\\\\N"`).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | `rows` is now of type iterable. Previously, it was of type array.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_copy_from() example

`<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");
$rows = pg_copy_to($db, $table_name);
pg_query($db, "DELETE FROM $table_name");
pg_copy_from($db, $table_name, $rows);
?>`

### See Also

- pg_copy_to() - Copy a table to an array

# pg_copy_to

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_copy_to — Copy a table to an array

### Description

pg_copy_to(
PgSql\Connection `$connection`,
string `$table_name`,
string `$separator` = "\t",
string `$null_as` = "\\\\N"
): array|false

pg_copy_to() copies a table to an array. It issues `COPY TO` SQL command internally to retrieve records.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table from which to copy the data into `rows`.

`separator`

  The token that separates values for each field in each element of `rows`. Default is `\t`.

`null_as`

  How SQL `NULL` values are represented in the `rows`. Default is `\\N` (`"\\\\N"`).

### Return Values

An array with one element for each line of `COPY` data, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_copy_to() example

`<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");
$rows = pg_copy_to($db, $table_name);
pg_query($db, "DELETE FROM $table_name");
pg_copy_from($db, $table_name, $rows);
?>`

### See Also

- pg_copy_from() - Insert records into a table from an array

# pg_dbname

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_dbname — Get the database name

### Description

pg_dbname(?PgSql\Connection `$connection` = `null`): string

pg_dbname() returns the name of the database that the given PostgreSQL `connection` instance.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the name of the database the `connection` is to.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_dbname() example

`<?php
error_reporting(E_ALL);
pg_connect("host=localhost port=5432 dbname=mary");
echo pg_dbname(); // mary
?>`

# pg_delete

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_delete — Deletes records

### Description

pg_delete(
PgSql\Connection `$connection`,
string `$table_name`,
array `$conditions`,
int `$flags` = `PGSQL_DML_EXEC`
): string|bool

pg_delete() deletes records from a table specified by the keys and values in `conditions`.

If `flags` is specified, pg_convert() is applied to `conditions` with the specified flags.

By default pg_delete() passes raw values. Values must be escaped or the `PGSQL_DML_ESCAPE` flag must be specified in `flags`. `PGSQL_DML_ESCAPE` quotes and escapes parameters/identifiers. Therefore, table/column names become case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table from which to delete rows.

`conditions`

  An array whose keys are field names in the table `table_name`, and whose values are the values of those fields that are to be deleted.

`flags`

  Any number of `PGSQL_CONV_FORCE_NULL`, `PGSQL_DML_NO_CONV`, `PGSQL_DML_ESCAPE`, `PGSQL_DML_EXEC`, `PGSQL_DML_ASYNC` or `PGSQL_DML_STRING` combined. If `PGSQL_DML_STRING` is part of the `flags` then query string is returned. When `PGSQL_DML_NO_CONV` or `PGSQL_DML_ESCAPE` is set, it does not call pg_convert() internally.

### Return Values

Returns `true` on success or `false` on failure. Returns string if `PGSQL_DML_STRING` is passed via `flags`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_delete() example

`<?php
$db = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_delete($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($res) {
echo "POST data is deleted: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>`

### See Also

- pg_convert() - Convert associative array values into forms suitable for SQL statements

# pg_end_copy

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_end_copy — Sync with PostgreSQL backend

### Description

pg_end_copy(?PgSql\Connection `$connection` = `null`): bool

pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_end_copy() example

`<?php
$conn = pg_pconnect("dbname=foo");
pg_query($conn, "create table bar (a int4, b char(16), d float8)");
pg_query($conn, "copy bar from stdin");
pg_put_line($conn, "3\thello world\t4.5\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
?>`

### See Also

- pg_put_line() - Send a NULL-terminated string to PostgreSQL backend

# pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_escape_bytea — Escape a string for insertion into a bytea field

### Description

pg_escape_bytea(PgSql\Connection `$connection` = ?, string `$string`): string

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

> Note:

> When you `SELECT` a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

> This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. `INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);` PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`string`

  A string containing text or binary data to be inserted into a bytea column.

### Return Values

A string containing the escaped data.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_escape_bytea() example

`<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a binary file
$data = file_get_contents('image1.jpg');
// Escape the binary data
$escaped = pg_escape_bytea($data);
// Insert it into the database
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>`

### See Also

- pg_unescape_bytea() - Unescape binary for bytea type
- pg_escape_string() - Escape a string for query

# pg_escape_identifier

(PHP 5 >= 5.4.4, PHP 7, PHP 8)

pg_escape_identifier — Escape an identifier for insertion into a text field

### Description

pg_escape_identifier(PgSql\Connection `$connection` = ?, string `$string`): string|false

pg_escape_identifier() escapes an identifier (e.g. table, field names) for querying the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() must be used. For bytea type fields, pg_escape_bytea() must be used instead.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`string`

  A string containing text to be escaped.

### Return Values

A string containing the escaped data, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_escape_identifier() example

`<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Escape the table name data
$escaped = pg_escape_identifier($table_name);
// Select rows from $table_name
pg_query("SELECT * FROM {$escaped};");
?>`

### See Also

- pg_escape_literal() - Escape a literal for insertion into a text field
- pg_escape_bytea() - Escape a string for insertion into a bytea field
- pg_escape_string() - Escape a string for query

# pg_escape_literal

(PHP 5 >= 5.4.4, PHP 7, PHP 8)

pg_escape_literal — Escape a literal for insertion into a text field

### Description

pg_escape_literal(PgSql\Connection `$connection` = ?, string `$string`): string|false

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`string`

  A string containing text to be escaped.

### Return Values

A string containing the escaped data, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_escape_literal() example

`<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a text file (containing apostrophes and backslashes)
$data = file_get_contents('letter.txt');
// Escape the text data
$escaped = pg_escape_literal($data);
// Insert it into the database. Note that no quotes around {$escaped}
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>`

### See Also

- pg_escape_identifier() - Escape an identifier for insertion into a text field
- pg_escape_bytea() - Escape a string for insertion into a bytea field
- pg_escape_string() - Escape a string for query

# pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_escape_string — Escape a string for query

### Description

pg_escape_string(PgSql\Connection `$connection` = ?, string `$string`): string

pg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes. pg_escape_literal() is more preferred way to escape SQL parameters for PostgreSQL. addslashes() must not be used with PostgreSQL. If the type of the column is bytea, pg_escape_bytea() must be used instead. pg_escape_identifier() must be used to escape identifiers (e.g. table names, field names)

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`string`

  A string containing text to be escaped.

### Return Values

A string containing the escaped data.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_escape_string() example

`<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a text file (containing apostrophes and backslashes)
$data = file_get_contents('letter.txt');
// Escape the text data
$escaped = pg_escape_string($data);
// Insert it into the database
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>`

### See Also

- pg_escape_bytea() - Escape a string for insertion into a bytea field

# pg_execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result

### Description

pg_execute(PgSql\Connection `$connection` = ?, string `$statement_name`, array `$params`): PgSql\Result|false

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`statement_name`

  The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a `PREPARE` SQL command.

`params`

  An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

  Warning

  Elements are converted to strings by calling this function.

### Return Values

An PgSql\Result instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_execute()

`<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>`

### See Also

- pg_prepare() - Submits a request to the server to create a prepared statement with the given parameters, and waits for completion
- pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
- pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

# pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_fetch_all — Fetches all rows from a result as an array

### Description

pg_fetch_all(PgSql\Result `$result`, int `$mode` = `PGSQL_ASSOC`): array

pg_fetch_all() returns an array that contains all rows (records) in the PgSql\Result instance.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`mode`

  An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: `PGSQL_ASSOC`, `PGSQL_NUM` and `PGSQL_BOTH`. Using `PGSQL_NUM`, the function will return an array with numerical indices, using `PGSQL_ASSOC` it will return only associative indices while `PGSQL_BOTH` will return both numerical and associative indices.

### Return Values

An array with all rows in the result. Each row is an array of field values indexed by field name.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.
8.0.0 | pg_fetch_all() will now return an empty array instead of `false` for result sets with zero rows.
7.1.0 | The `mode` parameter was added.

### Examples

Example #1 PostgreSQL fetch all

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$arr = pg_fetch_all($result);
print_r($arr);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => Fred
            )

        [1] => Array
            (
                [id] => 2
                [name] => Bob
            )

    )

### See Also

- pg_fetch_row() - Get a row as an enumerated array
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_object() - Fetch a row as an object
- pg_fetch_result() - Returns values from a result instance

# pg_fetch_all_columns

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

### Description

pg_fetch_all_columns(PgSql\Result `$result`, int `$field` = 0): array

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the PgSql\Result instance.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Column number. Defaults to the first column if not specified.

### Return Values

An array with all values in the result column.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_all_columns() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);
var_dump($arr);
?>`

### See Also

- pg_fetch_all() - Fetches all rows from a result as an array

# pg_fetch_array

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_array — Fetch a row as an array

### Description

pg_fetch_array(PgSql\Result `$result`, ?int `$row` = `null`, int `$mode` = `PGSQL_BOTH`): array|false

pg_fetch_array() returns an array that corresponds to the fetched row (record).

pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indices by default.

> Note: This function sets NULL fields to the PHP `null` value.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or `null`, the next row is fetched.

`mode`

  An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: `PGSQL_ASSOC`, `PGSQL_NUM` and `PGSQL_BOTH`. Using `PGSQL_NUM`, the function will return an array with numerical indices, using `PGSQL_ASSOC` it will return only associative indices while `PGSQL_BOTH` will return both numerical and associative indices.

### Return Values

An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. Each value in the array is represented as a string. Database `NULL` values are returned as `null`.

`false` is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error. Fetching from the result of a query other than SELECT will also return `false`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_array() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";
// The row parameter is optional; NULL can be passed instead,
// to pass a result_type. Successive calls to pg_fetch_array
// will return the next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";
$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";
?>`

### See Also

- pg_fetch_row() - Get a row as an enumerated array
- pg_fetch_object() - Fetch a row as an object
- pg_fetch_result() - Returns values from a result instance

# pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_fetch_assoc — Fetch a row as an associative array

### Description

pg_fetch_assoc(PgSql\Result `$result`, ?int `$row` = `null`): array|false

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with `PGSQL_ASSOC` as the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

> Note: This function sets NULL fields to the PHP `null` value.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or `null`, the next row is fetched.

### Return Values

An array indexed associatively (by field name). Each value in the array is represented as a string. Database `NULL` values are returned as `null`.

`false` is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_assoc() example

`<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_assoc($result)) {
echo $row['id'];
echo $row['author'];
echo $row['email'];
}
?>`

### See Also

- pg_fetch_row() - Get a row as an enumerated array
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_object() - Fetch a row as an object
- pg_fetch_result() - Returns values from a result instance

# pg_fetch_object

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_object — Fetch a row as an object

### Description

pg_fetch_object(
PgSql\Result `$result`,
?int `$row` = `null`,
string `$class` = "stdClass",
array `$constructor_args` = []
): object|false

pg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.

> Note: This function sets NULL fields to the PHP `null` value.

Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or `null`, the next row is fetched.

`class`

  The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

`constructor_args`

  An optional array of parameters to pass to the constructor for `class` objects.

### Return Values

An object with one attribute for each field name in the result. Database `NULL` values are returned as `null`.

`false` is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error.

### Errors/Exceptions

A ValueError is thrown when the `constructor_args` is non-empty with the class not having constructor.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a ValueError exception when the `constructor_args` is non-empty with the class not having constructor; previously an Exception was thrown.
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_object() example

`<?php
$database = "store";
$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
echo "Failed connecting to postgres database $database\n";
exit;
}
$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");
while ($data = pg_fetch_object($qu)) {
echo $data->author . " (";
echo $data->year . "): ";
echo $data->title . "<br />";
}
pg_free_result($qu);
pg_close($db_conn);
?>`

### See Also

- pg_query() - Execute a query
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_assoc() - Fetch a row as an associative array
- pg_fetch_row() - Get a row as an enumerated array
- pg_fetch_result() - Returns values from a result instance

# pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_fetch_result — Returns values from a result instance

### Description

pg_fetch_result(PgSql\Result `$result`, string|false|null `$row`, mixed `$field`): string|false|null
pg_fetch_result(PgSql\Result `$result`, mixed `$field`): string|false|null

pg_fetch_result() returns the value of a particular row and field (column) in an PgSql\Result instance.

> Note:

> This function used to be called pg_result().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

`field`

  A string representing the name of the field (column) to fetch, otherwise an int representing the field number to fetch. Fields are numbered from 0 upwards.

### Return Values

Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database `NULL` values are returned as `null`.

`false` is returned if `row` exceeds the number of rows in the set, or on any other error.

### Changelog

Version | Description
--- | ---
8.3.0 | `row` is now nullable.
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_result() example

`<?php
$db = pg_connect("dbname=users user=me");
$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");
$val = pg_fetch_result($res, 1, 0);
echo "First field in the second row is: ", $val, "\n";
?>`

The above example will output:

    First field in the second row is: 2

### See Also

- pg_query() - Execute a query
- pg_fetch_array() - Fetch a row as an array

# pg_fetch_row

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_row — Get a row as an enumerated array

### Description

pg_fetch_row(PgSql\Result `$result`, ?int `$row` = `null`, int `$mode` = `PGSQL_NUM`): array|false

pg_fetch_row() fetches one row of data from the result associated with the specified `result` instance.

> Note: This function sets NULL fields to the PHP `null` value.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or `null`, the next row is fetched.

`mode`

  An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: `PGSQL_ASSOC`, `PGSQL_NUM` and `PGSQL_BOTH`. Using `PGSQL_NUM`, the function will return an array with numerical indices, using `PGSQL_ASSOC` it will return only associative indices while `PGSQL_BOTH` will return both numerical and associative indices.

### Return Values

An array, indexed from 0 upwards, with each value represented as a string. Database `NULL` values are returned as `null`.

`false` is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_fetch_row() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>`

### See Also

- pg_query() - Execute a query
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_object() - Fetch a row as an object
- pg_fetch_result() - Returns values from a result instance

# pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_is_null — Test if a field is SQL `NULL`

### Description

pg_field_is_null(PgSql\Result `$result`, string|false|null `$row`, mixed `$field`): int
pg_field_is_null(PgSql\Result `$result`, mixed `$field`): int

pg_field_is_null() tests if a field in an PgSql\Result instance is SQL `NULL` or not.

> Note:

> This function used to be called pg_fieldisnull().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched.

`field`

  Field number (starting from 0) as an int or the field name as a string.

### Return Values

Returns `1` if the field in the given row is SQL `NULL`, `0` if not. `false` is returned if the row is out of range, or upon any other error.

### Changelog

Version | Description
--- | ---
8.3.0 | `row` is now nullable.
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_field_is_null() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
if ($res) {
if (pg_field_is_null($res, 0, "year") == 1) {
echo "The value of the field year is null.\n";
}
if (pg_field_is_null($res, 0, "year") == 0) {
echo "The value of the field year is not null.\n";
}
}
?>`

# pg_field_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_name — Returns the name of a field

### Description

pg_field_name(PgSql\Result `$result`, int `$field`): string

pg_field_name() returns the name of the field occupying the given `field` in the given `result` instance. Field numbering starts from 0.

> Note:

> This function used to be called pg_fieldname().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Field number, starting from 0.

### Return Values

The field name.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>`

The above example will output:

    column 0
    fieldname: author
    printed length: 6 characters
    storage length: -1 bytes
    field type: varchar

    column 1
    fieldname: year
    printed length: 4 characters
    storage length: 2 bytes
    field type: int2

    column 2
    fieldname: title
    printed length: 24 characters
    storage length: -1 bytes
    field type: varchar

### See Also

- pg_field_num() - Returns the field number of the named field

# pg_field_num

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_num — Returns the field number of the named field

### Description

pg_field_num(PgSql\Result `$result`, string `$field`): int

pg_field_num() will return the number of the field number that corresponds to the `field` in the given `result` instance.

> Note:

> This function used to be called pg_fieldnum().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  The name of the field. The given name is treated like an identifier in an SQL command, that is, it is downcased unless double-quoted.

### Return Values

The field number (numbered from 0), or -1 on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");
echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?>`

The above example will output:

    Column 'title' is field number: 2

### See Also

- pg_field_name() - Returns the name of a field

# pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_prtlen — Returns the printed length

### Description

pg_field_prtlen(PgSql\Result `$result`, string|false|null `$row`, mixed `$field_name_or_number`): int
pg_field_prtlen(PgSql\Result `$result`, mixed `$field_name_or_number`): int

pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL `result`. Row numbering starts at 0. This function will return `false` on an error.

`field_name_or_number` can be passed either as an int or as a string. If it is passed as an int, PHP recognises it as the field number, otherwise as field name.

See the example given at the pg_field_name() page.

> Note:

> This function used to be called pg_fieldprtlen().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.

### Return Values

The field printed length.

### Changelog

Version | Description
--- | ---
8.3.0 | `row` is now nullable.
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>`

The above example will output:

    column 0
    fieldname: author
    printed length: 6 characters
    storage length: -1 bytes
    field type: varchar

    column 1
    fieldname: year
    printed length: 4 characters
    storage length: 2 bytes
    field type: int2

    column 2
    fieldname: title
    printed length: 24 characters
    storage length: -1 bytes
    field type: varchar

### See Also

- pg_field_size() - Returns the internal storage size of the named field

# pg_field_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_size — Returns the internal storage size of the named field

### Description

pg_field_size(PgSql\Result `$result`, int `$field`): int

pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL `result`.

> Note:

> This function used to be called pg_fieldsize().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Field number, starting from 0.

### Return Values

The internal field storage size (in bytes). -1 indicates a variable length field.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>`

The above example will output:

    column 0
    fieldname: author
    printed length: 6 characters
    storage length: -1 bytes
    field type: varchar

    column 1
    fieldname: year
    printed length: 4 characters
    storage length: 2 bytes
    field type: int2

    column 2
    fieldname: title
    printed length: 24 characters
    storage length: -1 bytes
    field type: varchar

### See Also

- pg_field_prtlen() - Returns the printed length
- pg_field_type() - Returns the type name for the corresponding field number

# pg_field_table

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

pg_field_table — Returns the name or oid of the tables field

### Description

pg_field_table(PgSql\Result `$result`, int `$field`, bool `$oid_only` = `false`): string|int|false

pg_field_table() returns the name of the table that field belongs to, or the table's oid if `oid_only` is `true`.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Field number, starting from 0.

`oid_only`

  By default the tables name that field belongs to is returned but if `oid_only` is set to `true`, then the oid will instead be returned.

### Return Values

On success either the fields table name or oid, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting table information about a field

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "SELECT bar FROM foo");
echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);
$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?>`

The above example will output something similar to:

    foo
    14379580

    bool(false)

### Notes

> Note:

> Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

### See Also

- pg_field_name() - Returns the name of a field
- pg_field_type() - Returns the type name for the corresponding field number

# pg_field_type

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_type — Returns the type name for the corresponding field number

### Description

pg_field_type(PgSql\Result `$result`, int `$field`): string

pg_field_type() returns a string containing the base type name of the given `field` in the given `result` instance.

> Note:

> If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.

> Note:

> This function used to be called pg_fieldtype().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Field number, starting from 0.

### Return Values

A string containing the base name of the field's type.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Assume 'title' is a varchar type
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");
echo "Title field type: ", pg_field_type($res, 0);
?>`

The above example will output:

    Title field type: varchar

### See Also

- pg_field_prtlen() - Returns the printed length
- pg_field_name() - Returns the name of a field
- pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

# pg_field_type_oid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

### Description

pg_field_type_oid(PgSql\Result `$result`, int `$field`): string|int

pg_field_type_oid() returns an integer containing the OID of the base type of the given `field` in the given `result` instance.

You can get more information about the field type by querying PostgreSQL's `pg_type` system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

> Note:

> If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field`

  Field number, starting from 0.

### Return Values

The OID of the field's base type.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 Getting information about fields

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Assume 'title' is a varchar type
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");
echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>`

The above example will output:

    Title field type OID: 1043

### See Also

- pg_field_type() - Returns the type name for the corresponding field number
- pg_field_prtlen() - Returns the printed length
- pg_field_name() - Returns the name of a field

# pg_flush

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_flush — Flush outbound query data on the connection

### Description

pg_flush(PgSql\Connection `$connection`): int|bool

pg_flush() flushes any outbound query data waiting to be sent on the connection.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

Returns `true` if the flush was successful or no data was waiting to be flushed, `0` if part of the pending data was flushed but more remains or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

# pg_free_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_free_result — Free result memory

### Description

pg_free_result(PgSql\Result `$result`): bool

pg_free_result() frees the memory and data associated with the specified PgSql\Result instance.

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

> Note:

> This function used to be called pg_freeresult().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_free_result() example

`<?php
$db = pg_connect("dbname=users user=me");
$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");
$val = pg_fetch_result($res, 1, 0);
echo "First field in the second row is: ", $val, "\n";
pg_free_result($res);
?>`

The above example will output:

    First field in the second row is: 2

### See Also

- pg_query() - Execute a query
- pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
- pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
- pg_result_memory_size() - Returns the amount of memory allocated for a query result

# pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_notify — Gets SQL NOTIFY message

### Description

pg_get_notify(PgSql\Connection `$connection`, int `$mode` = `PGSQL_ASSOC`): array|false

pg_get_notify() gets notifications generated by a `NOTIFY` SQL command. To receive notifications, the `LISTEN` SQL command must be issued.

### Parameters

`connection`

  An PgSql\Connection instance.

`mode`

  An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: `PGSQL_ASSOC`, `PGSQL_NUM` and `PGSQL_BOTH`. Using `PGSQL_NUM`, the function will return an array with numerical indices, using `PGSQL_ASSOC` it will return only associative indices while `PGSQL_BOTH` will return both numerical and associative indices.

### Return Values

An array containing the `NOTIFY` message name and backend PID. If supported by the server, the array also contains the server version and the payload. Otherwise if no `NOTIFY` is waiting, then `false` is returned.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 PostgreSQL NOTIFY message

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
echo "No messages\n";
} else {
print_r($notify);
}
?>`

### See Also

- pg_get_pid() - Gets the backend's process ID

# pg_get_pid

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_pid — Gets the backend's process ID

### Description

pg_get_pid(PgSql\Connection `$connection`): int

pg_get_pid() gets the backend's (database server process) PID. The PID is useful to determine whether or not a `NOTIFY` message received via pg_get_notify() is sent from another process or not.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

The backend database process ID.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 PostgreSQL backend PID

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>`

### See Also

- pg_get_notify() - Gets SQL NOTIFY message

# pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_get_result — Get asynchronous query result

### Description

pg_get_result(PgSql\Connection `$connection`): PgSql\Result|false

pg_get_result() gets an PgSql\Result instance from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().

pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

An PgSql\Result instance, or `false` if no more results are available.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_get_result() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>`

The above example will output:

    First call to pg_get_result(): Resource id #3
    Resource id #3 has 3 records

    Second call to pg_get_result(): Resource id #4
    Resource id #4 has 1 records

### See Also

- pg_send_query() - Sends asynchronous query

# pg_host

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_host — Returns the host name associated with the connection

### Description

pg_host(?PgSql\Connection `$connection` = `null`): string

pg_host() returns the host name of the given PostgreSQL `connection` instance is connected to.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the name of the host the `connection` is to, or an empty string on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_host() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection
- pg_pconnect() - Open a persistent PostgreSQL connection

# pg_insert

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_insert — Insert array into table

### Description

pg_insert(
PgSql\Connection `$connection`,
string `$table_name`,
array `$values`,
int `$flags` = `PGSQL_DML_EXEC`
): PgSql\Result|string|bool

pg_insert() inserts the values of `values` into the table specified by `table_name`.

If `flags` is specified, pg_convert() is applied to `values` with the specified flags.

By default pg_insert() passes raw values. Values must be escaped or the `PGSQL_DML_ESCAPE` flag must be specified in `flags`. `PGSQL_DML_ESCAPE` quotes and escapes parameters/identifiers. Therefore, table/column names become case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table into which to insert rows. The table `table_name` must at least have as many columns as `values` has elements.

`values`

  An array whose keys are field names in the table `table_name`, and whose values are the values of those fields that are to be inserted.

`flags`

  Any number of `PGSQL_CONV_OPTS`, `PGSQL_DML_NO_CONV`, `PGSQL_DML_ESCAPE`, `PGSQL_DML_EXEC`, `PGSQL_DML_ASYNC` or `PGSQL_DML_STRING` combined. If `PGSQL_DML_STRING` is part of the `flags` then query string is returned. When `PGSQL_DML_NO_CONV` or `PGSQL_DML_ESCAPE` is set, it does not call pg_convert() internally.

### Return Values

Returns `true` on success or `false` on failure.. Or returns a string on success if `PGSQL_DML_STRING` is passed via `flags`.

### Errors/Exceptions

A ValueError is thrown when the specified table is invalid.

A ValueError or TypeError is thrown when the value or type of field does not match properly with a PostgreSQL's type.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a ValueError error when the specified table is invalid; previously an `E_WARNING` was emitted.
8.3.0 | Now throws a ValueError or TypeError error when the value or type of field does not match properly with a PostgreSQL's type; previously an `E_WARNING` was emitted.
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_insert() example

`<?php
$dbconn = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_insert($dbconn, 'post_log', $_POST, PGSQL_DML_ESCAPE);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>`

### See Also

- pg_convert() - Convert associative array values into forms suitable for SQL statements

# pg_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_last_error — Get the last error message string of a connection

### Description

pg_last_error(?PgSql\Connection `$connection` = `null`): string

pg_last_error() returns the last error message for a given `connection`.

Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.

Use pg_result_error(), pg_result_error_field(), pg_result_status() and pg_connection_status() for better error handling.

> Note:

> This function used to be called pg_errormessage().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the last error message on the given `connection`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_last_error() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Query that fails
$res = pg_query($dbconn, "select * from doesnotexist");
echo pg_last_error($dbconn);
?>`

### See Also

- pg_result_error() - Get error message associated with result
- pg_result_error_field() - Returns an individual field of an error report

# pg_last_notice

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

pg_last_notice — Returns the last notice message from PostgreSQL server

### Description

pg_last_notice(PgSql\Connection `$connection`, int `$mode` = `PGSQL_NOTICE_LAST`): array|string|bool

pg_last_notice() returns the last notice message from the PostgreSQL server on the specified `connection`. The PostgreSQL server sends notice messages in several cases, for instance when creating a `SERIAL` column in a table.

With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.

Notice message tracking can be set to optional by setting 1 for `pgsql.ignore_notice` in php.ini.

Notice message logging can be set to optional by setting 0 for `pgsql.log_notice` in php.ini. Unless `pgsql.ignore_notice` is set to 0, notice message cannot be logged.

### Parameters

`connection`

  An PgSql\Connection instance.

`mode`

  One of `PGSQL_NOTICE_LAST` (to return last notice), `PGSQL_NOTICE_ALL` (to return all notices), or `PGSQL_NOTICE_CLEAR` (to clear notices).

### Return Values

A string containing the last notice on the given `connection` with `PGSQL_NOTICE_LAST`, an array with `PGSQL_NOTICE_ALL`, a bool with `PGSQL_NOTICE_CLEAR`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
7.1.0 | The `mode` parameter was added.

### Examples

Example #1 pg_last_notice() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
$res = pg_query("CREATE TABLE test (id SERIAL)");
$notice = pg_last_notice($pgsql_conn);
echo $notice;
?>`

The above example will output:

    CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

### See Also

- pg_query() - Execute a query
- pg_last_error() - Get the last error message string of a connection

# pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_last_oid — Returns the last row's OID

### Description

pg_last_oid(PgSql\Result `$result`): string|int|false

pg_last_oid() is used to retrieve the OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.

To get the value of a `SERIAL` field in an inserted row, it is necessary to use the PostgreSQL `CURRVAL` function, naming the sequence whose last value is required. If the name of the sequence is unknown, the `pg_get_serial_sequence` PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function `LASTVAL` that returns the value of the most recently used sequence in the session. This avoids the need for naming the sequence, table or column altogether.

> Note:

> This function used to be called pg_getlastoid().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

An int or string containing the OID assigned to the most recently inserted row in the specified `connection`, or `false` on error or no available OID.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_last_oid() example

`<?php
// Connect to the database
pg_connect("dbname=mark host=localhost");
// Create a sample table
pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");
// Insert some data into it
$res = pg_query("INSERT INTO test VALUES (1)");
$oid = pg_last_oid($res);
?>`

### See Also

- pg_query() - Execute a query
- pg_result_status() - Get status of query result

# pg_lo_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_close — Close a large object

### Description

pg_lo_close(PgSql\Lob `$lob`): bool

pg_lo_close() closes a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loclose().

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_close() example

`<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>`

### See Also

- pg_lo_open() - Open a large object
- pg_lo_create() - Create a large object
- pg_lo_import() - Import a large object from file

# pg_lo_create

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_create — Create a large object

### Description

pg_lo_create(PgSql\Connection `$connection` = ?, mixed `$object_id` = ?): int
pg_lo_create(mixed `$object_id`): int

pg_lo_create() creates a large object and returns the OID of the large object. PostgreSQL access modes `INV_READ` and `INV_WRITE` are not supported, the object is created always with both read and write access.

To use the large object interface, it is necessary to enclose it within a transaction block.

Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().

> Note:

> This function used to be called pg_locreate().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`object_id`

  If an `object_id` is given the function will try to create a large object with this id, else a free object id is assigned by the server.

### Return Values

A large object OID, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_create() example

`<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>`

# pg_lo_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_export — Export a large object to file

### Description

pg_lo_export(PgSql\Connection `$connection` = ?, int `$oid`, string `$filename`): bool

pg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loexport().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`oid`

  The OID of the large object in the database.

`filename`

  The full path and file name of the file in which to write the large object on the client filesystem.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_export() example

`<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
$handle = pg_lo_open($database, $oid, "w");
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_lo_export($database, $oid, '/tmp/lob.dat');
pg_query($database, "commit");
?>`

### See Also

- pg_lo_import() - Import a large object from file

# pg_lo_import

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_import — Import a large object from file

### Description

pg_lo_import(PgSql\Connection `$connection` = ?, string `$filename`, int|string `$oid` = ?): int|string|false

pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loimport().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`filename`

  The full path and file name of the file on the client filesystem from which to read the large object data.

`oid`

  If an `oid` is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter relies on functionality that first appeared in PostgreSQL 8.1.

### Return Values

The OID of the newly created large object, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_import() example

`<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_import($database, '/tmp/lob.dat');
pg_query($database, "commit");
?>`

### See Also

- pg_lo_export() - Export a large object to file
- pg_lo_open() - Open a large object

# pg_lo_open

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_open — Open a large object

### Description

pg_lo_open(PgSql\Connection `$connection`, int `$oid`, string `$mode`): PgSql\Lob|false

pg_lo_open() opens a large object in the database and returns an PgSql\Lob instance so that it can be manipulated.

Warning

Do not close the database connection before closing the PgSql\Lob instance.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loopen().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`oid`

  The OID of the large object in the database.

`mode`

  Can be either "r" for read-only, "w" for write only or "rw" for read and write.

### Return Values

An PgSql\Lob instance, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Lob instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_open() example

`<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>`

### See Also

- pg_lo_close() - Close a large object
- pg_lo_create() - Create a large object

# pg_lo_read

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_read — Read a large object

### Description

pg_lo_read(PgSql\Lob `$lob`, int `$length` = 8192): string|false

pg_lo_read() reads at most `length` bytes from a large object and returns it as a string.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loread().

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

`length`

  An optional maximum number of bytes to return.

### Return Values

A string containing `length` bytes from the large object, or `false` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_read() example

`<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
$data = pg_lo_read($handle, 50000);
pg_query($database, "commit");
echo $data;
?>`

### See Also

- pg_lo_read_all() - Reads an entire large object and send straight to browser

# pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_read_all — Reads an entire large object and send straight to browser

### Description

pg_lo_read_all(PgSql\Lob `$lob`): int

pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_loreadall().

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

### Return Values

Number of bytes read.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_read_all() example

`<?php
header('Content-type: image/jpeg');
$image_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $image_oid, "r");
pg_lo_read_all($handle);
pg_query($database, "commit");
?>`

### See Also

- pg_lo_read() - Read a large object

# pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_seek — Seeks position within a large object

### Description

pg_lo_seek(PgSql\Lob `$lob`, int `$offset`, int `$whence` = `SEEK_CUR`): bool

pg_lo_seek() seeks a position within an PgSql\Lob instance.

To use the large object interface, it is necessary to enclose it within a transaction block.

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

`offset`

  The number of bytes to seek.

`whence`

  One of the constants `PGSQL_SEEK_SET` (seek from object start), `PGSQL_SEEK_CUR` (seek from current position) or `PGSQL_SEEK_END` (seek from object end) .

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_seek() example

`<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Skip first 50000 bytes
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// Read the next 10000 bytes
$data = pg_lo_read($handle, 10000);
pg_query($database, "commit");
echo $data;
?>`

### See Also

- pg_lo_tell() - Returns current seek position a of large object

# pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_tell — Returns current seek position a of large object

### Description

pg_lo_tell(PgSql\Lob `$lob`): int

pg_lo_tell() returns the current position (offset from the beginning) of a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

### Return Values

The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_tell() example

`<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Skip first 50000 bytes
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// See how far we've skipped
$offset = pg_lo_tell($handle);
echo "Seek position is: $offset";
pg_query($database, "commit");
?>`

The above example will output:

    Seek position is: 50000

### See Also

- pg_lo_seek() - Seeks position within a large object

# pg_lo_truncate

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_lo_truncate — Truncates a large object

### Description

pg_lo_truncate(PgSql\Lob `$lob`, int `$size`): bool

pg_lo_truncate() truncates an PgSql\Lob instance.

To use the large object interface, it is necessary to enclose it within a transaction block.

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

`size`

  The number of bytes to truncate.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_truncate() example

`<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Truncate to 0
pg_lo_truncate($handle, 0);
pg_query($database, "commit");
echo $data;
?>`

### See Also

- pg_lo_tell() - Returns current seek position a of large object

# pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_unlink — Delete a large object

### Description

pg_lo_unlink(PgSql\Connection `$connection`, int `$oid`): bool

pg_lo_unlink() deletes a large object with the `oid`. Returns `true` on success or `false` on failure.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_lounlink().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`oid`

  The OID of the large object in the database.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_lo_unlink() example

`<?php
// OID of the large object to delete
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
pg_lo_unlink($database, $doc_oid);
pg_query($database, "commit");
?>`

### See Also

- pg_lo_create() - Create a large object
- pg_lo_import() - Import a large object from file

# pg_lo_write

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_write — Write to a large object

### Description

pg_lo_write(PgSql\Lob `$lob`, string `$data`, ?int `$length` = `null`): int|false

pg_lo_write() writes data into a large object at the current seek position.

To use the large object interface, it is necessary to enclose it within a transaction block.

> Note:

> This function used to be called pg_lowrite().

### Parameters

`lob`

  An PgSql\Lob instance, returned by pg_lo_open().

`data`

  The data to be written to the large object. If `length` is an int and is less than the length of `data`, only `length` bytes will be written.

`length`

  An optional maximum number of bytes to write. Must be greater than zero and no greater than the length of `data`. Defaults to the length of `data`.

### Return Values

The number of bytes written to the large object, or `false` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `lob` parameter expects an PgSql\Lob instance now; previously, a resource was expected.
8.0.0 | `length` is now nullable.

### Examples

Example #1 pg_lo_write() example

`<?php
$doc_oid = 189762345;
$data = "This will overwrite the start of the large object.";
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "w");
$data = pg_lo_write($handle, $data);
pg_query($database, "commit");
?>`

### See Also

- pg_lo_create() - Create a large object
- pg_lo_open() - Open a large object

# pg_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_meta_data — Get meta data for table

### Description

pg_meta_data(PgSql\Connection `$connection`, string `$table_name`, bool `$extended` = `false`): array|false

pg_meta_data() returns table definition for `table_name` as an array.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  The name of the table.

`extended`

  Flag for returning extended meta data. Default to `false`.

### Return Values

An array of the table definition, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Getting table metadata

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$meta = pg_meta_data($dbconn, 'authors');
if (is_array($meta)) {
echo '<pre>';
var_dump($meta);
echo '</pre>';
}
?>`

The above example will output:

    array(3) {
    ["author"]=>
    array(5) {
      ["num"]=>
      int(1)
      ["type"]=>
      string(7) "varchar"
      ["len"]=>
      int(-1)
      ["not null"]=>
      bool(false)
      ["has default"]=>
      bool(false)
    }
    ["year"]=>
    array(5) {
      ["num"]=>
      int(2)
      ["type"]=>
      string(4) "int2"
      ["len"]=>
      int(2)
      ["not null"]=>
      bool(false)
      ["has default"]=>
      bool(false)
    }
    ["title"]=>
    array(5) {
      ["num"]=>
      int(3)
      ["type"]=>
      string(7) "varchar"
      ["len"]=>
      int(-1)
      ["not null"]=>
      bool(false)
      ["has default"]=>
      bool(false)
    }
    }

### See Also

- pg_convert() - Convert associative array values into forms suitable for SQL statements

# pg_num_fields

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_num_fields — Returns the number of fields in a result

### Description

pg_num_fields(PgSql\Result `$result`): int

pg_num_fields() returns the number of fields (columns) in the PgSql\Result instance.

> Note:

> This function used to be called pg_numfields().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

The number of fields (columns) in the result. On error, -1 is returned.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_num_fields() example

`<?php
$result = pg_query($conn, "SELECT 1, 2");
$num = pg_num_fields($result);
echo $num . " field(s) returned.\n";
?>`

The above example will output:

    2 field(s) returned.

### See Also

- pg_num_rows() - Returns the number of rows in a result
- pg_affected_rows() - Returns number of affected records (tuples)

# pg_num_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_num_rows — Returns the number of rows in a result

### Description

pg_num_rows(PgSql\Result `$result`): int

pg_num_rows() will return the number of rows in an PgSql\Result instance.

> Note:

> This function used to be called pg_numrows().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

The number of rows in the result. On error, `-1` is returned.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_num_rows() example

`<?php
$result = pg_query($conn, "SELECT 1");
$rows = pg_num_rows($result);
echo $rows . " row(s) returned.\n";
?>`

The above example will output:

    1 row(s) returned.

### See Also

- pg_num_fields() - Returns the number of fields in a result
- pg_affected_rows() - Returns number of affected records (tuples)

# pg_options

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_options — Get the options associated with the connection

### Description

pg_options(?PgSql\Connection `$connection` = `null`): string

pg_options() will return a string containing the options specified on the given PostgreSQL `connection` instance.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the `connection` options.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_options() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
echo pg_options($pgsql_conn);
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection

# pg_parameter_status

(PHP 5, PHP 7, PHP 8)

pg_parameter_status — Looks up a current parameter setting of the server

### Description

pg_parameter_status(PgSql\Connection `$connection` = ?, string `$name`): string|false

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or `false` if the parameter is not known.

Parameters reported by the server include `server_version`, `server_encoding`, `client_encoding`, `is_superuser`, `session_authorization`, `DateStyle`, `TimeZone`, and `integer_datetimes`. Note that `server_version`, `server_encoding` and `integer_datetimes` cannot change after PostgreSQL startup.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`name`

  Possible `name` values include `server_version`, `server_encoding`, `client_encoding`, `is_superuser`, `session_authorization`, `DateStyle`, `TimeZone`, and `integer_datetimes`. Note that this value is case-sensitive.

### Return Values

A string containing the value of the parameter, `false` on failure or invalid `name`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_parameter_status() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>`

The above example will output:

    Server encoding: SQL_ASCII

# pg_pconnect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_pconnect — Open a persistent PostgreSQL connection

### Description

pg_pconnect(string `$connection_string`, int `$flags` = 0): PgSql\Connection|false

pg_pconnect() opens a connection to a PostgreSQL database. It returns a PgSql\Connection instance that is needed by other PostgreSQL functions.

If a second call is made to pg_pconnect() with the same `connection_string` as an existing connection, the existing connection will be returned unless you pass `PGSQL_CONNECT_FORCE_NEW` as `flags`.

To enable persistent connections, the pgsql.allow_persistent php.ini directive must be set to `"On"` (which is the default). The maximum number of persistent connections can be defined with the pgsql.max_persistent php.ini directive (defaults to `-1` for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.

pg_close() will not close persistent links generated by pg_pconnect().

### Parameters

`connection_string`

  The `connection_string` can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form `keyword = value`. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., `keyword = 'a value'`. Single quotes and backslashes within the value must be escaped with a backslash, i.e., `\'` and `\\`.

  The currently recognized parameter keywords are: `host`, `hostaddr`, `port`, `dbname`, `user`, `password`, `connect_timeout`, `options`, `tty` (ignored), `sslmode`, `requiressl` (deprecated in favor of `sslmode`), and `service`. Which of these arguments exist depends on the PostgreSQL version.

`flags`

  If `PGSQL_CONNECT_FORCE_NEW` is passed, then a new connection is created, even if the `connection_string` is identical to an existing connection.

### Return Values

Returns a PgSql\Connection instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns a PgSql\Connection instance now; previously, a resource was returned.

### Examples

Example #1 Using pg_pconnect()

`<?php
// Connect to a database named "mary"
$dbconn = pg_pconnect("dbname=mary");
// Connect to a database named "mary" on "localhost" at port "5432"
$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// Connect to a database named "mary" on the host "sheep" with a username and password
$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
// Connect to a database named "test" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection
- Persistent Database Connections

# pg_ping

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_ping — Ping database connection

### Description

pg_ping(?PgSql\Connection `$connection` = `null`): bool

pg_ping() pings a database connection and tries to reconnect it if it is broken.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_ping() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
if (!pg_ping($conn))
die("Connection is broken\n");
?>`

### See Also

- pg_connection_status() - Get connection status
- pg_connection_reset() - Reset connection (reconnect)

# pg_port

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_port — Return the port number associated with the connection

### Description

pg_port(?PgSql\Connection `$connection` = `null`): string

pg_port() returns the port number that the given PostgreSQL `connection` instance is connected to.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the port number of the database server the `connection` is to, or empty string on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_port() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>`

# pg_prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_prepare — Submits a request to the server to create a prepared statement with the given parameters, and waits for completion

### Description

pg_prepare(PgSql\Connection `$connection` = ?, string `$statement_name`, string `$query`): PgSql\Result|false

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.

The function creates a prepared statement named `statement_name` from the `query` string, which must contain a single SQL command. `statement_name` may be `""` to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the `query` as `$1`, `$2`, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL `PREPARE` statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL `DEALLOCATE` statement can be used for that purpose.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`statement_name`

  The name to give the prepared statement. Must be unique per-connection. If `""` is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

`query`

  The parameterized SQL statement. Must contain only a single statement (multiple statements separated by semi-colons are not allowed). If any parameters are used, they are referred to as `$1`, `$2`, etc.

### Return Values

An PgSql\Result instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_prepare()

`<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>`

### See Also

- pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
- pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

# pg_put_line

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_put_line — Send a NULL-terminated string to PostgreSQL backend

### Description

pg_put_line(PgSql\Connection `$connection` = ?, string `$query`): bool

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's `COPY FROM` command.

`COPY` is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction.

An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.

> Note:

> The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().

Warning

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`query`

  A line of text to be sent directly to the PostgreSQL backend. A `NULL` terminator is added automatically.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_put_line() example

`<?php
$conn = pg_pconnect("dbname=foo");
pg_query($conn, "create table bar (a int4, b char(16), d float8)");
pg_query($conn, "copy bar from stdin");
pg_put_line($conn, "3\thello world\t4.5\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
?>`

### See Also

- pg_end_copy() - Sync with PostgreSQL backend

# pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_query — Execute a query

### Description

pg_query(PgSql\Connection `$connection` = ?, string `$query`): PgSql\Result|false

pg_query() executes the `query` on the specified database `connection`. pg_query_params() should be preferred in most cases.

If an error occurs, and `false` is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

> Note: Although `connection` can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.

> Note:

> This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`query`

  The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

  Warning

  String interpolation of user-supplied data is extremely dangerous and is likely to lead to SQL injection vulnerabilities. In most cases pg_query_params() should be preferred, passing user-supplied values as parameters rather than substituting them into the query string.

  Any user-supplied data substituted directly into a query string should be properly escaped.

### Return Values

An PgSql\Result instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_query() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>`

Example #2 Using pg_query() with multiple statements

`<?php
$conn = pg_pconnect("dbname=publisher");
// these statements will be executed as one transaction
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";
pg_query($conn, $query);
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection
- pg_pconnect() - Open a persistent PostgreSQL connection
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_object() - Fetch a row as an object
- pg_num_rows() - Returns the number of rows in a result
- pg_affected_rows() - Returns number of affected records (tuples)

# pg_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

### Description

pg_query_params(PgSql\Connection `$connection` = ?, string `$query`, array `$params`): PgSql\Result|false

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper.

If parameters are used, they are referred to in the `query` string as $1, $2, etc. The same parameter may appear more than once in the `query`; the same value will be used in that case. `params` specifies the actual values of the parameters. A `null` value in this array means the corresponding parameter is SQL `NULL`.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the `query` string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`query`

  The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

  User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

`params`

  An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

  Values intended for `bytea` fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

### Return Values

An PgSql\Result instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PgSql\Result instance now; previously, a resource was returned.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_query_params()

`<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Find all shops named Joe's Widgets. Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));
// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");
?>`

### See Also

- pg_query() - Execute a query

# pg_result_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_result_error — Get error message associated with result

### Description

pg_result_error(PgSql\Result `$result`): string|false

pg_result_error() returns any error message associated with the `result` instance. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns `false` if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

Returns a string. Returns empty string if there is no error. If there is an error associated with the `result` parameter, returns `false`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_result_error() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>`

### See Also

- pg_result_error_field() - Returns an individual field of an error report
- pg_query() - Execute a query
- pg_send_query() - Sends asynchronous query
- pg_get_result() - Get asynchronous query result
- pg_last_error() - Get the last error message string of a connection
- pg_last_notice() - Returns the last notice message from PostgreSQL server

# pg_result_error_field

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_result_error_field — Returns an individual field of an error report

### Description

pg_result_error_field(PgSql\Result `$result`, int `$field_code`): string|false|null

pg_result_error_field() returns one of the detailed error message fields associated with `result` instance. The error field is specified by the `field_code`.

Because pg_query() and pg_query_params() return `false` if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`field_code`

  Possible `field_code` values are: `PGSQL_DIAG_SEVERITY`, `PGSQL_DIAG_SQLSTATE`, `PGSQL_DIAG_MESSAGE_PRIMARY`, `PGSQL_DIAG_MESSAGE_DETAIL`, `PGSQL_DIAG_MESSAGE_HINT`, `PGSQL_DIAG_STATEMENT_POSITION`, `PGSQL_DIAG_INTERNAL_POSITION`, `PGSQL_DIAG_INTERNAL_QUERY`, `PGSQL_DIAG_CONTEXT`, `PGSQL_DIAG_SOURCE_FILE`, `PGSQL_DIAG_SOURCE_LINE` or `PGSQL_DIAG_SOURCE_FUNCTION`.

### Return Values

A string containing the contents of the error field, `null` if the field does not exist or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_result_error_field() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>`

### See Also

- pg_result_error() - Get error message associated with result

# pg_result_memory_size

(PHP 8 >= 8.4.0)

pg_result_memory_size — Returns the amount of memory allocated for a query result

### Description

pg_result_memory_size(PgSql\Result `$result`): int

Returns the amount of memory, in bytes, allocated to the specified query result PgSql\Result instance. This value is the same amount that would be freed by pg_free_result().

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

### Return Values

Returns the memory amount in bytes.

### Examples

Example #1 pg_result_memory_size() example

`<?php
$db = pg_connect("dbname=users user=me");
$res = pg_query($db, 'SELECT 1');
$size = pg_result_memory_size($res);
var_dump($size);
?>`

The above example will output something similar to:

    int(3288)

### See Also

- pg_free_result() - Free result memory

# pg_result_seek

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_result_seek — Set internal row offset in result instance

### Description

pg_result_seek(PgSql\Result `$result`, int `$row`): bool

pg_result_seek() sets the internal row offset in the `result` instance.

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`row`

  Row to move the internal offset to in the PgSql\Result instance. Rows are numbered starting from zero.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_result_seek() example

`<?php
// Connect to the database
$conn = pg_pconnect("dbname=publisher");
// Execute a query
$result = pg_query($conn, "SELECT author, email FROM authors");
// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result, 2);
// Fetch the 3rd row
$row = pg_fetch_row($result);
?>`

### See Also

- pg_fetch_row() - Get a row as an enumerated array
- pg_fetch_assoc() - Fetch a row as an associative array
- pg_fetch_array() - Fetch a row as an array
- pg_fetch_object() - Fetch a row as an object
- pg_fetch_result() - Returns values from a result instance

# pg_result_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_result_status — Get status of query result

### Description

pg_result_status(PgSql\Result `$result`, int `$mode` = `PGSQL_STATUS_LONG`): string|int

pg_result_status() returns the status of the PgSql\Result instance, or the PostgreSQL command completion tag associated with the result

### Parameters

`result`

  An PgSql\Result instance, returned by pg_query(), pg_query_params() or pg_execute()(among others).

`mode`

  Either `PGSQL_STATUS_LONG` to return the numeric status of the `result`, or `PGSQL_STATUS_STRING` to return the command tag of the `result`. If not specified, `PGSQL_STATUS_LONG` is the default.

### Return Values

Possible return values are `PGSQL_EMPTY_QUERY`, `PGSQL_COMMAND_OK`, `PGSQL_TUPLES_OK`, `PGSQL_TUPLES_CHUNK`, `PGSQL_COPY_OUT`, `PGSQL_COPY_IN`, `PGSQL_BAD_RESPONSE`, `PGSQL_NONFATAL_ERROR` and `PGSQL_FATAL_ERROR` if `PGSQL_STATUS_LONG` is specified. Otherwise, a string containing the PostgreSQL command tag is returned.

### Changelog

Version | Description
--- | ---
8.1.0 | The `result` parameter expects an PgSql\Result instance now; previously, a resource was expected.

### Examples

Example #1 pg_result_status() example

`<?php
// Connect to the database
$conn = pg_pconnect("dbname=publisher");
// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");
// Get the result status
$status = pg_result_status($result);
// Determine status
if ($status == PGSQL_COPY_IN)
echo "Copy began.";
else
echo "Copy failed.";
?>`

The above example will output:

    Copy began.

### See Also

- pg_connection_status() - Get connection status

# pg_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_select — Select records

### Description

pg_select(
PgSql\Connection `$connection`,
string `$table_name`,
array `$conditions` = [],
int `$flags` = `PGSQL_DML_EXEC`,
int `$mode` = `PGSQL_ASSOC`
): array|string|false

pg_select() selects records specified by `conditions` which has `field=>value`. For a successful query, it returns an array containing all records and fields that match the condition specified by `conditions`.

If `flags` is set, pg_convert() is applied to `conditions` with the specified flags.

If `mode` is set, the return value will be in the form of an array with `PGSQL_NUM`, an associative array with `PGSQL_ASSOC` (default) or both with `PGSQL_BOTH`.

By default pg_select() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table from which to select rows.

`conditions`

  An array whose keys are field names in the table `table_name`, and whose values are the conditions that a row must meet to be retrieved. As of PHP 8.4.0, when an empty array is provided, no conditions will apply. Previously, the function failed with an empty `conditions` argument.

`flags`

  Any number of `PGSQL_CONV_FORCE_NULL`, `PGSQL_DML_NO_CONV`, `PGSQL_DML_ESCAPE`, `PGSQL_DML_EXEC`, `PGSQL_DML_ASYNC` or `PGSQL_DML_STRING` combined. If `PGSQL_DML_STRING` is part of the `flags` then the query string is returned. When `PGSQL_DML_NO_CONV` or `PGSQL_DML_ESCAPE` is set, it does not call pg_convert() internally.

`mode`

  Any number of `PGSQL_ASSOC`, `PGSQL_NUM` or `PGSQL_BOTH` If `PGSQL_ASSOC` is set the return value will be an associative array, with `PGSQL_NUM` the return value will be an array, and with `PGSQL_BOTH` the return value will be both an associative and numerically indexed array.

### Return Values

Returns string if `PGSQL_DML_STRING` is passed via `flags`, otherwise it returns an array on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `conditions` is now optional.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
7.1.0 | The `mode` parameter was added.

### Examples

Example #1 pg_select() example

`<?php
$db = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$rec = pg_select($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($rec) {
echo "Records selected\n";
var_dump($rec);
} else {
echo "User must have sent wrong inputs\n";
}
?>`

### See Also

- pg_convert() - Convert associative array values into forms suitable for SQL statements

# pg_send_execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

### Description

pg_send_execute(PgSql\Connection `$connection`, string `$statement_name`, array `$params`): int|bool

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

### Parameters

`connection`

  An PgSql\Connection instance.

`statement_name`

  The name of the prepared statement to execute. If "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a `PREPARE` SQL command.

`params`

  An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

### Return Values

Returns `true` on success, `false` or `0` on failure. Use pg_get_result() to determine the query result.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_send_execute()

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}
// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}
?>`

### See Also

- pg_prepare() - Submits a request to the server to create a prepared statement with the given parameters, and waits for completion
- pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
- pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result

# pg_send_prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion

### Description

pg_send_prepare(PgSql\Connection `$connection`, string `$statement_name`, string `$query`): int|bool

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns `true` if it was able to dispatch the request, and `false` if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

### Parameters

`connection`

  An PgSql\Connection instance.

`statement_name`

  The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

`query`

  The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

### Return Values

Returns `true` on success, `false` or `0` on failure. Use pg_get_result() to determine the query result.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_send_prepare()

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}
// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}
?>`

### See Also

- pg_connect() - Open a PostgreSQL connection
- pg_pconnect() - Open a persistent PostgreSQL connection
- pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
- pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
- pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s)

# pg_send_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_send_query — Sends asynchronous query

### Description

pg_send_query(PgSql\Connection `$connection`, string `$query`): int|bool

pg_send_query() sends a query or queries asynchronously to the `connection`. Unlike pg_query(), it can send multiple queries at once to PostgreSQL and get the results one by one using pg_get_result().

Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().

Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.

### Parameters

`connection`

  An PgSql\Connection instance.

`query`

  The SQL statement or statements to be executed.

  Data inside the query should be properly escaped.

### Return Values

Returns `true` on success, `false` or `0` on failure. Use pg_get_result() to determine the query result.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_send_query() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>`

The above example will output:

    First call to pg_get_result(): Resource id #3
    Resource id #3 has 3 records

    Second call to pg_get_result(): Resource id #4
    Resource id #4 has 1 records

### See Also

- pg_query() - Execute a query
- pg_cancel_query() - Cancel an asynchronous query
- pg_get_result() - Get asynchronous query result
- pg_connection_busy() - Get connection is busy or not

# pg_send_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)

### Description

pg_send_query_params(PgSql\Connection `$connection`, string `$query`, array `$params`): int|bool

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the `query` string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

### Parameters

`connection`

  An PgSql\Connection instance.

`query`

  The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

`params`

  An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

### Return Values

Returns `true` on success, `false` or `0` on failure. Use pg_get_result() to determine the query result.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 Using pg_send_query_params()

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Using parameters. Note that it is not necessary to quote or escape
// the parameter.
pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));
// Compare against basic pg_send_query usage
$str = pg_escape_string('Perth');
pg_send_query($dbconn, "select count(*) from authors where city = '{$str}'");
?>`

### See Also

- pg_send_query() - Sends asynchronous query

# pg_set_chunked_rows_size

(PHP 8 >= 8.4.0)

pg_set_chunked_rows_size — Set the query results to be retrieved in chunk mode

### Description

pg_set_chunked_rows_size(PgSql\Connection `$connection`, int `$size`): bool

Set the query results to be retrieved in chunk mode. The query results returned afterward will be divided into multiple chunks, each containing up to `size` rows. This function must be called before retrieving results with pg_get_result(). This function is only available when libpq is version 17 or higher.

### Parameters

`connection`

  An PgSql\Connection instance.

`size`
  The number of rows to be retrieved in each chunk.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

If `size` is less than `1`, a ValueError will be thrown.

### Examples

Example #1 pg_result_memory_size() example

`<?php
$conn = pg_connect($conn_str);
for ($i = 0; $i < 10; $i ++) {
pg_query($conn, "INSERT INTO users DEFAULT VALUES");
}
pg_send_query($conn, "SELECT * FROM users");
pg_set_chunked_rows_size($conn, 1);
$result = pg_get_result($conn);
var_dump(pg_num_rows($result));
// No effect after the result is retrieved
var_dump(pg_set_chunked_rows_size($conn, 10));`

The above example will output:

    int(1)
    bool(false)

### See Also

- pg_get_result() - Get asynchronous query result
- pg_result_status() - Get status of query result

# pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_set_client_encoding — Set the client encoding

### Description

pg_set_client_encoding(PgSql\Connection `$connection` = ?, string `$encoding`): int

pg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.

PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.

> Note:

> The function used to be called pg_setclientencoding().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`encoding`

  The required client encoding. One of `SQL_ASCII`, `EUC_JP`, `EUC_CN`, `EUC_KR`, `EUC_TW`, `UNICODE`, `MULE_INTERNAL`, `LATINX` (X=1...9), `KOI8`, `WIN`, `ALT`, `SJIS`, `BIG5` or `WIN1250`.

  The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.

### Return Values

Returns `0` on success or `-1` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_set_client_encoding() example

`<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Set the client encoding to UNICODE. Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>`

### See Also

- pg_client_encoding() - Gets the client encoding

# pg_set_error_context_visibility

(PHP 8 >= 8.3.0)

pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error() and pg_result_error()

### Description

pg_set_error_context_visibility(PgSql\Connection `$connection`, int `$visibility`): int

Determines the visibility of the context's error messages returned by pg_last_error() and pg_result_error()

### Parameters

`connection`

  An PgSql\Connection instance.

`visibility`

  The required visibility: `PGSQL_SHOW_CONTEXT_NEVER`, `PGSQL_SHOW_CONTEXT_ERRORS` or `PGSQL_SHOW_CONTEXT_ALWAYS`.

### Return Values

The previous visibility level: `PGSQL_SHOW_CONTEXT_NEVER`, `PGSQL_SHOW_CONTEXT_ERRORS` or `PGSQL_SHOW_CONTEXT_ALWAYS`.

### Examples

Example #1 pg_set_error_context_visibility() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
pg_set_error_context_visibility($dbconn, PGSQL_SHOW_CONTEXT_ALWAYS);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>`

### See Also

- pg_last_error() - Get the last error message string of a connection
- pg_result_error() - Get error message associated with result

# pg_set_error_verbosity

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error()

### Description

pg_set_error_verbosity(PgSql\Connection `$connection` = ?, int `$verbosity`): int|false

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In `PGSQL_ERRORS_TERSE` mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (`PGSQL_ERRORS_DEFAULT`) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The `PGSQL_ERRORS_VERBOSE` mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`verbosity`

  The required verbosity: `PGSQL_ERRORS_TERSE`, `PGSQL_ERRORS_DEFAULT` or `PGSQL_ERRORS_VERBOSE`.

### Return Values

The previous verbosity level: `PGSQL_ERRORS_TERSE`, `PGSQL_ERRORS_DEFAULT` or `PGSQL_ERRORS_VERBOSE`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_set_error_verbosity() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>`

### See Also

- pg_last_error() - Get the last error message string of a connection
- pg_result_error() - Get error message associated with result

# pg_socket

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection

### Description

pg_socket(PgSql\Connection `$connection`): resource|false

pg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

A socket resource on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

# pg_trace

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

pg_trace — Enable tracing a PostgreSQL connection

### Description

pg_trace(
string `$filename`,
string `$mode` = "w",
?PgSql\Connection `$connection` = `null`,
int `$trace_mode` = 0
): bool

pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.

For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the » PostgreSQL Documentation.

### Parameters

`filename`

  The full path and file name of the file in which to write the trace log. Same as in fopen().

`mode`

  An optional file access mode, same as for fopen().

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

`trace_mode`

  An optional trace mode with the following constants `PGSQL_TRACE_SUPPRESS_TIMESTAMPS` and `PGSQL_TRACE_REGRESS_MODE`

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | `trace_mode` has been added.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_trace() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now /tmp/trace.log will contain backend communication
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>`

### See Also

- fopen() - Opens file or URL
- pg_untrace() - Disable tracing of a PostgreSQL connection

# pg_transaction_status

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_transaction_status — Returns the current in-transaction status of the server

### Description

pg_transaction_status(PgSql\Connection `$connection`): int

Returns the current in-transaction status of the server.

Caution

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter `autocommit` set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

### Parameters

`connection`

  An PgSql\Connection instance.

### Return Values

The status can be `PGSQL_TRANSACTION_IDLE` (currently idle), `PGSQL_TRANSACTION_ACTIVE` (a command is in progress), `PGSQL_TRANSACTION_INTRANS` (idle, in a valid transaction block), or `PGSQL_TRANSACTION_INERROR` (idle, in a failed transaction block). `PGSQL_TRANSACTION_UNKNOWN` is reported if the connection is bad. `PGSQL_TRANSACTION_ACTIVE` is reported only when a query has been sent to the server and not yet completed.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_transaction_status() example

`<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_transaction_status($dbconn);
if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
echo 'Connection is bad';
} else if ($stat === PGSQL_TRANSACTION_IDLE) {
echo 'Connection is currently idle';
} else {
echo 'Connection is in a transaction state';
}
?>`

# pg_tty

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_tty — Return the TTY name associated with the connection

### Description

pg_tty(?PgSql\Connection `$connection` = `null`): string

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL `connection` instance.

> Note:

> pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

A string containing the debug TTY of the `connection`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_tty() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>`

# pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_unescape_bytea — Unescape binary for bytea type

### Description

pg_unescape_bytea(string `$string`): string

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

> Note:

> When you `SELECT` a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

### Parameters

`string`

  A string containing PostgreSQL bytea data to be converted into a PHP binary string.

### Return Values

A string containing the unescaped data.

### Examples

Example #1 pg_unescape_bytea() example

`<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Get the bytea data
$res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
$raw = pg_fetch_result($res, 'data');
// Convert to binary and send to the browser
header('Content-type: image/jpeg');
echo pg_unescape_bytea($raw);
?>`

### See Also

- pg_escape_bytea() - Escape a string for insertion into a bytea field
- pg_escape_string() - Escape a string for query

# pg_untrace

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

pg_untrace — Disable tracing of a PostgreSQL connection

### Description

pg_untrace(?PgSql\Connection `$connection` = `null`): true

Stop tracing started by pg_trace().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_untrace() example

`<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now tracing of backend communication is disabled
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>`

### See Also

- pg_trace() - Enable tracing a PostgreSQL connection

# pg_update

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_update — Update table

### Description

pg_update(
PgSql\Connection `$connection`,
string `$table_name`,
array `$values`,
array `$conditions`,
int `$flags` = `PGSQL_DML_EXEC`
): string|bool

pg_update() updates records that matches `conditions` with `values`.

If `flags` is specified, pg_convert() is applied to `values` with the specified flags.

By default pg_update() passes raw values. Values must be escaped or the `PGSQL_DML_ESCAPE` flag must be specified in `flags`. `PGSQL_DML_ESCAPE` quotes and escapes parameters/identifiers. Therefore, table/column names become case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

### Parameters

`connection`

  An PgSql\Connection instance.

`table_name`

  Name of the table into which to update rows.

`values`

  An array whose keys are field names in the table `table_name`, and whose values are what matched rows are to be updated to.

`conditions`

  An array whose keys are field names in the table `table_name`, and whose values are the conditions that a row must meet to be updated.

`flags`

  Any number of `PGSQL_CONV_FORCE_NULL`, `PGSQL_DML_NO_CONV`, `PGSQL_DML_ESCAPE`, `PGSQL_DML_EXEC`, `PGSQL_DML_ASYNC` or `PGSQL_DML_STRING` combined. If `PGSQL_DML_STRING` is part of the `flags` then query string is returned. When `PGSQL_DML_NO_CONV` or `PGSQL_DML_ESCAPE` is set, it does not call pg_convert() internally.

### Return Values

Returns `true` on success or `false` on failure. Returns string if `PGSQL_DML_STRING` is passed via `flags`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.

### Examples

Example #1 pg_update() example

`<?php
$db = pg_connect('dbname=foo');
$data = array('field1'=>'AA', 'field2'=>'BB');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_update($db, 'post_log', $_POST, $data);
if ($res) {
echo "Data is updated: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>`

### See Also

- pg_convert() - Convert associative array values into forms suitable for SQL statements

# pg_version

(PHP 5, PHP 7, PHP 8)

pg_version — Returns an array with client, protocol and server version (when available)

### Description

pg_version(?PgSql\Connection `$connection` = `null`): array

pg_version() returns an array with the client, protocol and server version.

For more detailed server information, use pg_parameter_status().

### Parameters

`connection`

  An PgSql\Connection instance. When `connection` is `null`, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

  Warning

  As of PHP 8.1.0, using the default connection is deprecated.

### Return Values

Returns an array with `client`, `protocol` and `server` keys and values (if available).

### Changelog

Version | Description
--- | ---
8.1.0 | The `connection` parameter expects an PgSql\Connection instance now; previously, a resource was expected.
8.0.0 | `connection` is now nullable.

### Examples

Example #1 pg_version() example

`<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");
$v = pg_version($dbconn);
echo $v['client'];
?>`

The above example will output:

    7.4

### See Also

- pg_parameter_status() - Looks up a current parameter setting of the server

## Table of Contents

- pg_affected_rows — Returns number of affected records (tuples)
- pg_cancel_query — Cancel an asynchronous query
- pg_client_encoding — Gets the client encoding
- pg_close — Closes a PostgreSQL connection
- pg_connect — Open a PostgreSQL connection
- pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt
- pg_connection_busy — Get connection is busy or not
- pg_connection_reset — Reset connection (reconnect)
- pg_connection_status — Get connection status
- pg_consume_input — Reads input on the connection
- pg_convert — Convert associative array values into forms suitable for SQL statements
- pg_copy_from — Insert records into a table from an array
- pg_copy_to — Copy a table to an array
- pg_dbname — Get the database name
- pg_delete — Deletes records
- pg_end_copy — Sync with PostgreSQL backend
- pg_escape_bytea — Escape a string for insertion into a bytea field
- pg_escape_identifier — Escape an identifier for insertion into a text field
- pg_escape_literal — Escape a literal for insertion into a text field
- pg_escape_string — Escape a string for query
- pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result
- pg_fetch_all — Fetches all rows from a result as an array
- pg_fetch_all_columns — Fetches all rows in a particular result column as an array
- pg_fetch_array — Fetch a row as an array
- pg_fetch_assoc — Fetch a row as an associative array
- pg_fetch_object — Fetch a row as an object
- pg_fetch_result — Returns values from a result instance
- pg_fetch_row — Get a row as an enumerated array
- pg_field_is_null — Test if a field is SQL NULL
- pg_field_name — Returns the name of a field
- pg_field_num — Returns the field number of the named field
- pg_field_prtlen — Returns the printed length
- pg_field_size — Returns the internal storage size of the named field
- pg_field_table — Returns the name or oid of the tables field
- pg_field_type — Returns the type name for the corresponding field number
- pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
- pg_flush — Flush outbound query data on the connection
- pg_free_result — Free result memory
- pg_get_notify — Gets SQL NOTIFY message
- pg_get_pid — Gets the backend's process ID
- pg_get_result — Get asynchronous query result
- pg_host — Returns the host name associated with the connection
- pg_insert — Insert array into table
- pg_last_error — Get the last error message string of a connection
- pg_last_notice — Returns the last notice message from PostgreSQL server
- pg_last_oid — Returns the last row's OID
- pg_lo_close — Close a large object
- pg_lo_create — Create a large object
- pg_lo_export — Export a large object to file
- pg_lo_import — Import a large object from file
- pg_lo_open — Open a large object
- pg_lo_read — Read a large object
- pg_lo_read_all — Reads an entire large object and send straight to browser
- pg_lo_seek — Seeks position within a large object
- pg_lo_tell — Returns current seek position a of large object
- pg_lo_truncate — Truncates a large object
- pg_lo_unlink — Delete a large object
- pg_lo_write — Write to a large object
- pg_meta_data — Get meta data for table
- pg_num_fields — Returns the number of fields in a result
- pg_num_rows — Returns the number of rows in a result
- pg_options — Get the options associated with the connection
- pg_parameter_status — Looks up a current parameter setting of the server
- pg_pconnect — Open a persistent PostgreSQL connection
- pg_ping — Ping database connection
- pg_port — Return the port number associated with the connection
- pg_prepare — Submits a request to the server to create a prepared statement with the given parameters, and waits for completion
- pg_put_line — Send a NULL-terminated string to PostgreSQL backend
- pg_query — Execute a query
- pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
- pg_result_error — Get error message associated with result
- pg_result_error_field — Returns an individual field of an error report
- pg_result_memory_size — Returns the amount of memory allocated for a query result
- pg_result_seek — Set internal row offset in result instance
- pg_result_status — Get status of query result
- pg_select — Select records
- pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
- pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion
- pg_send_query — Sends asynchronous query
- pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)
- pg_set_chunked_rows_size — Set the query results to be retrieved in chunk mode
- pg_set_client_encoding — Set the client encoding
- pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
- pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error
- pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
- pg_trace — Enable tracing a PostgreSQL connection
- pg_transaction_status — Returns the current in-transaction status of the server
- pg_tty — Return the TTY name associated with the connection
- pg_unescape_bytea — Unescape binary for bytea type
- pg_untrace — Disable tracing of a PostgreSQL connection
- pg_update — Update table
- pg_version — Returns an array with client, protocol and server version (when available)

# The PgSql\Connection class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `pgsql link` resource as of PHP 8.1.0.

## Class synopsis

namespace PgSql;
final class Connection {
}

# The PgSql\Result class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `pgsql result` resource as of PHP 8.1.0.

## Class synopsis

namespace PgSql;
final class Result {
}

# The PgSql\Lob class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `pgsql large object` resource as of PHP 8.1.0.

## Class synopsis

namespace PgSql;
final class Lob {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
  - Basic usage
  - Basic usage
- PostgreSQL Functions
  - pg_affected_rows — Returns number of affected records (tuples)
  - pg_cancel_query — Cancel an asynchronous query
  - pg_client_encoding — Gets the client encoding
  - pg_close — Closes a PostgreSQL connection
  - pg_connect — Open a PostgreSQL connection
  - pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt
  - pg_connection_busy — Get connection is busy or not
  - pg_connection_reset — Reset connection (reconnect)
  - pg_connection_status — Get connection status
  - pg_consume_input — Reads input on the connection
  - pg_convert — Convert associative array values into forms suitable for SQL statements
  - pg_copy_from — Insert records into a table from an array
  - pg_copy_to — Copy a table to an array
  - pg_dbname — Get the database name
  - pg_delete — Deletes records
  - pg_end_copy — Sync with PostgreSQL backend
  - pg_escape_bytea — Escape a string for insertion into a bytea field
  - pg_escape_identifier — Escape an identifier for insertion into a text field
  - pg_escape_literal — Escape a literal for insertion into a text field
  - pg_escape_string — Escape a string for query
  - pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result
  - pg_fetch_all — Fetches all rows from a result as an array
  - pg_fetch_all_columns — Fetches all rows in a particular result column as an array
  - pg_fetch_array — Fetch a row as an array
  - pg_fetch_assoc — Fetch a row as an associative array
  - pg_fetch_object — Fetch a row as an object
  - pg_fetch_result — Returns values from a result instance
  - pg_fetch_row — Get a row as an enumerated array
  - pg_field_is_null — Test if a field is SQL NULL
  - pg_field_name — Returns the name of a field
  - pg_field_num — Returns the field number of the named field
  - pg_field_prtlen — Returns the printed length
  - pg_field_size — Returns the internal storage size of the named field
  - pg_field_table — Returns the name or oid of the tables field
  - pg_field_type — Returns the type name for the corresponding field number
  - pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
  - pg_flush — Flush outbound query data on the connection
  - pg_free_result — Free result memory
  - pg_get_notify — Gets SQL NOTIFY message
  - pg_get_pid — Gets the backend's process ID
  - pg_get_result — Get asynchronous query result
  - pg_host — Returns the host name associated with the connection
  - pg_insert — Insert array into table
  - pg_last_error — Get the last error message string of a connection
  - pg_last_notice — Returns the last notice message from PostgreSQL server
  - pg_last_oid — Returns the last row's OID
  - pg_lo_close — Close a large object
  - pg_lo_create — Create a large object
  - pg_lo_export — Export a large object to file
  - pg_lo_import — Import a large object from file
  - pg_lo_open — Open a large object
  - pg_lo_read — Read a large object
  - pg_lo_read_all — Reads an entire large object and send straight to browser
  - pg_lo_seek — Seeks position within a large object
  - pg_lo_tell — Returns current seek position a of large object
  - pg_lo_truncate — Truncates a large object
  - pg_lo_unlink — Delete a large object
  - pg_lo_write — Write to a large object
  - pg_meta_data — Get meta data for table
  - pg_num_fields — Returns the number of fields in a result
  - pg_num_rows — Returns the number of rows in a result
  - pg_options — Get the options associated with the connection
  - pg_parameter_status — Looks up a current parameter setting of the server
  - pg_pconnect — Open a persistent PostgreSQL connection
  - pg_ping — Ping database connection
  - pg_port — Return the port number associated with the connection
  - pg_prepare — Submits a request to the server to create a prepared statement with the given parameters, and waits for completion
  - pg_put_line — Send a NULL-terminated string to PostgreSQL backend
  - pg_query — Execute a query
  - pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  - pg_result_error — Get error message associated with result
  - pg_result_error_field — Returns an individual field of an error report
  - pg_result_memory_size — Returns the amount of memory allocated for a query result
  - pg_result_seek — Set internal row offset in result instance
  - pg_result_status — Get status of query result
  - pg_select — Select records
  - pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
  - pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion
  - pg_send_query — Sends asynchronous query
  - pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)
  - pg_set_chunked_rows_size — Set the query results to be retrieved in chunk mode
  - pg_set_client_encoding — Set the client encoding
  - pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
  - pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error
  - pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
  - pg_trace — Enable tracing a PostgreSQL connection
  - pg_transaction_status — Returns the current in-transaction status of the server
  - pg_tty — Return the TTY name associated with the connection
  - pg_unescape_bytea — Unescape binary for bytea type
  - pg_untrace — Disable tracing of a PostgreSQL connection
  - pg_update — Update table
  - pg_version — Returns an array with client, protocol and server version (when available)
- PgSql\Connection — The PgSql\Connection class
- PgSql\Result — The PgSql\Result class
- PgSql\Lob — The PgSql\Lob class

# SQLite3

# Introduction

Support for SQLite version 3 databases.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

As of PHP 7.4.0 » libsqlite ≥ 3.7.4 is required. Formerly, the bundled libsqlite could have been used instead.

## Installation

The SQLite3 extension is enabled by default. It's possible to disable it by using `--without-sqlite3` at compile time.

Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP.

> Note: Additional setup on Windows as of PHP 7.4.0

> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsqlite3.dll.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite3 Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
sqlite3.extension_dir | "" | `INI_SYSTEM` |
sqlite3.defensive | 1 | `INI_USER` | Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0. Prior to PHP 8.2.0 this setting was changeable only as `INI_SYSTEM`.

Here's a short explanation of the configuration directives.

`sqlite3.extension_dir` string

  Path to the directory where the loadable extensions for SQLite reside.

`sqlite3.defensive` bool

  When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. This forbids writing directly to the schema, shadow tables (eg. FTS data tables), or the sqlite_dbpage virtual table. This php.ini setting is only effective for libsqlite ≥ 3.26.0.

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

`SQLITE3_ASSOC` (int)
  Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column name as returned in the corresponding result set.
`SQLITE3_NUM` (int)
  Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column number as returned in the corresponding result set, starting at column 0.
`SQLITE3_BOTH` (int)
  Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
`SQLITE3_INTEGER` (int)
  Represents the SQLite3 INTEGER storage class.
`SQLITE3_FLOAT` (int)
  Represents the SQLite3 REAL (FLOAT) storage class.
`SQLITE3_TEXT` (int)
  Represents the SQLite3 TEXT storage class.
`SQLITE3_BLOB` (int)
  Represents the SQLite3 BLOB storage class.
`SQLITE3_NULL` (int)
  Represents the SQLite3 NULL storage class.
`SQLITE3_OPEN_READONLY` (int)
  Specifies that the SQLite3 database be opened for reading only.
`SQLITE3_OPEN_READWRITE` (int)
  Specifies that the SQLite3 database be opened for reading and writing.
`SQLITE3_OPEN_CREATE` (int)
  Specifies that the SQLite3 database be created if it does not already exist.
`SQLITE3_DETERMINISTIC` (int)
  Specifies that a function created with SQLite3::createFunction() is deterministic, i.e. it always returns the same result given the same inputs within a single SQL statement. (Available as of PHP 7.1.4.)

# The SQLite3 class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

A class that interfaces SQLite 3 databases.

## Class synopsis

class SQLite3 {
/* Constants */
public const int OK;
public const int DENY;
public const int IGNORE;
public const int CREATE_INDEX;
public const int CREATE_TABLE;
public const int CREATE_TEMP_INDEX;
public const int CREATE_TEMP_TABLE;
public const int CREATE_TEMP_TRIGGER;
public const int CREATE_TEMP_VIEW;
public const int CREATE_TRIGGER;
public const int CREATE_VIEW;
public const int DELETE;
public const int DROP_INDEX;
public const int DROP_TABLE;
public const int DROP_TEMP_INDEX;
public const int DROP_TEMP_TABLE;
public const int DROP_TEMP_TRIGGER;
public const int DROP_TEMP_VIEW;
public const int DROP_TRIGGER;
public const int DROP_VIEW;
public const int INSERT;
public const int PRAGMA;
public const int READ;
public const int SELECT;
public const int TRANSACTION;
public const int UPDATE;
public const int ATTACH;
public const int DETACH;
public const int ALTER_TABLE;
public const int REINDEX;
public const int ANALYZE;
public const int CREATE_VTABLE;
public const int DROP_VTABLE;
public const int FUNCTION;
public const int SAVEPOINT;
public const int COPY;
public const int RECURSIVE;
/* Methods */
public __construct(string `$filename`, int `$flags` = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string `$encryptionKey` = "")
public backup(SQLite3 `$destination`, string `$sourceDatabase` = "main", string `$destinationDatabase` = "main"): bool
public busyTimeout(int `$milliseconds`): bool
public changes(): int
public close(): bool
public createAggregate(
string `$name`,
callable `$stepCallback`,
callable `$finalCallback`,
int `$argCount` = -1
): bool
public createCollation(string `$name`, callable `$callback`): bool
public createFunction(
string `$name`,
callable `$callback`,
int `$argCount` = -1,
int `$flags` = 0
): bool
public enableExceptions(bool `$enable` = `false`): bool
public static escapeString(string `$string`): string
public exec(string `$query`): bool
public lastErrorCode(): int
public lastErrorMsg(): string
public lastInsertRowID(): int
public loadExtension(string `$name`): bool
public open(string `$filename`, int `$flags` = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string `$encryptionKey` = ""): void
public openBlob(
string `$table`,
string `$column`,
int `$rowid`,
string `$database` = "main",
int `$flags` = `SQLITE3_OPEN_READONLY`
): resource|false
public prepare(string `$query`): SQLite3Stmt|false
public query(string `$query`): SQLite3Result|false
public querySingle(string `$query`, bool `$entireRow` = `false`): mixed
public setAuthorizer(?callable `$callback`): bool
public static version(): array
}

## Predefined Constants

`SQLite3::OK`

`SQLite3::DENY`

`SQLite3::IGNORE`

`SQLite3::CREATE_INDEX`

`SQLite3::CREATE_TABLE`

`SQLite3::CREATE_TEMP_INDEX`

`SQLite3::CREATE_TEMP_TABLE`

`SQLite3::CREATE_TEMP_TRIGGER`

`SQLite3::CREATE_TEMP_VIEW`

`SQLite3::CREATE_TRIGGER`

`SQLite3::CREATE_VIEW`

`SQLite3::DELETE`

`SQLite3::DROP_INDEX`

`SQLite3::DROP_TABLE`

`SQLite3::DROP_TEMP_INDEX`

`SQLite3::DROP_TEMP_TABLE`

`SQLite3::DROP_TEMP_TRIGGER`

`SQLite3::DROP_TEMP_VIEW`

`SQLite3::DROP_TRIGGER`

`SQLite3::DROP_VIEW`

`SQLite3::INSERT`

`SQLite3::PRAGMA`

`SQLite3::READ`

`SQLite3::SELECT`

`SQLite3::TRANSACTION`

`SQLite3::UPDATE`

`SQLite3::ATTACH`

`SQLite3::DETACH`

`SQLite3::ALTER_TABLE`

`SQLite3::REINDEX`

`SQLite3::ANALYZE`

`SQLite3::CREATE_VTABLE`

`SQLite3::DROP_VTABLE`

`SQLite3::FUNCTION`

`SQLite3::SAVEPOINT`

`SQLite3::COPY`

`SQLite3::RECURSIVE`

# SQLite3::backup

(PHP 7 >= 7.4.0, PHP 8)

SQLite3::backup — Backup one database to another database

### Description

public SQLite3::backup(SQLite3 `$destination`, string `$sourceDatabase` = "main", string `$destinationDatabase` = "main"): bool

SQLite3::backup() copies the contents of one database into another, overwriting the contents of the destination database. It is useful either for creating backups of databases or for copying in-memory databases to or from persistent files.

Tip

As of SQLite 3.27.0 (2019-02-07), it is also possible to use the statement `VACUUM INTO 'file.db';` to backup the database to a new file.

### Parameters

`destination`

  A database connection opened with SQLite3::open().

`sourceDatabase`

  The database name is `"main"` for the main database, `"temp"` for the temporary database, or the name specified after the `AS` keyword in an `ATTACH` statement for an attached database.

`destinationDatabase`

  Analogous to `sourceDatabase` but for the `destination`.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Backup an existing database

`<?php
// $conn is a connection to an already opened sqlite3 database
$backup = new SQLite3('backup.sqlite');
$conn->backup($backup);
?>`

# SQLite3::busyTimeout

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

SQLite3::busyTimeout — Sets the busy connection handler

### Description

public SQLite3::busyTimeout(int `$milliseconds`): bool

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

### Parameters

`milliseconds`

  The milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.

### Return Values

Returns `true` on success, or `false` on failure.

# SQLite3::changes

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

### Description

public SQLite3::changes(): int

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

### Parameters

This function has no parameters.

### Return Values

Returns an int value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

### Examples

Example #1 SQLite3::changes() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
echo 'Number of rows modified: ', $db->changes();
}
?>`

# SQLite3::close

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::close — Closes the database connection

### Description

public SQLite3::close(): bool

Closes the database connection.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 SQLite3::close() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>`

# SQLite3::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database

### Description

public SQLite3::__construct(string `$filename`, int `$flags` = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string `$encryptionKey` = "")

Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.

### Parameters

`filename`

  Path to the SQLite database, or `:memory:` to use in-memory database. If `filename` is an empty string, then a private, temporary on-disk database will be created. This private database will be automatically deleted as soon as the database connection is closed.

`flags`

  Optional flags used to determine how to open the SQLite database. By default, open uses `SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE`.

  - `SQLITE3_OPEN_READONLY`: Open the database for reading only.

  - `SQLITE3_OPEN_READWRITE`: Open the database for reading and writing.

  - `SQLITE3_OPEN_CREATE`: Create the database if it does not exist.

`encryptionKey`

  An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.

### Errors/Exceptions

Throws an Exception on failure.

### Changelog

Version | Description
--- | ---
7.0.10 | The `filename` can now be empty to use a private, temporary on-disk database.

### Examples

Example #1 SQLite3::__construct() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE foo (bar TEXT)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>`

# SQLite3::createAggregate

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

### Description

public SQLite3::createAggregate(
string `$name`,
callable `$stepCallback`,
callable `$finalCallback`,
int `$argCount` = -1
): bool

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

### Parameters

`name`

  Name of the SQL aggregate to be created or redefined.

`stepCallback`

  Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

  This function need to be defined as:

  step(
  mixed `$context`,
  int `$rownumber`,
  mixed `$value`,
  mixed `...$values`
  ): mixed
  `context`

    `null` for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

  `rownumber`

    The current row number.

  `value`

    The first argument passed to the aggregate.

  `values`

    Further arguments passed to the aggregate.

  The return value of this function will be used as the `context` argument in the next call of the step or finalize functions.
`finalCallback`

  Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).

  This function need to be defined as:

  fini(mixed `$context`, int `$rownumber`): mixed
  `context`

    Holds the return value from the very last call to the step function.

  `rownumber`

    Always `0`.

  The return value of this function will be used as the return value for the aggregate.
`argCount`

  The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

### Return Values

Returns `true` upon successful creation of the aggregate, or `false` on failure.

### Examples

Example #1 max_length aggregation function example

`<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->bindValue(1, $str);
$insert->execute();
}
$insert = null;
function max_len_step($context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}
function max_len_finalize($context, $rownumber)
{
return $context === null ? 0 : $context;
}
$db->createAggregate('max_len', 'max_len_step', 'max_len_finalize');
var_dump($db->querySingle('SELECT max_len(a) from strings'));
?>`

The above example will output:

    int(5)

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the `max_len_step` function is called and passed a `$context` parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the `$string` has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the `max_len_finalize` function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the `$context`. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use SQLite3::createAggregate() to override SQLite native SQL functions.

# SQLite3::createCollation

(PHP 5 >= 5.3.11, PHP 7, PHP 8)

SQLite3::createCollation — Registers a PHP function for use as an SQL collating function

### Description

public SQLite3::createCollation(string `$name`, callable `$callback`): bool

Registers a PHP function or user-defined function for use as a collating function within SQL statements.

### Parameters

`name`

  Name of the SQL collating function to be created or redefined

`callback`

  The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two values and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

  This function need to be defined as:

  collation(mixed `$value1`, mixed `$value2`): int

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 SQLite3::createCollation() example

Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.

`<?php
$db = new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");
$db->createCollation('NATURAL_CMP', 'strnatcmp');
$defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");
echo "default:\n";
while ($row = $defaultSort->fetchArray()){
echo $row['col1'], "\n";
}
echo "\nnatural:\n";
while ($row = $naturalSort->fetchArray()){
echo $row['col1'], "\n";
}
$db->close();
?>`

The above example will output:

    default:
    a1
    a10
    a2

    natural:
    a1
    a2
    a10

### See Also

- The SQLite collation documentation: » http://sqlite.org/datatype3.html#collation

# SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

### Description

public SQLite3::createFunction(
string `$name`,
callable `$callback`,
int `$argCount` = -1,
int `$flags` = 0
): bool

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

### Parameters

`name`

  Name of the SQL function to be created or redefined.

`callback`

  The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

  This function need to be defined as:

  callback(mixed `$value`, mixed `...$values`): mixed
  `value`

    The first argument passed to the SQL function.

  `values`

    Further arguments passed to the SQL function.

`argCount`

  The number of arguments that the SQL function takes. If this parameter is `-1`, then the SQL function may take any number of arguments.

`flags`

  A bitwise conjunction of flags. Currently, only `SQLITE3_DETERMINISTIC` is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

### Return Values

Returns `true` upon successful creation of the function, `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.4 | The `flags` parameter has been added.

### Examples

Example #1 SQLite3::createFunction() example

`<?php
function my_udf_md5($string) {
return hash('md5', $string);
}
$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');
var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>`

The above example will output something similar to:

    string(32) "098f6bcd4621d373cade4e832627b4f6"

# SQLite3::enableExceptions

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::enableExceptions — Enable throwing exceptions

### Description

public SQLite3::enableExceptions(bool `$enable` = `false`): bool

Controls whether the SQLite3 instance will throw exceptions or warnings on error.

### Parameters

`enable`

  When `true`, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will throw exceptions on error.

  When `false`, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will raise warnings on error.

  For either mode, the error code and message, if any, will be available via SQLite3::lastErrorCode() and SQLite3::lastErrorMsg() respectively.

### Return Values

Returns the old value; `true` if exceptions were enabled, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.3.0 | Calling SQLite3::enableExceptions() with `enable` as `false` will trigger a `E_DEPRECATED` warning.

### Examples

Example #1 SQLite3::enableExceptions() example

`<?php
$sqlite = new SQLite3(':memory:');
try {
$sqlite->exec('create table foo');
$sqlite->enableExceptions(true);
$sqlite->exec('create table bar');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>`

The above example will output something similar to:

    Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4
    Caught exception: near "bar": syntax error

# SQLite3::escapeString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::escapeString — Returns a string that has been properly escaped

### Description

public static SQLite3::escapeString(string `$string`): string

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Warning

This function is not (yet) binary safe!

To properly handle BLOB fields which may contain NUL characters, use SQLite3Stmt::bindParam() instead.

### Parameters

`string`

  The string to be escaped.

### Return Values

Returns a properly escaped string that may be used safely in an SQL statement.

### Notes

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

# SQLite3::exec

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::exec — Executes a result-less query against a given database

### Description

public SQLite3::exec(string `$query`): bool

Executes a result-less query against a given database.

> Note: SQLite3 may need to create » temporary files during the execution of queries, so the respective directories may have to be writable.

### Parameters

`query`

  The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

### Return Values

Returns `true` if the query succeeded, `false` on failure.

### Examples

Example #1 SQLite3::exec() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE bar (bar TEXT)');
?>`

# SQLite3::lastErrorCode

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

### Description

public SQLite3::lastErrorCode(): int

Returns the numeric result code of the most recent failed SQLite request.

### Parameters

This function has no parameters.

### Return Values

Returns an integer value representing the numeric result code of the most recent failed SQLite request.

# SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

### Description

public SQLite3::lastErrorMsg(): string

Returns English text describing the most recent failed SQLite request.

### Parameters

This function has no parameters.

### Return Values

Returns an English string describing the most recent failed SQLite request.

# SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

### Description

public SQLite3::lastInsertRowID(): int

Returns the row ID of the most recent INSERT into the database.

### Parameters

This function has no parameters.

### Return Values

Returns the row ID of the most recent INSERT into the database. If no successful INSERTs into rowid tables have ever occurred on this database connection, then SQLite3::lastInsertRowID() returns `0`.

# SQLite3::loadExtension

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::loadExtension — Attempts to load an SQLite extension library

### Description

public SQLite3::loadExtension(string `$name`): bool

Attempts to load an SQLite extension library.

### Parameters

`name`

  The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

### Return Values

Returns `true` if the extension is successfully loaded, `false` on failure.

### Examples

Example #1 SQLite3::loadExtension() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>`

# SQLite3::open

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::open — Opens an SQLite database

### Description

public SQLite3::open(string `$filename`, int `$flags` = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string `$encryptionKey` = ""): void

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

### Parameters

`filename`

  Path to the SQLite database, or `:memory:` to use in-memory database.

`flags`

  Optional flags used to determine how to open the SQLite database. By default, open uses `SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE`.

  - `SQLITE3_OPEN_READONLY`: Open the database for reading only.

  - `SQLITE3_OPEN_READWRITE`: Open the database for reading and writing.

  - `SQLITE3_OPEN_CREATE`: Create the database if it does not exist.

`encryptionKey`

  An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.

### Return Values

No value is returned.

### Examples

Example #1 SQLite3::open() example

`<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>`

# SQLite3::openBlob

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::openBlob — Opens a stream resource to read a BLOB

### Description

public SQLite3::openBlob(
string `$table`,
string `$column`,
int `$rowid`,
string `$database` = "main",
int `$flags` = `SQLITE3_OPEN_READONLY`
): resource|false

Opens a stream resource to read or write a BLOB, which would be selected by:

SELECT `column` FROM `database`.`table` WHERE rowid = `rowid`

> Note: It is not possible to change the size of a BLOB by writing to the stream. Instead, an UPDATE statement has to be executed, possibly using SQLite's zeroblob() function to set the desired BLOB size.

### Parameters

`table`

  The table name.

`column`

  The column name.

`rowid`

  The row ID.

`database`

  The symbolic name of the DB

`flags`

  Either `SQLITE3_OPEN_READONLY` or `SQLITE3_OPEN_READWRITE` to open the stream for reading only, or for reading and writing, respectively.

### Return Values

Returns a stream resource, or `false` on failure.

### Changelog

Version | Description
--- | ---
7.2.0 | The `flags` parameter has been added, allowing to write BLOBs; formerly only reading was supported.

### Examples

Example #1 SQLite3::openBlob() example

`<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES ('Lorem ipsum')");
$stream = $conn->openBlob('test', 'text', 1);
echo stream_get_contents($stream);
fclose($stream); // mandatory, otherwise the next line would fail
$conn->close();
?>`

The above example will output:

    Lorem ipsum

Example #2 Incrementally writing a BLOB

`<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES (zeroblob(36))");
$stream = $conn->openBlob('test', 'text', 1, 'main', SQLITE3_OPEN_READWRITE);
for ($i = 0; $i < 3; $i++) {
fwrite($stream, "Lorem ipsum\n");
}
fclose($stream);
echo $conn->querySingle("SELECT text FROM test");
$conn->close();
?>`

The above example will output:

    Lorem ipsum
    Lorem ipsum
    Lorem ipsum

# SQLite3::prepare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::prepare — Prepares an SQL statement for execution

### Description

public SQLite3::prepare(string `$query`): SQLite3Stmt|false

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

### Parameters

`query`

  The SQL query to prepare.

### Return Values

Returns an SQLite3Stmt object on success or `false` on failure.

### Examples

Example #1 SQLite3::prepare() example

`<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray());
?>`

### See Also

- SQLite3Stmt::paramCount() - Returns the number of parameters within the prepared statement
- SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
- SQLite3Stmt::bindParam() - Binds a parameter to a statement variable

# SQLite3::query

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::query — Executes an SQL query

### Description

public SQLite3::query(string `$query`): SQLite3Result|false

Executes an SQL query, returning an SQLite3Result object. If the query does not yield a result (such as DML statements) the returned SQLite3Result object is not really usable. Use SQLite3::exec() for such queries instead.

### Parameters

`query`

  The SQL query to execute.

### Return Values

Returns an SQLite3Result object, or `false` on failure.

### Examples

Example #1 SQLite3::query() example

`<?php
$db = new SQLite3('mysqlitedb.db');
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>`

# SQLite3::querySingle

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::querySingle — Executes a query and returns a single result

### Description

public SQLite3::querySingle(string `$query`, bool `$entireRow` = `false`): mixed

Executes a query and returns a single result.

### Parameters

`query`

  The SQL query to execute.

`entireRow`

  By default, querySingle() returns the value of the first column returned by the query. If `entireRow` is `true`, then it returns an array of the entire first row.

### Return Values

Returns the value of the first column of results or an array of the entire first row (if `entireRow` is `true`).

If the query is valid but no results are returned, then `null` will be returned if `entireRow` is `false`, otherwise an empty array is returned.

Invalid or failing queries will return `false`.

### Examples

Example #1 SQLite3::querySingle() example

`<?php
$db = new SQLite3('mysqlitedb.db');
var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>`

The above example will output something similar to:

    string(5) "Scott"
    Array
    (
        [username] => Scott
        [email] => scott@example.com
    )

# SQLite3::setAuthorizer

(PHP 8)

SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do

### Description

public SQLite3::setAuthorizer(?callable `$callback`): bool

Sets a callback that will be called by SQLite every time an action is performed (reading, deleting, updating, etc.). This is used when preparing a SQL statement from an untrusted source to ensure that the SQL statements do not try to access data they are not allowed to see, or that they do not try to execute malicious statements that damage the database. For example, an application may allow a user to enter arbitrary SQL queries for evaluation by a database. But the application does not want the user to be able to make arbitrary changes to the database. An authorizer could then be put in place while the user-entered SQL is being prepared that disallows everything except SELECT statements.

The authorizer callback may be called multiple times for each statement prepared by SQLite. A `SELECT` or `UPDATE` query will call the authorizer for every column that would be read or updated.

The authorizer is called with up to five parameters. The first parameter is always given, and is an int (action code) matching a constant from `SQLite3`. The other parameters are only passed for some actions. The following table describes the second and third parameters according to the action:

List of action codes and parameters
Action | Second parameter | Third parameter
--- | --- | ---
`SQLite3::CREATE_INDEX` | Index Name | Table Name
`SQLite3::CREATE_TABLE` | Table Name | `null`
`SQLite3::CREATE_TEMP_INDEX` | Index Name | Table Name
`SQLite3::CREATE_TEMP_TABLE` | Table Name | `null`
`SQLite3::CREATE_TEMP_TRIGGER` | Trigger Name | Table Name
`SQLite3::CREATE_TEMP_VIEW` | View Name | `null`
`SQLite3::CREATE_TRIGGER` | Trigger Name | Table Name
`SQLite3::CREATE_VIEW` | View Name | `null`
`SQLite3::DELETE` | Table Name | `null`
`SQLite3::DROP_INDEX` | Index Name | Table Name
`SQLite3::DROP_TABLE` | Table Name | `null`
`SQLite3::DROP_TEMP_INDEX` | Index Name | Table Name
`SQLite3::DROP_TEMP_TABLE` | Table Name | `null`
`SQLite3::DROP_TEMP_TRIGGER` | Trigger Name | Table Name
`SQLite3::DROP_TEMP_VIEW` | View Name | `null`
`SQLite3::DROP_TRIGGER` | Trigger Name | Table Name
`SQLite3::DROP_VIEW` | View Name | `null`
`SQLite3::INSERT` | Table Name | `null`
`SQLite3::PRAGMA` | Pragma Name | First argument passed to the pragma, or `null`
`SQLite3::READ` | Table Name | Column Name
`SQLite3::SELECT` | `null` | `null`
`SQLite3::TRANSACTION` | Operation | `null`
`SQLite3::UPDATE` | Table Name | Column Name
`SQLite3::ATTACH` | Filename | `null`
`SQLite3::DETACH` | Database Name | `null`
`SQLite3::ALTER_TABLE` | Database Name | Table Name
`SQLite3::REINDEX` | Index Name | `null`
`SQLite3::ANALYZE` | Table Name | `null`
`SQLite3::CREATE_VTABLE` | Table Name | Module Name
`SQLite3::DROP_VTABLE` | Table Name | Module Name
`SQLite3::FUNCTION` | `null` | Function Name
`SQLite3::SAVEPOINT` | Operation | Savepoint Name
`SQLite3::RECURSIVE` | `null` | `null`

The 4th parameter will be the name of the database (`"main"`, `"temp"`, etc.) if applicable.

The 5th parameter to the authorizer callback is the name of the inner-most trigger or view that is responsible for the access attempt or `null` if this access attempt is directly from top-level SQL code.

When the callback returns `SQLite3::OK`, that means the operation requested is accepted. When the callback returns `SQLite3::DENY`, the call that triggered the authorizer will fail with an error message explaining that access is denied.

If the action code is `SQLite3::READ` and the callback returns `SQLite3::IGNORE` then the prepared statement is constructed to substitute a `null` value in place of the table column that would have been read if `SQLite3::OK` had been returned. The `SQLite3::IGNORE` return can be used to deny an untrusted user access to individual columns of a table.

When a table is referenced by a `SELECT` but no column values are extracted from that table (for example in a query like `"SELECT count(*) FROM table"`) then the `SQLite3::READ` authorizer callback is invoked once for that table with a column name that is an empty string.

If the action code is `SQLite3::DELETE` and the callback returns `SQLite3::IGNORE` then the DELETE operation proceeds but the truncate optimization is disabled and all rows are deleted individually.

Only a single authorizer can be in place on a database connection at a time. Each call to SQLite3::setAuthorizer() overrides the previous call. Disable the authorizer by installing a `null` callback. The authorizer is disabled by default.

The authorizer callback must not do anything that will modify the database connection that invoked the authorizer callback.

Note that the authorizer is only called when a statement is prepared, not when it's executed.

More details can be found in the » SQLite3 documentation.

### Parameters

`callback`

  The callable to be called.

  If `null` is passed instead, this will disable the current authorizer callback.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

This method doesn't throw any error, but if an authorizer is enabled and returns an invalid value, the statement preparation will throw an error (or exception, depending on the use of the SQLite3::enableExceptions() method).

### Examples

Example #1 SQLite3::setAuthorizer() example

This only allows access to reading, and only some columns of the `users` table will be returned. Other columns will be replaced with `null`.

`<?php
$db = new SQLite3('data.sqlite');
$db->exec('CREATE TABLE users (id, name, password);');
$db->exec('INSERT INTO users VALUES (1, \'Pauline\', \'Snails4eva\');');
$allowed_columns = ['id', 'name'];
$db->setAuthorizer(function (int $action, ...$args) use ($allowed_columns) {
if ($action === SQLite3::READ) {
list($table, $column) = $args;
if ($table === 'users' && in_array($column, $allowed_columns)) {
return SQLite3::OK;
}
return SQLite3::IGNORE;
}
return SQLite3::DENY;
});
print_r($db->querySingle('SELECT * FROM users WHERE id = 1;'));`

The above example will output:

    Array
    (
        [id] => 1
        [name] => Pauline
        [password] =>
    )

# SQLite3::version

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

### Description

public static SQLite3::version(): array

Returns the SQLite3 library version as a string constant and as a number.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the keys "versionString" and "versionNumber".

### Examples

Example #1 SQLite3::version() example

`<?php
print_r(SQLite3::version());
?>`

The above example will output something similar to:

    Array
    (
        [versionString] => 3.5.9
        [versionNumber] => 3005009
    )

## Table of Contents

- SQLite3::backup — Backup one database to another database
- SQLite3::busyTimeout — Sets the busy connection handler
- SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
- SQLite3::close — Closes the database connection
- SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
- SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
- SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
- SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
- SQLite3::enableExceptions — Enable throwing exceptions
- SQLite3::escapeString — Returns a string that has been properly escaped
- SQLite3::exec — Executes a result-less query against a given database
- SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
- SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
- SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
- SQLite3::loadExtension — Attempts to load an SQLite extension library
- SQLite3::open — Opens an SQLite database
- SQLite3::openBlob — Opens a stream resource to read a BLOB
- SQLite3::prepare — Prepares an SQL statement for execution
- SQLite3::query — Executes an SQL query
- SQLite3::querySingle — Executes a query and returns a single result
- SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do
- SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

# The SQLite3Exception class

(PHP 8 >= 8.3.0)

## Introduction

Represents a SQLite3 specific exception.

## Class synopsis

class SQLite3Exception extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The SQLite3Stmt class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

A class that handles prepared statements for the SQLite 3 extension.

## Class synopsis

class SQLite3Stmt {
/* Methods */
private __construct(SQLite3 `$sqlite3`, string `$query`)
public bindParam(string|int `$param`, mixed `&$var`, int `$type` = `SQLITE3_TEXT`): bool
public bindValue(string|int `$param`, mixed `$value`, int `$type` = `SQLITE3_TEXT`): bool
public clear(): bool
public close(): true
public execute(): SQLite3Result|false
public getSQL(bool `$expand` = `false`): string|false
public paramCount(): int
public readOnly(): bool
public reset(): bool
}

# SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

### Description

public SQLite3Stmt::bindParam(string|int `$param`, mixed `&$var`, int `$type` = `SQLITE3_TEXT`): bool

Binds a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, SQLite3Stmt::reset() must be called after the first call to SQLite3Stmt::execute() if the bound value should be properly updated on following calls to SQLite3Stmt::execute(). If SQLite3Stmt::reset() is not called, the bound value will not change, even if the value assigned to the variable passed to SQLite3Stmt::bindParam() has changed, or SQLite3Stmt::bindParam() has been called again.

### Parameters

`param`

  Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (`:`) or an at sign (`@`), a colon (`:`) is automatically preprended. Positional parameters start with `1`.

`var`

  The parameter to bind to a statement variable.

`type`

  The data type of the parameter to bind.

  - `SQLITE3_INTEGER`: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  - `SQLITE3_FLOAT`: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  - `SQLITE3_TEXT`: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  - `SQLITE3_BLOB`: The value is a blob of data, stored exactly as it was input.

  - `SQLITE3_NULL`: The value is a NULL value.

  As of PHP 7.0.7, if `type` is omitted, it is automatically detected from the type of the `var`: bool and int are treated as `SQLITE3_INTEGER`, float as `SQLITE3_FLOAT`, null as `SQLITE3_NULL` and all others as `SQLITE3_TEXT`. Formerly, if `type` has been omitted, it has defaulted to `SQLITE3_TEXT`.

  > Note:

  > If `var` is `null`, it is always treated as `SQLITE3_NULL`, regardless of the given `type`.

### Return Values

Returns `true` if the parameter is bound to the statement variable, `false` on failure.

### Changelog

Version | Description
--- | ---
7.4.0 | `param` now also supports the `@param` notation.

### Examples

Example #1 SQLite3Stmt::bindParam() Usage

This example shows how a single prepared statement with a single parameter binding can be used to insert multiple rows with different values.

`<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE foo (bar TEXT)");
$stmt = $db->prepare("INSERT INTO foo VALUES (:bar)");
$stmt->bindParam(':bar', $bar, SQLITE3_TEXT);
$bar = 'baz';
$stmt->execute();
$bar = 42;
$stmt->execute();
$res = $db->query("SELECT * FROM foo");
while (($row = $res->fetchArray(SQLITE3_ASSOC))) {
var_dump($row);
}
?>`

The above example will output:

    array(1) {
      ["bar"]=>
      string(3) "baz"
    }
    array(1) {
      ["bar"]=>
      string(2) "42"
    }

### See Also

- SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
- SQLite3::prepare() - Prepares an SQL statement for execution

# SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

### Description

public SQLite3Stmt::bindValue(string|int `$param`, mixed `$value`, int `$type` = `SQLITE3_TEXT`): bool

Binds the value of a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, once the statement has been executed, SQLite3Stmt::reset() needs to be called to be able to change the value of bound parameters.

### Parameters

`param`

  Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (`:`) or an at sign (`@`), a colon (`:`) is automatically preprended. Positional parameters start with `1`.

`value`

  The value to bind to a statement variable.

`type`

  The data type of the value to bind.

  - `SQLITE3_INTEGER`: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  - `SQLITE3_FLOAT`: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  - `SQLITE3_TEXT`: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  - `SQLITE3_BLOB`: The value is a blob of data, stored exactly as it was input.

  - `SQLITE3_NULL`: The value is a NULL value.

  As of PHP 7.0.7, if `type` is omitted, it is automatically detected from the type of the `value`: bool and int are treated as `SQLITE3_INTEGER`, float as `SQLITE3_FLOAT`, null as `SQLITE3_NULL` and all others as `SQLITE3_TEXT`. Formerly, if `type` has been omitted, it has defaulted to `SQLITE3_TEXT`.

  > Note:

  > If `value` is `null`, it is always treated as `SQLITE3_NULL`, regardless of the given `type`.

### Return Values

Returns `true` if the value is bound to the statement variable, or `false` on failure.

### Changelog

Version | Description
--- | ---
7.4.0 | `param` now also supports the `@param` notation.

### Examples

Example #1 SQLite3Stmt::bindValue() example

`<?php
$db = new SQLite3(':memory:');
$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray(SQLITE3_ASSOC));
?>`

The above example will output:

    array(1) {
      ["bar"]=>
      string(14) "This is a test"
    }

### See Also

- SQLite3Stmt::bindParam() - Binds a parameter to a statement variable
- SQLite3::prepare() - Prepares an SQL statement for execution

# SQLite3Stmt::clear

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::clear — Clears all current bound parameters

### Description

public SQLite3Stmt::clear(): bool

Clears all current bound parameters (sets them to `null`).

Caution

This method needs to be used with SQLite3Stmt::reset(). If used alone, any call to SQLite3Stmt::bindValue() or SQLite3Stmt::bindParam() will be of no effect and all bound parameters will have the `null` value.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on successful clearing of bound parameters, `false` on failure.

# SQLite3Stmt::close

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::close — Closes the prepared statement

### Description

public SQLite3Stmt::close(): true

Closes the prepared statement.

> Note: Note that all SQLite3Results that have been retrieved by executing this statement will be invalidated when the statement is closed.

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Errors/Exceptions

An Error is thrown if the method is called on an uninitialized object.

### Changelog

Version | Description
--- | ---
8.1.0 | This method now throws an Error exception if the object is not correct initialized. Previously, it returned `false`.

# SQLite3Stmt::__construct

(No version information available, might only be in Git)

SQLite3Stmt::__construct — Constructs an SQLite3Stmt object

### Description

private SQLite3Stmt::__construct(SQLite3 `$sqlite3`, string `$query`)

SQLite3Stmt instances are created by SQLite3::prepare().

### Parameters

`sqlite3`

`query`

# SQLite3Stmt::execute

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

### Description

public SQLite3Stmt::execute(): SQLite3Result|false

Executes a prepared statement and returns a result set object.

Caution

Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.

### Parameters

This function has no parameters.

### Return Values

Returns an SQLite3Result object on successful execution of the prepared statement, `false` on failure.

### See Also

- SQLite3::prepare() - Prepares an SQL statement for execution
- SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
- SQLite3Stmt::bindParam() - Binds a parameter to a statement variable

# SQLite3Stmt::getSQL

(PHP 7 >= 7.4.0, PHP 8)

SQLite3Stmt::getSQL — Get the SQL of the statement

### Description

public SQLite3Stmt::getSQL(bool `$expand` = `false`): string|false

Retrieves the SQL of the prepared statement. If `expand` is `false`, the unmodified SQL is retrieved. If `expand` is `true`, all query parameters are replaced with their bound values, or with an SQL `NULL`, if not already bound.

### Parameters

`expand`

  Whether to retrieve the expanded SQL. Passing `true` is only supported as of libsqlite 3.14.

### Return Values

Returns the SQL of the prepared statement, or `false` on failure.

### Errors/Exceptions

If `expand` is `true`, but the libsqlite version is less than 3.14, an error of level `E_WARNING` or an Exception is issued, according to SQLite3::enableExceptions().

### Examples

Example #1 Inspecting the expanded SQL

`<?php
$db = new SQLite3(':memory:');
$stmt = $db->prepare("SELECT :a, ?, :c");
$stmt->bindValue(':a', 'foo');
$answer = 42;
$stmt->bindParam(2, $answer);
var_dump($stmt->getSQL(true));
?>`

The above example will output something similar to:

    string(24) "SELECT 'foo', '42', NULL"

# SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

### Description

public SQLite3Stmt::paramCount(): int

Returns the number of parameters within the prepared statement.

### Parameters

This function has no parameters.

### Return Values

Returns the number of parameters within the prepared statement.

### See Also

- SQLite3::prepare() - Prepares an SQL statement for execution

# SQLite3Stmt::readOnly

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

SQLite3Stmt::readOnly — Returns whether a statement is definitely read only

### Description

public SQLite3Stmt::readOnly(): bool

Returns whether a statement is definitely read only. A statement is considered read only, if it makes no direct changes to the content of the database file. Note that user defined SQL functions might change the database indirectly as a side effect.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if a statement is definitely read only, `false` otherwise.

# SQLite3Stmt::reset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::reset — Resets the prepared statement

### Description

public SQLite3Stmt::reset(): bool

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the statement is successfully reset, or `false` on failure.

## Table of Contents

- SQLite3Stmt::bindParam — Binds a parameter to a statement variable
- SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
- SQLite3Stmt::clear — Clears all current bound parameters
- SQLite3Stmt::close — Closes the prepared statement
- SQLite3Stmt::__construct — Constructs an SQLite3Stmt object
- SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
- SQLite3Stmt::getSQL — Get the SQL of the statement
- SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
- SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
- SQLite3Stmt::reset — Resets the prepared statement

# The SQLite3Result class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

A class that handles result sets for the SQLite 3 extension.

## Class synopsis

class SQLite3Result {
/* Methods */
private __construct()
public columnName(int `$column`): string|false
public columnType(int `$column`): int|false
public fetchArray(int `$mode` = `SQLITE3_BOTH`): array|false
public finalize(): true
public numColumns(): int
public reset(): bool
}

# SQLite3Result::columnName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::columnName — Returns the name of the nth column

### Description

public SQLite3Result::columnName(int `$column`): string|false

Returns the name of the column specified by the `column`. Note that the name of a result column is the value of the `AS` clause for that column, if there is an `AS` clause. If there is no `AS` clause then the name of the column is unspecified and may change from one release of libsqlite3 to the next.

### Parameters

`column`

  The numeric zero-based index of the column.

### Return Values

Returns the string name of the column identified by `column`, or `false` if the column does not exist.

# SQLite3Result::columnType

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::columnType — Returns the type of the nth column

### Description

public SQLite3Result::columnType(int `$column`): int|false

Returns the type of the column identified by `column`.

### Parameters

`column`

  The numeric zero-based index of the column.

### Return Values

Returns the data type index of the column identified by `column` (one of `SQLITE3_INTEGER`, `SQLITE3_FLOAT`, `SQLITE3_TEXT`, `SQLITE3_BLOB`, or `SQLITE3_NULL`), or `false` if the column does not exist.

# SQLite3Result::__construct

(No version information available, might only be in Git)

SQLite3Result::__construct — Constructs an SQLite3Result

### Description

private SQLite3Result::__construct()

SQLite3Result instances are created by SQLite3::query() and SQLite3Stmt::execute().

### Parameters

This function has no parameters.

# SQLite3Result::fetchArray

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

### Description

public SQLite3Result::fetchArray(int `$mode` = `SQLITE3_BOTH`): array|false

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

### Parameters

`mode`

  Controls how the next row will be returned to the caller. This value must be one of either `SQLITE3_ASSOC`, `SQLITE3_NUM`, or `SQLITE3_BOTH`.

  - `SQLITE3_ASSOC`: returns an array indexed by column name as returned in the corresponding result set

  - `SQLITE3_NUM`: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  - `SQLITE3_BOTH`: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

### Return Values

Returns a result row as an associatively or numerically indexed array or both. Alternately will return `false` if there are no more rows.

The types of the values of the returned array are mapped from SQLite3 types as follows: integers are mapped to int if they fit into the range `PHP_INT_MIN`..`PHP_INT_MAX`, and to string otherwise. Floats are mapped to float, `NULL` values are mapped to null, and strings and blobs are mapped to string.

# SQLite3Result::finalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::finalize — Closes the result set

### Description

public SQLite3Result::finalize(): true

Closes the result set.

### Parameters

This function has no parameters.

### Return Values

Always returns `true`.

### Errors/Exceptions

An Error is thrown if the method is called on an uninitialized object.

### Changelog

Version | Description
--- | ---
8.1.0 | This method now throws an Error exception if the object is not correct initialized. Previously, it returned `false`.

# SQLite3Result::numColumns

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::numColumns — Returns the number of columns in the result set

### Description

public SQLite3Result::numColumns(): int

Returns the number of columns in the result set.

### Parameters

This function has no parameters.

### Return Values

Returns the number of columns in the result set.

# SQLite3Result::reset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::reset — Resets the result set back to the first row

### Description

public SQLite3Result::reset(): bool

Resets the result set back to the first row.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the result set is successfully reset back to the first row, `false` on failure.

## Table of Contents

- SQLite3Result::columnName — Returns the name of the nth column
- SQLite3Result::columnType — Returns the type of the nth column
- SQLite3Result::__construct — Constructs an SQLite3Result
- SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
- SQLite3Result::finalize — Closes the result set
- SQLite3Result::numColumns — Returns the number of columns in the result set
- SQLite3Result::reset — Resets the result set back to the first row

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- SQLite3 — The SQLite3 class
  - SQLite3::backup — Backup one database to another database
  - SQLite3::busyTimeout — Sets the busy connection handler
  - SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
  - SQLite3::close — Closes the database connection
  - SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
  - SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
  - SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
  - SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  - SQLite3::enableExceptions — Enable throwing exceptions
  - SQLite3::escapeString — Returns a string that has been properly escaped
  - SQLite3::exec — Executes a result-less query against a given database
  - SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
  - SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
  - SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
  - SQLite3::loadExtension — Attempts to load an SQLite extension library
  - SQLite3::open — Opens an SQLite database
  - SQLite3::openBlob — Opens a stream resource to read a BLOB
  - SQLite3::prepare — Prepares an SQL statement for execution
  - SQLite3::query — Executes an SQL query
  - SQLite3::querySingle — Executes a query and returns a single result
  - SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do
  - SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
- SQLite3Exception — The SQLite3Exception class
- SQLite3Stmt — The SQLite3Stmt class
  - SQLite3Stmt::bindParam — Binds a parameter to a statement variable
  - SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
  - SQLite3Stmt::clear — Clears all current bound parameters
  - SQLite3Stmt::close — Closes the prepared statement
  - SQLite3Stmt::__construct — Constructs an SQLite3Stmt object
  - SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
  - SQLite3Stmt::getSQL — Get the SQL of the statement
  - SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
  - SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
  - SQLite3Stmt::reset — Resets the prepared statement
- SQLite3Result — The SQLite3Result class
  - SQLite3Result::columnName — Returns the name of the nth column
  - SQLite3Result::columnType — Returns the type of the nth column
  - SQLite3Result::__construct — Constructs an SQLite3Result
  - SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
  - SQLite3Result::finalize — Closes the result set
  - SQLite3Result::numColumns — Returns the number of columns in the result set
  - SQLite3Result::reset — Resets the result set back to the first row

# Microsoft SQL Server Driver for PHP

# Introduction

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

The SQLSRV extension can be used on the following operating systems:

- Windows Vista Service Pack 2 or later
- Windows Server 2008 Service Pack 2 or later
- Windows Server 2008 R2
- Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:

- » Download the x86 package
- » Download the x64 package

The SQLSRV download comes 8 driver files, four of which are for PDO support.

The most recent version of the driver is available for download here: » SQLSRV download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

## Installation

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with 8 driver files, four of which are for PDO support.

The most recent version of the driver is available for download here: » SQLSRV download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

Since version 4.0 the SQLSRV extension is compatible only with PHP 7.0 running on Linux or Windows.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.

SQLSRV Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
sqlsrv.WarningsReturnAsErrors | 1 (`true`) | `INI_ALL` | Available since SQLSRV 1.0
sqlsrv.LogSubsystems | 0 | `INI_ALL` | Available since SQLSRV 1.0
sqlsrv.LogSeverity | 1 | `INI_ALL` | Available since SQLSRV 1.0

## Resource Types

## Connection resource

A connection resource returned by sqlsrv_connect().

## Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().

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

`SQLSRV_FETCH_ASSOC` (int)
  Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
`SQLSRV_FETCH_NUMERIC` (int)
  Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
`SQLSRV_FETCH_BOTH` (int)
  Forces sqlsrv_fetch_array() to return an array with both associative and numeric keys when passed as a parameter (the default behavior).
`SQLSRV_ERR_ALL` (int)
  Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
`SQLSRV_ERR_ERRORS` (int)
  Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
`SQLSRV_ERR_WARNINGS` (int)
  Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
`SQLSRV_LOG_SYSTEM_ALL` (int)
  Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SYSTEM_CONN` (int)
  Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SYSTEM_INIT` (int)
  Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SYSTEM_OFF` (int)
  Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SYSTEM_STMT` (int)
  Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SYSTEM_UTIL` (int)
  Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SEVERITY_ALL` (int)
  Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SEVERITY_ERROR` (int)
  Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SEVERITY_NOTICE` (int)
  Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
`SQLSRV_LOG_SEVERITY_WARNING` (int)
  Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
`SQLSRV_NULLABLE_YES` (int)
  Indicates that a column is nullable.
`SQLSRV_NULLABLE_NO` (int)
  Indicates that a column is not nullable.
`SQLSRV_NULLABLE_UNKNOWN` (int)
  Indicates that it is not known if a column is nullable.
`SQLSRV_PARAM_IN` (int)
  Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
`SQLSRV_PARAM_INOUT` (int)
  Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
`SQLSRV_PARAM_OUT` (int)
  Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
`SQLSRV_PHPTYPE_INT` (int)
  Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
`SQLSRV_PHPTYPE_DATETIME` (int)
  Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
`SQLSRV_PHPTYPE_FLOAT` (int)
  Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
`SQLSRV_PHPTYPE_STREAM` (int)
  Specifies a PHP stream. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
`SQLSRV_PHPTYPE_STRING` (int)
  Specifies a string PHP data type. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
`SQLSRV_ENC_BINARY` (int)
  Specifies that data is returned as a raw byte stream from the server without performing encoding or translation. For usage information, see » How to: Specify PHP Types.
`SQLSRV_ENC_CHAR` (int)
  Data is returned in 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This is the default encoding. For usage information, see » How to: Specify PHP Types.
`SQLSRV_SQLTYPE_BIGINT` (int)
  Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_BINARY` (int)
  Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_BIT` (int)
  Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_CHAR` (int)
  Describes the char SQL Server data type. This constant works like a function and accepts a parameter indicating the number characters. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_DATE` (int)
  Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_DATETIME` (int)
  Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_DATETIME2` (int)
  Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_DATETIMEOFFSET` (int)
  Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_DECIMAL` (int)
  Describes the decimal SQL Server data type. This constant works like a function and accepts two parameters indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_FLOAT` (int)
  Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_IMAGE` (int)
  Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_INT` (int)
  Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_MONEY` (int)
  Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_NCHAR` (int)
  Describes the nchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_NUMERIC` (int)
  Describes the numeric SQL Server data type. This constant works like a function and accepts two parameter indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_NVARCHAR` (int)
  Describes the nvarchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_NVARCHAR`('max') (int)
  Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_NTEXT` (int)
  Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_REAL` (int)
  Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_SMALLDATETIME` (int)
  Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_SMALLINT` (int)
  Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_SMALLMONEY` (int)
  Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_TEXT` (int)
  Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_TIME` (int)
  Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_TIMESTAMP` (int)
  Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_TINYINT` (int)
  Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_UNIQUEIDENTIFIER` (int)
  Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_UDT` (int)
  Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_VARBINARY` (int)
  Describes the varbinary SQL Server data type. This constant works like a function and accepts a single parameter indicating the byte count. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_VARBINARY`('max') (int)
  Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_VARCHAR` (int)
  Describes the varchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_VARCHAR`('max') (int)
  Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_SQLTYPE_XML` (int)
  Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
`SQLSRV_TXN_READ_UNCOMMITTED` (int)
  Indicates a transaction isolation level of READ UNCOMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
`SQLSRV_TXN_READ_COMMITTED` (int)
  Indicates a transaction isolation level of READ COMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
`SQLSRV_TXN_REPEATABLE_READ` (int)
  Indicates a transaction isolation level of REPEATABLE READ. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
`SQLSRV_TXN_SNAPSHOT` (int)
  Indicates a transaction isolation level of SNAPSHOT. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
`SQLSRV_TXN_READ_SERIALIZABLE` (int)
  Indicates a transaction isolation level of SERIALIZABLE. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
`SQLSRV_CURSOR_FORWARD` (int)
  Indicates a forward-only cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_CURSOR_STATIC` (int)
  Indicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_CURSOR_DYNAMIC` (int)
  Indicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_CURSOR_KEYSET` (int)
  Indicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_CURSOR_BUFFERED` (int)
  Creates a client-side cursor query. Lets you access rows in any order. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_NEXT` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_PRIOR` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_FIRST` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_LAST` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_ABSOLUTE` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
`SQLSRV_SCROLL_RELATIVE` (int)
  Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.

# SQLSRV Functions

# sqlsrv_begin_transaction

(No version information available, might only be in Git)

sqlsrv_begin_transaction — Begins a database transaction

### Description

sqlsrv_begin_transaction(resource `$conn`): bool

The transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

### Parameters

`conn`
  The connection resource returned by a call to sqlsrv_connect().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_begin_transaction() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>`

The above example will output something similar to:

### See Also

- sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction
- sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

# sqlsrv_cancel

(No version information available, might only be in Git)

sqlsrv_cancel — Cancels a statement

### Description

sqlsrv_cancel(resource `$stmt`): bool

Cancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.

### Parameters

`stmt`
  The statement resource to be cancelled.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_cancel() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sales FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_execute( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$salesTotal = 0;
$count = 0;
while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
$qty = $row[0];
$price = $row[1];
$salesTotal += ( $price * $qty);
$count++;
}
echo "$count sales accounted for the first $$salesTotal in revenue.<br />";
// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>`

### Notes

The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

### See Also

- sqlsrv_free_stmt() - Frees all resources for the specified statement
- sqlsrv_prepare() - Prepares a query for execution

# sqlsrv_client_info

(No version information available, might only be in Git)

sqlsrv_client_info — Returns information about the client and specified connection

### Description

sqlsrv_client_info(resource `$conn`): array

Returns information about the client and specified connection

### Parameters

`conn`
  The connection about which information is returned.

### Return Values

Returns an associative array with keys described in the table below. Returns `false` otherwise.

Array returned by sqlsrv_client_info
Key | Description
--- | ---
DriverDllName | SQLNCLI10.DLL
DriverODBCVer | ODBC version (xx.yy)
DriverVer | SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer | php_sqlsrv.dll version (2.0.xxx.x)

### Examples

Example #1 sqlsrv_client_info() example

`<?php
$serverName = "serverName\sqlexpress";
$connOptions = array("UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
echo "Error in retrieving client info.<br />";
}
?>`

### See Also

- sqlsrv_server_info() - Returns information about the server

# sqlsrv_close

(No version information available, might only be in Git)

sqlsrv_close — Closes an open connection and releases resourses associated with the connection

### Description

sqlsrv_close(resource `$conn`): bool

Closes an open connection and releases resourses associated with the connection.

### Parameters

`conn`
  The connection to be closed.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_close() example

`<?php
$serverName = "serverName\sqlexpres";
$connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
//-------------------------------------
// Perform database operations here.
//-------------------------------------
// Close the connection.
sqlsrv_close( $conn );
?>`

### See Also

- sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database

# sqlsrv_commit

(No version information available, might only be in Git)

sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()

### Description

sqlsrv_commit(resource `$conn`): bool

Commits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

### Parameters

`conn`
  The connection on which the transaction is to be committed.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_commit() example

The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>`

### See Also

- sqlsrv_begin_transaction() - Begins a database transaction
- sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

# sqlsrv_configure

(No version information available, might only be in Git)

sqlsrv_configure — Changes the driver error handling and logging configurations

### Description

sqlsrv_configure(string `$setting`, mixed `$value`): bool

Changes the driver error handling and logging configurations.

### Parameters

`setting`
  The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".
`value`

  The value of the specified setting. The following table shows possible values:

  Error and Logging Setting Options
  Setting | Options
  --- | ---
  WarningsReturnAsErrors | 1 (`true`) or 0 (`false`)
  LogSubsystems | SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8)
  LogSeverity | SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2)

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- » SQLSRV Error Handling.
- » Logging SQLSRV Activity.

# sqlsrv_connect

(No version information available, might only be in Git)

sqlsrv_connect — Opens a connection to a Microsoft SQL Server database

### Description

sqlsrv_connect(string `$serverName`, array `$connectionInfo` = ?): resource

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.

### Parameters

`serverName`
  The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward slash and the instance name (e.g. serverName\sqlexpress).
`connectionInfo`
  An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

### Return Values

A connection resource. If a connection cannot be successfully opened, `false` is returned.

### Examples

Example #1 Connect using Windows Authentication.

`<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>`

Example #2 Connect by specifying a user name and password.

`<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>`

Example #3 Connect on a specified port.

`<?php
$serverName = "serverName\\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>`

### Notes

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or `false`). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).

### See Also

- sqlsrv_close() - Closes an open connection and releases resourses associated with the connection
- sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
- sqlsrv_query() - Prepares and executes a query

# sqlsrv_errors

(No version information available, might only be in Git)

sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed

### Description

sqlsrv_errors(int `$errorsOrWarnings` = ?): mixed

Returns error and warning information about the last SQLSRV operation performed.

### Parameters

`errorsOrWarnings`
  Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.

### Return Values

If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred on the last sqlsrv operation, `null` is returned. The following table describes the structure of the returned arrays:

Array returned by sqlsrv_errors
Key | Description
--- | ---
SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP.
code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code.
message | A description of the error.

### Examples

Example #1 functionname() example

`<?php
$serverName = "serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";
/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
?>`

### Notes

By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns `false`. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see sqlsrv_configure() and the WarningsReturnAsErrors setting.

### See Also

- sqlsrv_configure() - Changes the driver error handling and logging configurations

# sqlsrv_execute

(No version information available, might only be in Git)

sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()

### Description

sqlsrv_execute(resource `$stmt`): bool

Executes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.

### Parameters

`stmt`
  A statement resource returned by sqlsrv_prepare().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_execute() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>`

### Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

### See Also

- sqlsrv_prepare() - Prepares a query for execution
- sqlsrv_query() - Prepares and executes a query

# sqlsrv_fetch

(No version information available, might only be in Git)

sqlsrv_fetch — Makes the next row in a result set available for reading

### Description

sqlsrv_fetch(resource `$stmt`, int `$row` = ?, int `$offset` = ?): mixed

Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.

### Parameters

`stmt`
  A statement resource created by executing sqlsrv_query() or sqlsrv_execute().
`row`

  The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  - SQLSRV_SCROLL_NEXT
  - SQLSRV_SCROLL_PRIOR
  - SQLSRV_SCROLL_FIRST
  - SQLSRV_SCROLL_LAST
  - SQLSRV_SCROLL_ABSOLUTE
  - SQLSRV_SCROLL_RELATIVE
`offset`
  Specifies the row to be accessed if the row parameter is set to `SQLSRV_SCROLL_ABSOLUTE` or `SQLSRV_SCROLL_RELATIVE`. Note that the first row in a result set has index 0.

### Return Values

Returns `true` if the next row of a result set was successfully retrieved, `false` if an error occurs, and `null` if there are no more rows in the result set.

### Examples

Example #1 sqlsrv_fetch() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>`

### See Also

- sqlsrv_get_field() - Gets field data from the currently selected row
- sqlsrv_fetch_array() - Returns a row as an array
- sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

# sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_array — Returns a row as an array

### Description

sqlsrv_fetch_array(
resource `$stmt`,
int `$fetchType` = ?,
int `$row` = ?,
int `$offset` = ?
): array

Returns the next available row of data as an associative array, a numeric array, or both (the default).

### Parameters

`stmt`
  A statement resource returned by sqlsrv_query or sqlsrv_prepare.
`fetchType`
  A predefined constant specifying the type of array to return. Possible values are `SQLSRV_FETCH_ASSOC`, `SQLSRV_FETCH_NUMERIC`, and `SQLSRV_FETCH_BOTH` (the default). A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.
`row`
  Specifies the row to access in a result set that uses a scrollable cursor. Possible values are `SQLSRV_SCROLL_NEXT`, `SQLSRV_SCROLL_PRIOR`, `SQLSRV_SCROLL_FIRST`, `SQLSRV_SCROLL_LAST`, `SQLSRV_SCROLL_ABSOLUTE` and, `SQLSRV_SCROLL_RELATIVE` (the default). When this parameter is specified, the `fetchType` must be explicitly defined.
`offset`
  Specifies the row to be accessed if the row parameter is set to `SQLSRV_SCROLL_ABSOLUTE` or `SQLSRV_SCROLL_RELATIVE`. Note that the first row in a result set has index 0.

### Return Values

Returns an array on success, `null` if there are no more rows to return, and `false` if an error occurs.

### Examples

Example #1 Retrieving an associative array.

`<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>`

Example #2 Retrieving a numeric array.

`<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
sqlsrv_free_stmt( $stmt);
?>`

### Notes

Not specifying the `fetchType` or explicitly using the `SQLSRV_FETCH_TYPE` constant in the examples above will return an array that has both associative and numeric keys.

If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.

If a column with no name is returned, the associative key for the array element will be an empty string ("").

### See Also

- sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database
- sqlsrv_query() - Prepares and executes a query
- sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
- sqlsrv_fetch() - Makes the next row in a result set available for reading

# sqlsrv_fetch_object

(No version information available, might only be in Git)

sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object

### Description

sqlsrv_fetch_object(
resource `$stmt`,
string `$className` = ?,
array `$ctorParams` = ?,
int `$row` = ?,
int `$offset` = ?
): mixed

Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.

### Parameters

`stmt`
  A statement resource created by sqlsrv_query() or sqlsrv_execute().
`className`
  The name of the class to instantiate. If no class name is specified, stdClass is instantiated.
`ctorParams`
  Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.
`row`

  The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  - SQLSRV_SCROLL_NEXT
  - SQLSRV_SCROLL_PRIOR
  - SQLSRV_SCROLL_FIRST
  - SQLSRV_SCROLL_LAST
  - SQLSRV_SCROLL_ABSOLUTE
  - SQLSRV_SCROLL_RELATIVE
`offset`
  Specifies the row to be accessed if the row parameter is set to `SQLSRV_SCROLL_ABSOLUTE` or `SQLSRV_SCROLL_RELATIVE`. Note that the first row in a result set has index 0.

### Return Values

Returns an object on success, `null` if there are no more rows to return, and `false` if an error occurs or if the specified class does not exist.

### Examples

Example #1 sqlsrv_fetch_object() example

The following example demonstrates how to retrieve a row as a stdClass object.

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
echo $obj->fName.", ".$obj->lName."<br />";
}
?>`

### Notes

If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:

- Field-property name matching is case-sensitive.
- Field-property matching occurs regardless of access modifiers.
- Class property data types are ignored when applying a field value to a property.
- If the class does not exist, the function returns `false` and adds an error to the error collection.

Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection.

When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().

### See Also

- sqlsrv_fetch() - Makes the next row in a result set available for reading
- sqlsrv_fetch_array() - Returns a row as an array

# sqlsrv_field_metadata

(No version information available, might only be in Git)

sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

### Description

sqlsrv_field_metadata(resource `$stmt`): mixed

Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.

### Parameters

`stmt`
  The statement resource for which metadata is returned.

### Return Values

Returns an array of arrays on success. Otherwise, `false` is returned. Each returned array is described by the following table:

Array returned by sqlsrv_field_metadata
Key | Description
--- | ---
Name | The name of the field.
Type | The numeric value for the SQL type.
Size | The number of characters for fields of character type, the number of bytes for fields of binary type, or `null` for other types.
Precision | The precision for types of variable precision, `null` for other types.
Scale | The scale for types of variable scale, `null` for other types.
Nullable | An enumeration indicating whether the column is nullable, not nullable, or if it is not known.

For more information, see » sqlsrv_field_metadata in the Microsoft SQLSRV documentation.

### Examples

Example #1 sqlsrv_field_metadata() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );
foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
foreach( $fieldMetadata as $name => $value) {
echo "$name: $value<br />";
}
echo "<br />";
}
?>`

### See Also

- sqlsrv_client_info() - Returns information about the client and specified connection

# sqlsrv_free_stmt

(No version information available, might only be in Git)

sqlsrv_free_stmt — Frees all resources for the specified statement

### Description

sqlsrv_free_stmt(resource `$stmt`): bool

Frees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.

### Parameters

`stmt`
  The statement for which resources are freed. Note that `null` is a valid parameter value. This allows the function to be called multiple times in a script.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_free_stmt() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
/*-------------------------------
Process query results here.
-------------------------------*/
/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);
?>`

### Notes

The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

### See Also

- sqlsrv_cancel() - Cancels a statement

# sqlsrv_get_config

(No version information available, might only be in Git)

sqlsrv_get_config — Returns the value of the specified configuration setting

### Description

sqlsrv_get_config(string `$setting`): mixed

Returns the value of the specified configuration setting.

### Parameters

`setting`
  The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

### Return Values

Returns the value of the specified setting. If an invalid setting is specified, `false` is returned.

### See Also

- sqlsrv_configure() - Changes the driver error handling and logging configurations

# sqlsrv_get_field

(No version information available, might only be in Git)

sqlsrv_get_field — Gets field data from the currently selected row

### Description

sqlsrv_get_field(resource `$stmt`, int `$fieldIndex`, int `$getAsType` = ?): mixed

Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.

### Parameters

`stmt`
  A statement resource returned by sqlsrv_query() or sqlsrv_execute().
`fieldIndex`
  The index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.
`getAsType`
  The PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.

### Return Values

Returns data from the specified field on success. Returns `false` otherwise.

### Examples

Example #1 sqlsrv_get_field() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>`

### See Also

- sqlsrv_fetch() - Makes the next row in a result set available for reading
- sqlsrv_fetch_array() - Returns a row as an array
- sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

# sqlsrv_has_rows

(No version information available, might only be in Git)

sqlsrv_has_rows — Indicates whether the specified statement has rows

### Description

sqlsrv_has_rows(resource `$stmt`): bool

Indicates whether the specified statement has rows.

### Parameters

`stmt`
  A statement resource returned by sqlsrv_query() or sqlsrv_execute().

### Return Values

Returns `true` if the specified statement has rows and `false` if the statement does not have rows or if an error occurred.

### Examples

Example #1 sqlsrv_has_rows() example

`<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
echo "There are rows. <br />";
else
echo "There are no rows. <br />";
}
?>`

### See Also

- sqlsrv_num_rows() - Retrieves the number of rows in a result set
- sqlsrv_query() - Prepares and executes a query

# sqlsrv_next_result

(No version information available, might only be in Git)

sqlsrv_next_result — Makes the next result of the specified statement active

### Description

sqlsrv_next_result(resource `$stmt`): mixed

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

### Parameters

`stmt`
  The statement on which the next result is being called.

### Return Values

Returns `true` if the next result was successfully retrieved, `false` if an error occurred, and `null` if there are no more results to retrieve.

### Examples

Example #1 sqlsrv_next_result() example

The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);
// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";
// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo $row['id'].": ".$row['data']."<br />";
}
} elseif( is_null($next_result)) {
echo "No more results.<br />";
} else {
die(print_r(sqlsrv_errors(), true));
}
?>`

### See Also

- sqlsrv_query() - Prepares and executes a query
- sqlsrv_fetch_array() - Returns a row as an array
- sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

# sqlsrv_num_fields

(No version information available, might only be in Git)

sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement

### Description

sqlsrv_num_fields(resource `$stmt`): mixed

Retrieves the number of fields (columns) on a statement.

### Parameters

`stmt`
  The statement for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.

### Return Values

Returns the number of fields on success. Returns `false` otherwise.

### Examples

Example #1 sqlsrv_num_fields() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true));
}
$numFields = sqlsrv_num_fields( $stmt );
while( sqlsrv_fetch( $stmt )) {
// Iterate through the fields of each row.
for($i = 0; $i < $numFields; $i++) {
echo sqlsrv_get_field($stmt, $i)." ";
}
echo "<br />";
}
?>`

### See Also

- sqlsrv_field_metadata() - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
- sqlsrv_fetch() - Makes the next row in a result set available for reading
- sqlsrv_get_field() - Gets field data from the currently selected row

# sqlsrv_num_rows

(No version information available, might only be in Git)

sqlsrv_num_rows — Retrieves the number of rows in a result set

### Description

sqlsrv_num_rows(resource `$stmt`): mixed

Retrieves the number of rows in a result set. This function requires that the statement resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

### Parameters

`stmt`
  The statement for which the row count is returned. The statement resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

### Return Values

Returns the number of rows retrieved on success and `false` if an error occurred. If a forward cursor (the default) or dynamic cursor is used, `false` is returned.

### Examples

Example #1 sqlsrv_num_rows() example

`<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );
$sql = "SELECT * FROM Table_1";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>`

### See Also

- sqlsrv_has_rows() - Indicates whether the specified statement has rows
- sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

# sqlsrv_prepare

(No version information available, might only be in Git)

sqlsrv_prepare — Prepares a query for execution

### Description

sqlsrv_prepare(
resource `$conn`,
string `$sql`,
array `$params` = ?,
array `$options` = ?
): mixed

Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.

### Parameters

`conn`
  A connection resource returned by sqlsrv_connect().
`sql`
  The string that defines the query to be prepared and executed.
`params`

  An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  - A literal value
  - A PHP variable
  - An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
  The following table describes the elements in the array structure above:

  Array structure
  Element | Description
  --- | ---
  $value | A literal value, a PHP variable, or a PHP by-reference variable.
  $direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
  $phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
  $sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.

`options`
  An array specifying query property options. The supported keys are described in the following table:

  Query Options
  Key | Values | Description
  --- | --- | ---
  QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
  SendStreamParamsAtExec | `true` or `false` (the default is `true`) | Configures the driver to send all stream data at execution (`true`), or to send stream data in chunks (`false`). By default, the value is set to `true`. For more information, see sqlsrv_send_stream_data().
  Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

### Return Values

Returns a statement resource on success and `false` if an error occurred.

### Examples

Example #1 sqlsrv_prepare() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>`

### Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

### See Also

- sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
- sqlsrv_query() - Prepares and executes a query

# sqlsrv_query

(No version information available, might only be in Git)

sqlsrv_query — Prepares and executes a query

### Description

sqlsrv_query(
resource `$conn`,
string `$sql`,
array `$params` = ?,
array `$options` = ?
): mixed

Prepares and executes a query.

### Parameters

`conn`
  A connection resource returned by sqlsrv_connect().
`sql`
  The string that defines the query to be prepared and executed.
`params`

  An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  - A literal value
  - A PHP variable
  - An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
  The following table describes the elements in the array structure above:

  Array structure
  Element | Description
  --- | ---
  $value | A literal value, a PHP variable, or a PHP by-reference variable.
  $direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
  $phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
  $sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.

`options`
  An array specifying query property options. The supported keys are described in the following table:

  Query Options
  Key | Values | Description
  --- | --- | ---
  QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
  SendStreamParamsAtExec | `true` or `false` (the default is `true`) | Configures the driver to send all stream data at execution (`true`), or to send stream data in chunks (`false`). By default, the value is set to `true`. For more information, see sqlsrv_send_stream_data().
  Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

### Return Values

Returns a statement resource on success and `false` if an error occurred.

### Examples

Example #1 sqlsrv_query() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>`

### Notes

For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().

### See Also

- sqlsrv_prepare() - Prepares a query for execution
- sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare

# sqlsrv_rollback

(No version information available, might only be in Git)

sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()

### Description

sqlsrv_rollback(resource `$conn`): bool

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

### Parameters

`conn`
  The connection resource returned by a call to sqlsrv_connect().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 sqlsrv_rollback() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>`

### See Also

- sqlsrv_begin_transaction() - Begins a database transaction
- sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction

# sqlsrv_rows_affected

(No version information available, might only be in Git)

sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

### Description

sqlsrv_rows_affected(resource `$stmt`): int|false

Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().

### Parameters

`stmt`
  The executed statement resource for which the number of affected rows is returned.

### Return Values

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query. If no rows were affected, 0 is returned. If the number of affected rows cannot be determined, -1 is returned. If an error occurred, `false` is returned.

### Examples

Example #1 sqlsrv_rows_affected() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";
$params = array("updated data", 1);
$stmt = sqlsrv_query( $conn, $sql, $params);
$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
echo "No information available.<br />";
} else {
echo $rows_affected." rows were updated.<br />";
}
?>`

### See Also

- sqlsrv_num_rows() - Retrieves the number of rows in a result set

# sqlsrv_send_stream_data

(No version information available, might only be in Git)

sqlsrv_send_stream_data — Sends data from parameter streams to the server

### Description

sqlsrv_send_stream_data(resource `$stmt`): bool

Send data from parameter streams to the server. Up to 8 KB of data is sent with each call.

### Parameters

`stmt`
  A statement resource returned by sqlsrv_query() or sqlsrv_execute().

### Return Values

Returns `true` if there is more data to send and `false` if there is not.

### Examples

Example #1 sqlsrv_send_stream_data() example

`<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";
// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);
// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);
sqlsrv_execute( $stmt);
// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
$i++;
}
echo "$i calls were made.";
?>`

### See Also

- sqlsrv_prepare() - Prepares a query for execution
- sqlsrv_query() - Prepares and executes a query

# sqlsrv_server_info

(No version information available, might only be in Git)

sqlsrv_server_info — Returns information about the server

### Description

sqlsrv_server_info(resource `$conn`): array

Returns information about the server.

### Parameters

`conn`
  The connection resource that connects the client and the server.

### Return Values

Returns an array as described in the following table:

Returned Array
CurrentDatabase | The connected-to database.
--- | ---
SQLServerVersion | The SQL Server version.
SQLServerName | The name of the server.

### Examples

Example #1 sqlsrv_server_info() example

`<?php
$serverName = "serverName\sqlexpress";
$conn = sqlsrv_connect( $serverName);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$server_info = sqlsrv_server_info( $conn);
if( $server_info )
{
foreach( $server_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
die( print_r( sqlsrv_errors(), true));
}
?>`

### See Also

- sqlsrv_client_info() - Returns information about the client and specified connection

## Table of Contents

- sqlsrv_begin_transaction — Begins a database transaction
- sqlsrv_cancel — Cancels a statement
- sqlsrv_client_info — Returns information about the client and specified connection
- sqlsrv_close — Closes an open connection and releases resourses associated with the connection
- sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
- sqlsrv_configure — Changes the driver error handling and logging configurations
- sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
- sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
- sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
- sqlsrv_fetch — Makes the next row in a result set available for reading
- sqlsrv_fetch_array — Returns a row as an array
- sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
- sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
- sqlsrv_free_stmt — Frees all resources for the specified statement
- sqlsrv_get_config — Returns the value of the specified configuration setting
- sqlsrv_get_field — Gets field data from the currently selected row
- sqlsrv_has_rows — Indicates whether the specified statement has rows
- sqlsrv_next_result — Makes the next result of the specified statement active
- sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
- sqlsrv_num_rows — Retrieves the number of rows in a result set
- sqlsrv_prepare — Prepares a query for execution
- sqlsrv_query — Prepares and executes a query
- sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
- sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
- sqlsrv_send_stream_data — Sends data from parameter streams to the server
- sqlsrv_server_info — Returns information about the server

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- SQLSRV Functions
  - sqlsrv_begin_transaction — Begins a database transaction
  - sqlsrv_cancel — Cancels a statement
  - sqlsrv_client_info — Returns information about the client and specified connection
  - sqlsrv_close — Closes an open connection and releases resourses associated with the connection
  - sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
  - sqlsrv_configure — Changes the driver error handling and logging configurations
  - sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
  - sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
  - sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
  - sqlsrv_fetch — Makes the next row in a result set available for reading
  - sqlsrv_fetch_array — Returns a row as an array
  - sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
  - sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  - sqlsrv_free_stmt — Frees all resources for the specified statement
  - sqlsrv_get_config — Returns the value of the specified configuration setting
  - sqlsrv_get_field — Gets field data from the currently selected row
  - sqlsrv_has_rows — Indicates whether the specified statement has rows
  - sqlsrv_next_result — Makes the next result of the specified statement active
  - sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
  - sqlsrv_num_rows — Retrieves the number of rows in a result set
  - sqlsrv_prepare — Prepares a query for execution
  - sqlsrv_query — Prepares and executes a query
  - sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
  - sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
  - sqlsrv_send_stream_data — Sends data from parameter streams to the server
  - sqlsrv_server_info — Returns information about the server

- CUBRID
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - CUBRID Functions
  - CUBRID MySQL Compatibility Functions
  - CUBRID Obsolete Aliases and Functions
- dBase
  - Installing/Configuring
  - Predefined Constants
  - dBase Functions
- Firebird/InterBase
  - Installing/Configuring
  - Predefined Constants
  - Firebird/InterBase Functions
- IBM DB2 — IBM DB2, Cloudscape and Apache Derby
  - Installing/Configuring
  - Predefined Constants
  - IBM DB2 Functions
- MongoDB — MongoDB Extension
  - Installing/Configuring
  - Predefined Constants
  - Tutorials
  - Driver Architecture and Internals — Explains the driver architecture, and special features
  - Security
  - MongoDB\Driver — MongoDB Extension Classes
  - MongoDB\BSON — MongoDB BSON Classes and Functions
  - MongoDB\Driver\Monitoring — Monitoring classes and subscriber functions
  - MongoDB\Driver\Exception — Exception classes
- MySQL — MySQL Drivers and Plugins
  - Overview of the MySQL PHP drivers
  - MySQLi — MySQL Improved Extension
  - Mysql_xdevapi
  - MySQL (Original) — Original MySQL API
  - Mysqlnd — MySQL Native Driver
- OCI8 — Oracle OCI8
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - OCI8 Connection Handling and Connection Pooling
  - OCI8 Fast Application Notification (FAN) Support
  - OCI8 Transparent Application Failover (TAF) Support
  - OCI8 and DTrace Dynamic Tracing
  - Supported Datatypes
  - OCI8 Functions
  - OCICollection — The OCICollection class
  - OCILob — The OCILob class
  - OCI8 Obsolete Aliases and Functions
- PostgreSQL
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - PostgreSQL Functions
  - PgSql\Connection — The PgSql\Connection class
  - PgSql\Result — The PgSql\Result class
  - PgSql\Lob — The PgSql\Lob class
- SQLite3
  - Installing/Configuring
  - Predefined Constants
  - SQLite3 — The SQLite3 class
  - SQLite3Exception — The SQLite3Exception class
  - SQLite3Stmt — The SQLite3Stmt class
  - SQLite3Result — The SQLite3Result class
- SQLSRV — Microsoft SQL Server Driver for PHP
  - Installing/Configuring
  - Predefined Constants
  - SQLSRV Functions

- Abstraction Layers
  - DBA — Database (dbm-style) Abstraction Layer
  - ODBC — ODBC (Unified)
  - PDO — PHP Data Objects
- Vendor Specific Database Extensions
  - CUBRID
  - dBase
  - Firebird/InterBase
  - IBM DB2 — IBM DB2, Cloudscape and Apache Derby
  - MongoDB — MongoDB Extension
  - MySQL — MySQL Drivers and Plugins
  - OCI8 — Oracle OCI8
  - PostgreSQL
  - SQLite3
  - SQLSRV — Microsoft SQL Server Driver for PHP

# Date and Time Related Extensions

# Calendar

# Introduction

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.

# Installing/Configuring

## Table of Contents

- Installation

## Installation

To get these functions to work, you have to compile PHP with --enable-calendar.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

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

`CAL_EASTER_DEFAULT` (int)
  For easter_days(): calculate Easter for years before 1753 according to the Julian calendar, and for later years according to the Gregorian calendar.
`CAL_EASTER_ROMAN` (int)
  For easter_days(): calculate Easter for years before 1583 according to the Julian calendar, and for later years according to the Gregorian calendar.
`CAL_EASTER_ALWAYS_GREGORIAN` (int)
  For easter_days(): calculate Easter according to the proleptic Gregorian calendar.
`CAL_EASTER_ALWAYS_JULIAN` (int)
  For easter_days(): calculate Easter according to the Julian calendar.
`CAL_GREGORIAN` (int)
  For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the proleptic Gregorian calendar.
`CAL_JULIAN` (int)
  For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the Julian calendar.
`CAL_JEWISH` (int)
  For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the Jewish calendar.
`CAL_FRENCH` (int)
  For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the French Repuclican calendar.
`CAL_NUM_CALS` (int)
  The number of available calendars.
`CAL_JEWISH_ADD_ALAFIM_GERESH` (int)
  For jdtojewish(): adds a geresh symbol (which resembles a single-quote mark) as thousands separator to the year number.
`CAL_JEWISH_ADD_ALAFIM` (int)
  For jdtojewish(): adds the word alafim as thousands separator to the year number.
`CAL_JEWISH_ADD_GERESHAYIM` (int)
  For jdtojewish(): add a gershayim symbol (which resembles a double-quote mark) before the final letter of the day and year numbers.
`CAL_DOW_DAYNO` (int)
  For jddayofweek(): the day of the week as int, where `0` means Sunday and `6` means Saturday.
`CAL_DOW_SHORT` (int)
  For jddayofweek(): the abbreviated English name of the day of the week.
`CAL_DOW_LONG` (int)
  For jddayofweek(): the English name of the day of the week.
`CAL_MONTH_GREGORIAN_SHORT` (int)
  For jdmonthname(): the abbreviated Gregorian month name.
`CAL_MONTH_GREGORIAN_LONG` (int)
  For jdmonthname(): the Gregorian month name.
`CAL_MONTH_JULIAN_SHORT` (int)
  For jdmonthname(): the abbreviated Julian month name.
`CAL_MONTH_JULIAN_LONG` (int)
  For jdmonthname(): the Julian month name.
`CAL_MONTH_JEWISH` (int)
  For jdmonthname(): the Jewish month name.
`CAL_MONTH_FRENCH` (int)
  For jdmonthname(): the French Republican month name.

# Calendar Functions

# cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_days_in_month — Return the number of days in a month for a given year and calendar

### Description

cal_days_in_month(int `$calendar`, int `$month`, int `$year`): int

This function will return the number of days in the `month` of `year` for the specified `calendar`.

### Parameters

`calendar`

  Calendar to use for calculation

`month`

  Month in the selected calendar

`year`

  Year in the selected calendar

### Return Values

The length in days of the selected month in the given calendar

### Examples

Example #1 cal_days_in_month() example

`<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";
?>`

# cal_from_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_from_jd — Converts from Julian Day Count to a supported calendar

### Description

cal_from_jd(int `$julian_day`, int `$calendar`): array

cal_from_jd() converts the Julian day given in `julian_day` into a date of the specified `calendar`. Supported `calendar` values are `CAL_GREGORIAN`, `CAL_JULIAN`, `CAL_JEWISH` and `CAL_FRENCH`.

### Parameters

`julian_day`

  Julian day as integer

`calendar`

  Calendar to convert to

### Return Values

Returns an array containing calendar information like month, day, year, day of week (`dow`), abbreviated and full names of weekday and month and the date in string form "month/day/year". The day of week ranges from `0` (Sunday) to `6` (Saturday).

### Examples

Example #1 cal_from_jd() example

`<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>`

The above example will output:

    Array
    (
        [date] => 8/16/2003
        [month] => 8
        [day] => 16
        [year] => 2003
        [dow] => 6
        [abbrevdayname] => Sat
        [dayname] => Saturday
        [abbrevmonth] => Aug
        [monthname] => August
    )

### See Also

- cal_to_jd() - Converts from a supported calendar to Julian Day Count
- jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
- jdtogregorian() - Converts Julian Day Count to Gregorian date
- jdtojewish() - Converts a Julian day count to a Jewish calendar date
- jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
- jdtounix() - Convert Julian Day to Unix timestamp

# cal_info

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_info — Returns information about a particular calendar

### Description

cal_info(int `$calendar` = -1): array

cal_info() returns information on the specified `calendar`.

Calendar information is returned as an array containing the elements `calname`, `calsymbol`, `month`, `abbrevmonth` and `maxdaysinmonth`. The names of the different calendars which can be used as `calendar` are as follows:

- 0 or `CAL_GREGORIAN` - Gregorian Calendar
- 1 or `CAL_JULIAN` - Julian Calendar
- 2 or `CAL_JEWISH` - Jewish Calendar
- 3 or `CAL_FRENCH` - French Revolutionary Calendar

If no `calendar` is specified information on all supported calendars is returned as an array.

### Parameters

`calendar`

  Calendar to return information for. If no calendar is specified information about all calendars is returned.

### Return Values

### Examples

Example #1 cal_info() example

`<?php
$info = cal_info(0);
print_r($info);
?>`

The above example will output:

    Array
    (
        [months] => Array
            (
                [1] => January
                [2] => February
                [3] => March
                [4] => April
                [5] => May
                [6] => June
                [7] => July
                [8] => August
                [9] => September
                [10] => October
                [11] => November
                [12] => December
            )

        [abbrevmonths] => Array
            (
                [1] => Jan
                [2] => Feb
                [3] => Mar
                [4] => Apr
                [5] => May
                [6] => Jun
                [7] => Jul
                [8] => Aug
                [9] => Sep
                [10] => Oct
                [11] => Nov
                [12] => Dec
            )

        [maxdaysinmonth] => 31
        [calname] => Gregorian
        [calsymbol] => CAL_GREGORIAN
    )

# cal_to_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_to_jd — Converts from a supported calendar to Julian Day Count

### Description

cal_to_jd(
int `$calendar`,
int `$month`,
int `$day`,
int `$year`
): int

cal_to_jd() calculates the Julian day count for a date in the specified `calendar`. Supported `calendar`s are `CAL_GREGORIAN`, `CAL_JULIAN`, `CAL_JEWISH` and `CAL_FRENCH`.

### Parameters

`calendar`

  Calendar to convert from, one of `CAL_GREGORIAN`, `CAL_JULIAN`, `CAL_JEWISH` or `CAL_FRENCH`.

`month`

  The month as a number, the valid range depends on the `calendar`

`day`

  The day as a number, the valid range depends on the `calendar`

`year`

  The year as a number, the valid range depends on the `calendar`

### Return Values

A Julian Day number.

### See Also

- cal_from_jd() - Converts from Julian Day Count to a supported calendar
- frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
- gregoriantojd() - Converts a Gregorian date to Julian Day Count
- jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
- juliantojd() - Converts a Julian Calendar date to Julian Day Count
- unixtojd() - Convert Unix timestamp to Julian Day

# easter_date

(PHP 4, PHP 5, PHP 7, PHP 8)

easter_date — Get Unix timestamp for local midnight on Easter of a given year

### Description

easter_date(?int `$year` = `null`, int `$mode` = `CAL_EASTER_DEFAULT`): int

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

### Parameters

`year`

  The year must be a number between 1970 and 2037 for 32-bit systems, or between 1970 and 2,000,000,000 for 64-bit systems. If omitted or `null`, defaults to the current year according to the local time.

`mode`

  Allows Easter dates to be calculated based on the Julian calendar when set to `CAL_EASTER_ALWAYS_JULIAN`. See also calendar constants.

### Return Values

The easter date as a unix timestamp.

### Errors/Exceptions

A ValueError is thrown if the year is earlier than 1970 or later than 2037 when running on a 32-bit system, or later than 2,000,000,000 on a 64-bit system.

### Changelog

Version | Description
--- | ---
8.3.0 | On 64-bit systems, the `year` parameter now accepts values within the range of 1970 to 2,000,000,000.
8.0.0 | `year` is nullable now.
8.0.0 | A ValueError is now thrown when `year` is outside the allowed range. Previously, an `E_WARNING` was raised and the function returned `false`.

### Examples

Example #1 easter_date() example

`<?php
echo date("M-d-Y", easter_date(1999)); // Apr-04-1999
echo date("M-d-Y", easter_date(2000)); // Apr-23-2000
echo date("M-d-Y", easter_date(2001)); // Apr-15-2001
?>`

Example #2 Using easter_date() with DateTime

`<?php
$timestamp = easter_date(2023);
$datetime = new \DateTime();
$datetime->setTimestamp($timestamp);
echo $datetime->format('M-d-Y'); // Apr-09-2023
?>`

### Notes

> Note:

> easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the `TZ` environment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.

> As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:

> `<?php
> function get_easter_datetime($year) {
> $base = new DateTime("$year-03-21");
> $days = easter_days($year);
> return $base->add(new DateInterval("P{$days}D"));
> }
> foreach (range(2012, 2015) as $year) {
> printf("Easter in %d is on %s\n",
> $year,
> get_easter_datetime($year)->format('F j'));
> }
> ?>`

> The above example will output:

>     Easter in 2012 is on April 8
>     Easter in 2013 is on March 31
>     Easter in 2014 is on April 20
>     Easter in 2015 is on April 5

### See Also

- easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037

# easter_days

(PHP 4, PHP 5, PHP 7, PHP 8)

easter_days — Get number of days after March 21 on which Easter falls for a given year

### Description

easter_days(?int `$year` = `null`, int `$mode` = `CAL_EASTER_DEFAULT`): int

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

### Parameters

`year`

  The year as a positive number. If omitted or `null`, defaults to the current year according to the local time.

`mode`

  Allows Easter dates to be calculated based on the Gregorian calendar during the years 1582 - 1752 when set to `CAL_EASTER_ROMAN`. See the calendar constants for more valid constants.

### Return Values

The number of days after March 21st that the Easter Sunday is in the given `year`.

### Changelog

Version | Description
--- | ---
8.0.0 | `year` is nullable now.

### Examples

Example #1 easter_days() example

`<?php
echo easter_days(1999); // 14, i.e. April 4
echo easter_days(1492); // 32, i.e. April 22
echo easter_days(1913); // 2, i.e. March 23
?>`

### See Also

- easter_date() - Get Unix timestamp for local midnight on Easter of a given year

# frenchtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

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

### Description

frenchtojd(int `$month`, int `$day`, int `$year`): int

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

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

### Parameters

`month`

  The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

`day`

  The day as a number from 1 to 30

`year`

  The year as a number between 1 and 14

### Return Values

The julian day for the given french revolution date as an integer.

### See Also

- jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
- cal_to_jd() - Converts from a supported calendar to Julian Day Count

# gregoriantojd

(PHP 4, PHP 5, PHP 7, PHP 8)

gregoriantojd — Converts a Gregorian date to Julian Day Count

### Description

gregoriantojd(int `$month`, int `$day`, int `$year`): int

The valid range for the Gregorian calendar is from November 25, 4714 B.C. to at least December 31, 9999 A.D.

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

### Parameters

`month`

  The month as a number from 1 (for January) to 12 (for December)

`day`

  The day as a number from 1 to 31. If the month has less days then given, overflow occurs; see the example below.

`year`

  The year as a number between -4714 and 9999. Negative numbers mean years B.C., positive numbers mean years A.D. Note that there is no year `0`; December 31, 1 B.C. is immediately followed by January 1, 1 A.D.

### Return Values

The julian day for the given gregorian date as an integer. Dates outside the valid range return `0`.

### Examples

Example #1 Calendar functions

`<?php
$jd = gregoriantojd(10, 11, 1970);
echo "$jd\n";
$gregorian = jdtogregorian($jd);
echo "$gregorian\n";
?>`

The above example will output:

    2440871
    10/11/1970

Example #2 Overflow behavior

`<?php
echo gregoriantojd(2, 31, 2018), PHP_EOL,
gregoriantojd(3, 3, 2018), PHP_EOL;
?>`

The above example will output:

    2458181
    2458181

### See Also

- jdtogregorian() - Converts Julian Day Count to Gregorian date
- cal_to_jd() - Converts from a supported calendar to Julian Day Count

# jddayofweek

(PHP 4, PHP 5, PHP 7, PHP 8)

jddayofweek — Returns the day of the week

### Description

jddayofweek(int `$julian_day`, int `$mode` = `CAL_DOW_DAYNO`): int|string

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

### Parameters

`julian_day`

  A julian day number as integer

`mode`

  Calendar week modes
  Mode | Meaning
  --- | ---
  0 (Default) | Return the day number as an int (0=Sunday, 1=Monday, etc)
  1 | Returns string containing the day of week (English-Gregorian)
  2 | Return a string containing the abbreviated day of week (English-Gregorian)

### Return Values

The gregorian weekday as either an integer or string.

# jdmonthname

(PHP 4, PHP 5, PHP 7, PHP 8)

jdmonthname — Returns a month name

### Description

jdmonthname(int `$julian_day`, int `$mode`): string

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

Calendar modes
Mode | Meaning | Values
--- | --- | ---
`CAL_MONTH_GREGORIAN_SHORT` | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
`CAL_MONTH_GREGORIAN_LONG` | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December
`CAL_MONTH_JULIAN_SHORT` | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
`CAL_MONTH_JULIAN_LONG` | Julian | January, February, March, April, May, June, July, August, September, October, November, December
`CAL_MONTH_JEWISH` | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, Adar, Adar I, Adar II, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
`CAL_MONTH_FRENCH` | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

### Parameters

`julian_day`

  The Julian Day to operate on

`mode`

  The calendar mode (see table above).

### Return Values

The month name for the given Julian Day and `mode`.

# jdtofrench

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtofrench — Converts a Julian Day Count to the French Republican Calendar

### Description

jdtofrench(int `$julian_day`): string

Converts a Julian Day Count to the French Republican Calendar.

### Parameters

`julian_day`

  A julian day number as integer

### Return Values

The french revolution date as a string in the form "month/day/year"

### See Also

- frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
- cal_from_jd() - Converts from Julian Day Count to a supported calendar

# jdtogregorian

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtogregorian — Converts Julian Day Count to Gregorian date

### Description

jdtogregorian(int `$julian_day`): string

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

### Parameters

`julian_day`

  A julian day number as integer

### Return Values

The gregorian date as a string in the form "month/day/year"

### See Also

- gregoriantojd() - Converts a Gregorian date to Julian Day Count
- cal_from_jd() - Converts from Julian Day Count to a supported calendar

# jdtojewish

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtojewish — Converts a Julian day count to a Jewish calendar date

### Description

jdtojewish(int `$julian_day`, bool `$hebrew` = `false`, int `$flags` = 0): string

Converts a Julian Day Count to the Jewish Calendar.

### Parameters

`julian_day`

  A julian day number as integer

`hebrew`

  If the `hebrew` parameter is set to `true`, the `flags` parameter is used for Hebrew, ISO-8859-8 encoded string based, output format.

`flags`

  A bitmask which may consist of `CAL_JEWISH_ADD_ALAFIM_GERESH`, `CAL_JEWISH_ADD_ALAFIM` and `CAL_JEWISH_ADD_GERESHAYIM`.

### Return Values

The Jewish date as a string in the form "month/day/year", or an ISO-8859-8 encoded Hebrew date string, according to the `hebrew` parameter.

### Examples

Example #1 jdtojewish() Example

`<?php
$jd = gregoriantojd(10, 8, 2002);
echo jdtojewish($jd, true), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_GERESHAYIM), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_ALAFIM), PHP_EOL,
jdtojewish($jd, true,CAL_JEWISH_ADD_ALAFIM_GERESH), PHP_EOL;
?>`

The above example will output:

    ב חשון התשסג
    ב' חשון התשס"ג
    ב חשון ה אלפים תשסג
    ב חשון ה'תשסג

### See Also

- jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
- cal_from_jd() - Converts from Julian Day Count to a supported calendar

# jdtojulian

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtojulian — Converts a Julian Day Count to a Julian Calendar Date

### Description

jdtojulian(int `$julian_day`): string

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

### Parameters

`julian_day`

  A julian day number as integer

### Return Values

The julian date as a string in the form "month/day/year"

### See Also

- juliantojd() - Converts a Julian Calendar date to Julian Day Count
- cal_from_jd() - Converts from Julian Day Count to a supported calendar

# jdtounix

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtounix — Convert Julian Day to Unix timestamp

### Description

jdtounix(int `$julian_day`): int

This function will return a Unix timestamp corresponding to the Julian Day given in `julian_day`. The time returned is UTC.

### Parameters

`julian_day`

  A julian day number between `2440588` and `106751993607888` on 64bit systems, or between `2440588` and `2465443` on 32bit systems.

### Return Values

The unix timestamp for the start (midnight, not noon) of the given Julian day

### Errors/Exceptions

If `julian_day` is outside of the allowed range, a ValueError is thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | This function no longer returns `false` on failure, but raises a ValueError instead.
7.3.24, 7.4.12 | The upper limit of `julian_day` has been extended. Previously, it was `2465342` regardless of the architecture.

### See Also

- unixtojd() - Convert Unix timestamp to Julian Day

# jewishtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count

### Description

jewishtojd(int `$month`, int `$day`, int `$year`): int

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

### Parameters

`month`

  The month as a number from `1` to `13`, where `1` means `Tishri`, `13` means `Elul`, and `6` and `7` mean `Adar` in regular years, but `Adar I` and `Adar II`, respectively, in leap years.

`day`

  The day as a number from `1` to `30`. If the month has only 29 days, the first day of the following month is assumed.

`year`

  The year as a number between 1 and 9999

### Return Values

The julian day for the given jewish date as an integer.

### See Also

- jdtojewish() - Converts a Julian day count to a Jewish calendar date
- cal_to_jd() - Converts from a supported calendar to Julian Day Count

# juliantojd

(PHP 4, PHP 5, PHP 7, PHP 8)

juliantojd — Converts a Julian Calendar date to Julian Day Count

### Description

juliantojd(int `$month`, int `$day`, int `$year`): int

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

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

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

### Parameters

`month`

  The month as a number from 1 (for January) to 12 (for December)

`day`

  The day as a number from 1 to 31

`year`

  The year as a number between -4713 and 9999

### Return Values

The julian day for the given julian date as an integer.

### See Also

- jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
- cal_to_jd() - Converts from a supported calendar to Julian Day Count

# unixtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

unixtojd — Convert Unix timestamp to Julian Day

### Description

unixtojd(?int `$timestamp` = `null`): int|false

Return the Julian Day for a Unix `timestamp` (seconds since 1.1.1970), or for the current day if no `timestamp` is given. Either way, the time is regarded as local time (not UTC).

### Parameters

`timestamp`

  A unix timestamp to convert.

### Return Values

A julian day number as integer, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### See Also

- jdtounix() - Convert Julian Day to Unix timestamp

## Table of Contents

- cal_days_in_month — Return the number of days in a month for a given year and calendar
- cal_from_jd — Converts from Julian Day Count to a supported calendar
- cal_info — Returns information about a particular calendar
- cal_to_jd — Converts from a supported calendar to Julian Day Count
- easter_date — Get Unix timestamp for local midnight on Easter of a given year
- easter_days — Get number of days after March 21 on which Easter falls for a given year
- frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count
- gregoriantojd — Converts a Gregorian date to Julian Day Count
- jddayofweek — Returns the day of the week
- jdmonthname — Returns a month name
- jdtofrench — Converts a Julian Day Count to the French Republican Calendar
- jdtogregorian — Converts Julian Day Count to Gregorian date
- jdtojewish — Converts a Julian day count to a Jewish calendar date
- jdtojulian — Converts a Julian Day Count to a Julian Calendar Date
- jdtounix — Convert Julian Day to Unix timestamp
- jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count
- juliantojd — Converts a Julian Calendar date to Julian Day Count
- unixtojd — Convert Unix timestamp to Julian Day

- Installing/Configuring
  - Installation
- Predefined Constants
- Calendar Functions
  - cal_days_in_month — Return the number of days in a month for a given year and calendar
  - cal_from_jd — Converts from Julian Day Count to a supported calendar
  - cal_info — Returns information about a particular calendar
  - cal_to_jd — Converts from a supported calendar to Julian Day Count
  - easter_date — Get Unix timestamp for local midnight on Easter of a given year
  - easter_days — Get number of days after March 21 on which Easter falls for a given year
  - frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count
  - gregoriantojd — Converts a Gregorian date to Julian Day Count
  - jddayofweek — Returns the day of the week
  - jdmonthname — Returns a month name
  - jdtofrench — Converts a Julian Day Count to the French Republican Calendar
  - jdtogregorian — Converts Julian Day Count to Gregorian date
  - jdtojewish — Converts a Julian day count to a Jewish calendar date
  - jdtojulian — Converts a Julian Day Count to a Julian Calendar Date
  - jdtounix — Convert Julian Day to Unix timestamp
  - jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count
  - juliantojd — Converts a Julian Calendar date to Julian Day Count
  - unixtojd — Convert Unix timestamp to Julian Day

# Date and Time

# Introduction

The DateTimeImmutable and related classes allow you represent date/time information. The objects can be created by passing in a string presentation of date/time information, or from the current system's time.

A rich set of methods is supplied to modify and format this information as well, including handling timezones and DST transitions.

The date/time features in PHP implements the ISO 8601 calendar, which is a » proleptic Gregorian calendar which implements the current leap-day rules from before the Gregorian calendar was in place, and also includes the year `0` as the year number in between `-1 BCE` and `1 CE`. Leap seconds are not supported.

The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.

> Note: The timezones referenced in this section can be found in the List of Supported Timezones.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

There is no installation needed to use these functions; they are part of the PHP core.

> Note: Getting the latest timezone database

> The latest version of the timezone database can be installed via PECL's » timezonedb.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Date/Time Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
date.default_latitude | "31.7667" | `INI_ALL` |
date.default_longitude | "35.2333" | `INI_ALL` |
date.sunrise_zenith | "90.833333" | `INI_ALL` | Prior to PHP 8.0.0, the default was "90.583333"
date.sunset_zenith | "90.833333" | `INI_ALL` | Prior to PHP 8.0.0, the default was "90.583333"
date.timezone | "UTC" | `INI_ALL` | From PHP 8.2, a warning is emitted when setting this to an invalid value or an empty string.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`date.default_latitude` float

  The default latitude ranging from `0` at the equator, to `+90` northward, and `-90` southward.

`date.default_longitude` float

  The default longitude ranging from `0` at the prime meridian to `+180` eastward and `−180` westward.

`date.sunrise_zenith` float

  The default sunrise zenith.

  The default value is 90°50'. The additional 50' is due to two components: the Sun's radius, which is 16', and the atmospheric refraction, which is 34'.

`date.sunset_zenith` float

  The default sunset zenith.

`date.timezone` string

  The default timezone used by all date/time functions. The precedence order for which timezone is used if none is explicitly mentioned is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.

> Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().

# Predefined Constants

The `DATE_*` constants are defined and offer standard date representations, which can be used along with the date format functions (like date()).

Available `returnFormat` for date_sunrise() and date_sunset()
Warning

These constants are deprecated as of PHP 8.4.0. The corresponding date_sunrise() and date_sunset() functions are deprecated as of PHP 8.1.0.

`SUNFUNCS_RET_TIMESTAMP` (int)
  Timestamp
`SUNFUNCS_RET_STRING` (int)
  Hours:minutes (example: `08:02`)
`SUNFUNCS_RET_DOUBLE` (int)
  Hours as floating point number (example `8.75`)

`DATE_*` constants
`DATE_ATOM` (string)
  Atom (example: `2005-08-15T15:52:01+00:00`); compatible with ISO-8601, RFC 3339, and XML Schema
`DATE_COOKIE` (string)
  HTTP Cookies (example: `Monday, 15-Aug-2005 15:52:01 UTC`)
`DATE_ISO8601` (string)
  ISO-8601-like (example: `2005-08-15T15:52:01+0000`)

  > Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use `DATE_ISO8601_EXPANDED`, `DATE_ATOM` for compatibility with ISO-8601 instead (ref ISO8601:2004 section 4.3.3 clause d).

`DATE_ISO8601_EXPANDED` (string)
  ISO-8601 Expanded (example: `+10191-07-26T08:59:52+01:00`)

  > Note: This format allows for year ranges outside of ISO-8601's normal range of `0000`-`9999` by always including a sign character. It also ensures that the timezone part (`+01:00`) is compatible with ISO-8601.

`DATE_RFC822` (string)
  RFC 822 (example: `Mon, 15 Aug 05 15:52:01 +0000`)
`DATE_RFC850` (string)
  RFC 850 (example: `Monday, 15-Aug-05 15:52:01 UTC`)
`DATE_RFC1036` (string)
  RFC 1036 (example: `Mon, 15 Aug 05 15:52:01 +0000`)
`DATE_RFC1123` (string)
  RFC 1123 (example: `Mon, 15 Aug 2005 15:52:01 +0000`)
`DATE_RFC7231` (string)
  RFC 7231 (as of PHP 7.0.19 and 7.1.5) (example: `Sat, 30 Apr 2016 17:52:13 GMT`)
`DATE_RFC2822` (string)
  RFC 2822 (example: `Mon, 15 Aug 2005 15:52:01 +0000`)
`DATE_RFC3339` (string)
  Same as `DATE_ATOM`.
`DATE_RFC3339_EXTENDED` (string)
  RFC 3339 EXTENDED format (example: `2005-08-15T15:52:01.000+00:00`)
`DATE_RSS` (string)
  RSS (example: `Mon, 15 Aug 2005 15:52:01 +0000`). Alias of `DATE_RFC1123`.
`DATE_W3C` (string)
  World Wide Web Consortium (example: `2005-08-15T15:52:01+00:00`). Alias of `DATE_RFC3339`.

# Examples

## Table of Contents

- Date/Time Arithmetic

## Date/Time Arithmetic

The following examples show some pitfalls of Date/Time arithmetic with regard to DST transitions and months having different numbers of days.

Example #1 DateTimeImmutable::add/sub add intervals which cover elapsed time

Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).

`<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->add(new DateInterval("PT3H"));
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;`

The above example will output:

    Start: 2015-11-01 00:00:00 -04:00
    End:   2015-11-01 02:00:00 -05:00

Example #2 DateTimeImmutable::modify and strtotime increment or decrement individual component values

Adding +24 hours over a DST transition will add exactly 24 hours as seen in the date/time string (unless the start or end time is on a transition point).

`<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+24 hours");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;`

The above example will output:

    Start: 2015-11-01 00:00:00 -04:00
    End:   2015-11-02 00:00:00 -05:00

Example #3 Adding or subtracting times can over- or underflow dates

Like where January 31st + 1 month will result in March 2nd (leap year) or 3rd (normal year).

`<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
echo "Leap year:\n"; // February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;`

The above example will output:

    Normal year:
    Start: 2015-01-31 00:00:00 -05:00
    End:   2015-03-03 00:00:00 -05:00
    Leap year:
    Start: 2016-01-31 00:00:00 -05:00
    End:   2016-03-02 00:00:00 -05:00

To get the last day of the next month (i.e. to prevent the overflow), the `last day of` format is available.

`<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
echo "Leap year:\n"; // February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;`

The above example will output:

    Normal year:
    Start: 2015-01-31 00:00:00 -05:00
    End:   2015-02-28 00:00:00 -05:00
    Leap year:
    Start: 2016-01-31 00:00:00 -05:00
    End:   2016-02-29 00:00:00 -05:00

# The DateTime class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

## Introduction

Representation of date and time.

This class behaves the same as DateTimeImmutable, except objects are modified itself when modification methods such as DateTime::modify() are called.

Warning

Calling methods on objects of the class DateTime will change the information encapsulated in these objects, if you want to prevent that you will have to use `clone` operator to create a new object. Use DateTimeImmutable instead of DateTime to obtain this recommended behaviour by default.

## Class synopsis

class DateTime implements DateTimeInterface {
/* Inherited constants */
public const string DateTimeInterface::ATOM = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
public const string DateTimeInterface::ISO8601 = "Y-m-d\\TH:i:sO";
public const string DateTimeInterface::ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC822 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
public const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC3339 = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string DateTimeInterface::RSS = "D, d M Y H:i:s O";
public const string DateTimeInterface::W3C = "Y-m-d\\TH:i:sP";
/* Methods */
public __construct(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`)
public add(DateInterval `$interval`): DateTime
public static createFromFormat(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTime|false
public static createFromImmutable(DateTimeImmutable `$object`): static
public static createFromInterface(DateTimeInterface `$object`): DateTime
public modify(string `$modifier`): DateTime
public static __set_state(array `$array`): DateTime
public setDate(int `$year`, int `$month`, int `$day`): DateTime
public setISODate(int `$year`, int `$week`, int `$dayOfWeek` = 1): DateTime
public setTime(
int `$hour`,
int `$minute`,
int `$second` = 0,
int `$microsecond` = 0
): DateTime
public setTimestamp(int `$timestamp`): DateTime
public setTimezone(DateTimeZone `$timezone`): DateTime
public sub(DateInterval `$interval`): DateTime
public diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval
public format(string `$format`): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __serialize(): array
public __unserialize(array `$data`): void
#[\Deprecated]
public __wakeup(): void
}

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
7.2.0 | The class constants of DateTime are now defined on DateTimeInterface.
7.1.0 | The DateTime constructor now includes the current microseconds in the constructed value. Before this, it would always initialise the microseconds to `0`.

# DateTime::add

# date_add

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::add -- date_add — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds

### Description

Object-oriented style

public DateTime::add(DateInterval `$interval`): DateTime

Procedural style

date_add(DateTime `$object`, DateInterval `$interval`): DateTime

Adds the specified DateInterval object to the specified DateTime object.

Like DateTimeImmutable::add() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`interval`

  A DateInterval object

### Return Values

Returns the modified DateTime object for method chaining.

### See Also

- DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds

# DateTime::__construct

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::__construct — Returns new DateTime object

### Description

public DateTime::__construct(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`)

Like DateTimeImmutable::__construct() but works with DateTime. Consider using the DateTimeImmutable and features instead.

Returns a new DateTime object.

### Parameters

`datetime`

  A date/time string. Valid formats are explained in Date and Time Formats.

  Enter `"now"` here to obtain the current time when using the `$timezone` parameter.

`timezone`

  A DateTimeZone object representing the timezone of `$datetime`.

  If `$timezone` is omitted or `null`, the current timezone will be used.

  > Note:

  > The `$timezone` parameter and the current timezone are ignored when the `$datetime` parameter either is a UNIX timestamp (e.g. `@946684800`) or specifies a timezone (e.g. `2010-01-28T15:00:00+02:00`).

### Return Values

Returns a new DateTime instance.

### Errors/Exceptions

If an invalid Date/Time string is passed, DateMalformedStringException is thrown. Previous to PHP 8.3, this was Exception.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws DateMalformedStringException if an invalid string is passed, instead of Exception.

### See Also

- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object

# DateTime::createFromFormat

# date_create_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format

### Description

Object-oriented style

public static DateTime::createFromFormat(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTime|false

Procedural style

date_create_from_format(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTime|false

Returns a new DateTime object representing the date and time specified by the `datetime` string, which was formatted in the given `format`.

Like DateTimeImmutable::createFromFormat() and date_create_immutable_from_format(), respectively, but creates a DateTime object.

This method, including parameters, examples, and considerations are documented on the DateTimeImmutable::createFromFormat page.

### Parameters

See DateTimeImmutable::createFromFormat.

### Return Values

Returns a new DateTime instance or `false` on failure.

### Errors/Exceptions

This method throws ValueError when the `datetime` contains NULL-bytes.

### Changelog

Version | Description
--- | ---
8.0.21, 8.1.8, 8.2.0 | Now throws ValueError when NULL-bytes are passed into `datetime`, which previously was silently ignored.

### Examples

For an extensive set of examples, see DateTimeImmutable::createFromFormat.

### See Also

- DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format

# DateTime::createFromImmutable

(PHP 7 >= 7.3.0, PHP 8)

DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object

### Description

public static DateTime::createFromImmutable(DateTimeImmutable `$object`): static

### Parameters

`object`

  The immutable DateTimeImmutable object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime instance is created containing the same date, time, and timezone information.

### Return Values

Returns a new DateTime instance.

### Changelog

Version | Description
--- | ---
8.0.0 | The method returns an instance of the currently invoked class now. Previously, it created a new instance of DateTime.

### Examples

Example #1 Creating a mutable date time object

`<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$mutable = DateTime::createFromImmutable( $date );`

# DateTime::createFromInterface

(PHP 8)

DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object

### Description

public static DateTime::createFromInterface(DateTimeInterface `$object`): DateTime

### Parameters

`object`

  The DateTimeInterface object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime object is created containing the same date, time, and timezone information.

### Return Values

Returns a new DateTime instance.

### Examples

Example #1 Creating a mutable date time object

`<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$mutable = DateTime::createFromInterface($date);
$date = new DateTime("2014-06-20 11:45 Europe/London");
$also_mutable = DateTime::createFromInterface($date);`

# DateTime::getLastErrors

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::getLastErrors — Alias of DateTimeImmutable::getLastErrors()

### Description

This function is an alias of: DateTimeImmutable::getLastErrors()

# DateTime::modify

# date_modify

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::modify -- date_modify — Alters the timestamp

### Description

Object-oriented style

public DateTime::modify(string `$modifier`): DateTime

Procedural style

date_modify(DateTime `$object`, string `$modifier`): DateTime|false

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by DateTimeImmutable::__construct().

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`modifier`

  A date/time string. Valid formats are explained in Date and Time Formats.

### Return Values

Returns DateTime on success. Procedural style returns `false` on failure.

### Errors/Exceptions

Object Oriented API only: If an invalid Date/Time string is passed, DateMalformedStringException is thrown.

### Changelog

Version | Description
--- | ---
8.3.0 | DateTime::modify() now throws DateMalformedStringException if an invalid string is passed. Previously, it returned `false`, and a warning was emitted. date_modify() has not been changed.

### Examples

Example #1 DateTime::modify() example

Object-oriented style

`<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');`

The above example will output:

    2006-12-13

Procedural style

`<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');`

The above example will output:

    2006-12-13

Example #2 Beware when adding or subtracting months

`<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";`

The above example will output:

    2001-01-31
    2001-03-03

Example #3 All formats of Date and Time are supported

`<?php
$date = new DateTime('2020-12-31');
$date->modify('July 1st, 2023');
echo $date->format('Y-m-d H:i') . "\n";
$date->modify('Monday next week');
echo $date->format('Y-m-d H:i') . "\n";
$date->modify('17:30');
echo $date->format('Y-m-d H:i') . "\n";`

The above example will output:

    2023-07-01 00:00
    2023-07-03 00:00
    2023-07-03 17:30

### See Also

- strtotime() - Parse about any English textual datetime description into a Unix timestamp
- DateTimeImmutable::modify() - Creates a new object with modified timestamp
- DateTime::add() - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTime::setDate() - Sets the date
- DateTime::setISODate() - Sets the ISO date
- DateTime::setTime() - Sets the time
- DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp

# DateTime::__set_state

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::__set_state — The __set_state handler

### Description

public static DateTime::__set_state(array `$array`): DateTime

The __set_state() handler.

Like DateTimeImmutable::__set_state() but works with DateTime.

### Parameters

`array`

  Initialization array.

### Return Values

Returns a new instance of a DateTime object.

# DateTime::setDate

# date_date_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setDate -- date_date_set — Sets the date

### Description

Object-oriented style

public DateTime::setDate(int `$year`, int `$month`, int `$day`): DateTime

Procedural style

date_date_set(
DateTime `$object`,
int `$year`,
int `$month`,
int `$day`
): DateTime

Resets the current date of the DateTime object to a different date.

Like DateTimeImmutable::setDate() but works with DateTime, and changes the existing object.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`year`

  Year of the date.

`month`

  Month of the date.

`day`

  Day of the date.

### Return Values

Returns the modified DateTime object for method chaining.

### See Also

- DateTimeImmutable::setDate() - Sets the date

# DateTime::setISODate

# date_isodate_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setISODate -- date_isodate_set — Sets the ISO date

### Description

Object-oriented style

public DateTime::setISODate(int `$year`, int `$week`, int `$dayOfWeek` = 1): DateTime

Procedural style

date_isodate_set(
DateTime `$object`,
int `$year`,
int `$week`,
int `$dayOfWeek` = 1
): DateTime

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Like DateTimeImmutable::setISODate() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`year`

  Year of the date.

`week`

  Week of the date.

`dayOfWeek`

  Offset from the first day of the week.

### Return Values

Returns the modified DateTime object for method chaining.

### See Also

- DateTimeImmutable::setISODate() - Sets the ISO date

# DateTime::setTime

# date_time_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setTime -- date_time_set — Sets the time

### Description

Object-oriented style

public DateTime::setTime(
int `$hour`,
int `$minute`,
int `$second` = 0,
int `$microsecond` = 0
): DateTime

Procedural style

date_time_set(
DateTime `$object`,
int `$hour`,
int `$minute`,
int `$second` = 0,
int `$microsecond` = 0
): DateTime

Resets the current time of the DateTime object to a different time.

Like DateTimeImmutable::setTime() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`hour`

  Hour of the time.

`minute`

  Minute of the time.

`second`

  Second of the time.

`microsecond`

  Microsecond of the time.

### Return Values

Returns the modified DateTime object for method chaining.

### Changelog

Version | Description
--- | ---
8.1.0 | The behaviour with double existing hours (during the fall-back DST transition) changed. Previously PHP would pick the second occurrence (after the DST transition), instead of the first occurrence (before DST transition).
7.1.0 | The `microsecond` parameter was added.

### See Also

- DateTimeImmutable::setTime() - Sets the time

# DateTime::setTimestamp

# date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::setTimestamp -- date_timestamp_set — Sets the date and time based on an Unix timestamp

### Description

Object-oriented style

public DateTime::setTimestamp(int `$timestamp`): DateTime

Procedural style

date_timestamp_set(DateTime `$object`, int `$timestamp`): DateTime

Sets the date and time based on an Unix timestamp.

Like DateTimeImmutable::setTimestamp() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`timestamp`

  Unix timestamp representing the date. Setting timestamps outside the range of int is possible by using DateTimeImmutable::modify() with the `@` format.

### Return Values

Returns the modified DateTime object for method chaining.

### See Also

- DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp

# DateTime::setTimezone

# date_timezone_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object

### Description

Object-oriented style

public DateTime::setTimezone(DateTimeZone `$timezone`): DateTime

Procedural style

date_timezone_set(DateTime `$object`, DateTimeZone `$timezone`): DateTime

Sets a new timezone for a DateTime object.

Like DateTimeImmutable::setTimezone() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`timezone`

  A DateTimeZone object representing the desired time zone.

### Return Values

Returns the DateTime object for method chaining. The underlaying point-in-time is not changed when calling this method.

### Examples

Example #1 DateTime::setTimeZone() example

Object-oriented style

`<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";`

The above example will output:

    2000-01-01 00:00:00+12:00
    2000-01-01 01:45:00+13:45

Procedural style

`<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";`

The above example will output:

    2000-01-01 00:00:00+12:00
    2000-01-01 01:45:00+13:45

### See Also

- DateTimeImmutable::setTimezone() - Sets the time zone
- DateTime::getTimezone() - Return time zone relative to given DateTime
- DateTimeZone::__construct() - Creates new DateTimeZone object

# DateTime::sub

# date_sub

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

### Description

Object-oriented style

public DateTime::sub(DateInterval `$interval`): DateTime

Procedural style

date_sub(DateTime `$object`, DateInterval `$interval`): DateTime

Modifies the specified DateTime object, by subtracting the specified DateInterval object.

Like DateTimeImmutable::sub() but works with DateTime.

The procedural version takes the DateTime object as its first argument.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`interval`

  A DateInterval object

### Return Values

Returns the modified DateTime object for method chaining.

### Errors/Exceptions

Object Oriented API only: If an unsupported operation is attempted, such as using a DateInterval object representing relative time specifications such as `next weekday`, a DateInvalidOperationException is thrown.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a DateInvalidOperationException with DateTime::sub(), instead of a warning when an unsupported operation is attempted. date_sub() has not been changed.

### See Also

- DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds

## Table of Contents

- DateTime::add — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::__construct — Returns new DateTime object
- DateTime::createFromFormat — Parses a time string according to a specified format
- DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object
- DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object
- DateTime::getLastErrors — Alias of DateTimeImmutable::getLastErrors
- DateTime::modify — Alters the timestamp
- DateTime::__set_state — The __set_state handler
- DateTime::setDate — Sets the date
- DateTime::setISODate — Sets the ISO date
- DateTime::setTime — Sets the time
- DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
- DateTime::setTimezone — Sets the time zone for the DateTime object
- DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

# The DateTimeImmutable class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

Representation of date and time.

This class behaves the same as DateTime except new objects are returned when modification methods such as DateTime::modify() are called.

## Class synopsis

class DateTimeImmutable implements DateTimeInterface {
/* Inherited constants */
public const string DateTimeInterface::ATOM = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
public const string DateTimeInterface::ISO8601 = "Y-m-d\\TH:i:sO";
public const string DateTimeInterface::ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC822 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
public const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC3339 = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string DateTimeInterface::RSS = "D, d M Y H:i:s O";
public const string DateTimeInterface::W3C = "Y-m-d\\TH:i:sP";
/* Methods */
public __construct(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`)
#[\NoDiscard]
public add(DateInterval `$interval`): DateTimeImmutable
public static createFromFormat(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTimeImmutable|false
public static createFromInterface(DateTimeInterface `$object`): DateTimeImmutable
public static createFromMutable(DateTime `$object`): static
public static getLastErrors(): array|false
#[\NoDiscard]
public modify(string `$modifier`): DateTimeImmutable
public static __set_state(array `$array`): DateTimeImmutable
#[\NoDiscard]
public setDate(int `$year`, int `$month`, int `$day`): DateTimeImmutable
#[\NoDiscard]
public setISODate(int `$year`, int `$week`, int `$dayOfWeek` = 1): DateTimeImmutable
#[\NoDiscard]
public setTime(
int `$hour`,
int `$minute`,
int `$second` = 0,
int `$microsecond` = 0
): DateTimeImmutable
#[\NoDiscard]
public setTimestamp(int `$timestamp`): DateTimeImmutable
#[\NoDiscard]
public setTimezone(DateTimeZone `$timezone`): DateTimeImmutable
#[\NoDiscard]
public sub(DateInterval `$interval`): DateTimeImmutable
public diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval
public format(string `$format`): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __serialize(): array
public __unserialize(array `$data`): void
#[\Deprecated]
public __wakeup(): void
}

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
7.1.0 | The DateTimeImmutable constructor now includes the current microseconds in the constructed value. Before this, it would always initialise the microseconds to `0`.

# DateTimeImmutable::add

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds

### Description

#[\NoDiscard]
public DateTimeImmutable::add(DateInterval `$interval`): DateTimeImmutable

Creates a new DateTimeImmutable object, and adds the specified DateInterval object to this, to represent the new value.

### Parameters

`interval`

  A DateInterval object

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Examples

Example #1 DateTimeImmutable::add() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P10D'));
echo $newDate->format('Y-m-d') . "\n";
?>`

Example #2 Further DateTimeImmutable::add() examples

`<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('PT10H30S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>`

The above example will output:

    2000-01-01 10:00:30
    2007-06-05 04:03:02

Example #3 Beware when adding months

`<?php
$date = new DateTimeImmutable('2000-12-31');
$interval = new DateInterval('P1M');
$newDate1 = $date->add($interval);
echo $newDate1->format('Y-m-d') . "\n";
$newDate2 = $newDate1->add($interval);
echo $newDate2->format('Y-m-d') . "\n";
?>`

The above example will output:

    2001-01-31
    2001-03-03

### See Also

- DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
- DateTimeImmutable::diff() - Returns the difference between two DateTime objects
- DateTimeImmutable::modify() - Creates a new object with modified timestamp

# DateTimeImmutable::__construct

# date_create_immutable

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object

### Description

Object-oriented style

public DateTimeImmutable::__construct(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`)

Procedural style

date_create_immutable(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`): DateTimeImmutable|false

Returns new a DateTimeImmutable object.

### Parameters

`datetime`

  A date/time string. Valid formats are explained in Date and Time Formats.

  Enter `"now"` here to obtain the current time when using the `$timezone` parameter.

`timezone`

  A DateTimeZone object representing the timezone of `$datetime`.

  If `$timezone` is omitted or `null`, the current timezone will be used.

  > Note:

  > The `$timezone` parameter and the current timezone are ignored when the `$datetime` parameter either is a UNIX timestamp (e.g. `@946684800`) or specifies a timezone (e.g. `2010-01-28T15:00:00+02:00`, or `2010-07-05T06:00:00Z`).

### Return Values

Returns a new DateTimeImmutable instance.

### Errors/Exceptions

If an invalid Date/Time string is passed, DateMalformedStringException is thrown. Previous to PHP 8.3, this was Exception.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws DateMalformedStringException if an invalid string is passed, instead of Exception.
7.1.0 | From now on microseconds are filled with actual value. Not with '00000'.

### Examples

Example #1 DateTimeImmutable::__construct() example

Object-oriented style

`<?php
try {
$date = new DateTimeImmutable('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
echo $date->format('Y-m-d');`

The above example will output:

    2000-01-01

Procedural style

`<?php
$date = date_create('2000-01-01');
if (!$date) {
$e = date_get_last_errors();
foreach ($e['errors'] as $error) {
echo "$error\n";
}
exit(1);
}
echo date_format($date, 'Y-m-d');`

The above example will output:

    2000-01-01

Example #2 Intricacies of DateTimeImmutable::__construct()

`<?php
date_default_timezone_set('America/Jamaica');
// Specified date/time in PHP's default time zone.
$date = new DateTimeImmutable('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTimeImmutable('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your PHP's default time zone.
$date = new DateTimeImmutable();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTimeImmutable('now', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTimeImmutable('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTimeImmutable('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";`

The above example will output something similar to:

    2000-01-01 00:00:00-05:00
    2000-01-01 00:00:00+12:00
    2010-04-24 10:24:16-04:00
    2010-04-25 02:24:16+12:00
    2000-01-01 00:00:00+00:00
    2000-03-01 00:00:00-05:00

> Note:

> Rolled over dates can be detected by checking for warnings using DateTimeImmutable::getLastErrors().

Example #3 Changing the associated timezone

`<?php
$timeZone = new \DateTimeZone('Asia/Tokyo');
$time = new \DateTimeImmutable();
$time = $time->setTimezone($timeZone);
echo $time->format('Y/m/d H:i:s e'), "\n";`

The above example will output something similar to:

    2022/08/12 23:49:23 Asia/Tokyo

Example #4 Using a relative date/time string

`<?php
$time = new \DateTimeImmutable("-1 year");
echo $time->format('Y/m/d H:i:s'), "\n";`

The above example will output something similar to:

    2021/08/12 15:43:51

# DateTimeImmutable::createFromFormat

# date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Parses a time string according to a specified format

### Description

Object-oriented style

public static DateTimeImmutable::createFromFormat(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTimeImmutable|false

Procedural style

date_create_immutable_from_format(string `$format`, string `$datetime`, ?DateTimeZone `$timezone` = `null`): DateTimeImmutable|false

Returns a new DateTimeImmutable object representing the date and time specified by the `datetime` string, which was formatted in the given `format`.

### Parameters

`format`

  The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

  All fields are initialised with the current date/time. In most cases you would want to reset these to "zero" (the Unix epoch, `1970-01-01 00:00:00 UTC`). You do that by including the `!` character as first character in your `format`, or `|` as your last. Please see the documentation for each character below for more information.

  The format is parsed from left to right, which means that in some situations the order in which the format characters are present affects the result. In the case of `z` (the day of the year), it is required that a year has already been parsed, for example through the `Y` or `y` characters.

  Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be. For example, the `d` (day of the month) accepts values in the range from `00` to `99`. The only constraint is on the amount of digits. The date/time parser's overflow mechanism is used when out-of-range values are given. The examples below show some of this behaviour.

  This also means that the data parsed for a format letter is greedy, and will read up to the amount of digits its format allows for. That can then also mean that there are no longer enough characters in the `datetime` string for following format characters. An example on this page also illustrates this issue.

  The following characters are recognized in the `format` parameter string
  `format` character | Description | Example parsable values
  --- | --- | ---
  Day | --- | ---
  `d` and `j` | Day of the month, 2 digits with or without leading zeros | `01` to `31` or `1` to `31`. (2 digit numbers higher than the number of days in the month are accepted, in which case they will make the month overflow. For example using 33 with January, means February 2nd)
  `D` and `l` | A textual representation of a day | `Mon` through `Sun` or `Sunday` through `Saturday`. If the day name given is different then the day name belonging to a parsed (or default) date is different, then an overflow occurs to the next date with the given day name. See the examples below for an explanation.
  `S` | English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. | `st`, `nd`, `rd` or `th`.
  `z` | The day of the year (starting from 0); must be preceded by `Y` or `y`. | `0` through `365`. (3 digit numbers higher than the numbers in a year are accepted, in which case they will make the year overflow. For example using 366 with 2022, means January 2nd, 2023)
  Month | --- | ---
  `F` and `M` | A textual representation of a month, such as January or Sept | `January` through `December` or `Jan` through `Dec`
  `m` and `n` | Numeric representation of a month, with or without leading zeros | `01` through `12` or `1` through `12`. (2 digit numbers higher than 12 are accepted, in which case they will make the year overflow. For example using 13 means January in the next year)
  Year | --- | ---
  `X` and `x` | A full numeric representation of a year, up to 19 digits, optionally prefixed by `+` or `-` | Examples: `0055`, `787`, `1999`, `-2003`, `+10191`
  `Y` | A full numeric representation of a year, up to 4 digits | Examples: `25` (same as `0025`), `787`, `1999`, `2003`
  `y` | A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) | Examples: `99` or `03` (which will be interpreted as `1999` and `2003`, respectively)
  Time | --- | ---
  `a` and `A` | Ante meridiem and Post meridiem | `am` or `pm`
  `g` and `h` | 12-hour format of an hour with or without leading zero | `1` through `12` or `01` through `12` (2 digit numbers higher than 12 are accepted, in which case they will make the day overflow. For example using `14` means `02` in the next AM/PM period)
  `G` and `H` | 24-hour format of an hour with or without leading zeros | `0` through `23` or `00` through `23` (2 digit numbers higher than 24 are accepted, in which case they will make the day overflow. For example using `26` means `02:00` the next day)
  `i` | Minutes with leading zeros | `00` to `59`. (2 digit numbers higher than 59 are accepted, in which case they will make the hour overflow. For example using `66` means `:06` the next hour)
  `s` | Seconds, with leading zeros | `00` through `59` (2 digit numbers higher than 59 are accepted, in which case they will make the minute overflow. For example using `90` means `:30` the next minute)
  `v` | Fraction in milliseconds (up to three digits) | Example: `12` (`0.12` seconds), `345` (`0.345` seconds)
  `u` | Fraction in microseconds (up to six digits) | Example: `45` (`0.45` seconds), `654321` (`0.654321` seconds)
  Timezone | --- | ---
  `e`, `O`, `p`, `P` and `T` | Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: `UTC`, `GMT`, `Atlantic/Azores` or `+0200` or `+02:00` or `EST`, `MDT`
  Full Date/Time | --- | ---
  `U` | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: `1292177455`
  Whitespace and Separators | --- | ---
  `` (space) | Zero or more spaces, tabs, NBSP (U+A0), or NNBSP (U+202F) characters | Example: `"\t"`, `" "`
  `#` | One of the following separation symbol: `;`, `:`, `/`, `.`, `,`, `-`, `(` or `)` | Example: `/`
  `;`, `:`, `/`, `.`, `,`, `-`, `(` or `)` | The specified character. | Example: `-`
  `?` | A random byte | Example: `^` (Be aware that for UTF-8 characters you might need more than one `?`. In this case, using `*` is probably what you want instead)
  `*` | Random bytes until the next separator or digit | Example: `*` in `Y-*-d` with the string `2009-aWord-08` will match `aWord`
  `!` | Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values ( `0` for hour, minute, second and fraction, `1` for month and day, `1970` for year and the default timezone) | Without `!,` all fields will be set to the current date and time.
  `|` | Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values if they have not been parsed yet | `Y-m-d|` will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0.
  `+` | If this format specifier is present, trailing data in the string will not cause an error, but a warning instead | Use DateTimeImmutable::getLastErrors() to find out whether trailing data was present.

  Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTimeImmutable::getLastErrors().

  To include literal characters in `format`, you have to escape them with a backslash (`\`).

  If `format` does not contain the character `!` then portions of the generated date/time which are not specified in `format` will be set to the current system time.

  If `format` contains the character `!`, then portions of the generated date/time not provided in `format`, as well as values to the left-hand side of the `!`, will be set to corresponding values from the Unix epoch.

  If any time character is parsed, then all other time-related fields are set to "0", unless also parsed.

  The Unix epoch is 1970-01-01 00:00:00 UTC.

`datetime`

  String representing the time.

`timezone`

  A DateTimeZone object representing the desired time zone.

  If `timezone` is omitted or `null` and `datetime` contains no timezone, the current timezone will be used.

  > Note:

  > The `timezone` parameter and the current timezone are ignored when the `datetime` parameter either contains a UNIX timestamp (e.g. `946684800`) or specifies a timezone (e.g. `2010-01-28T15:00:00+02:00`).

### Return Values

Returns a new DateTimeImmutable instance or `false` on failure.

### Errors/Exceptions

This method throws ValueError when the `datetime` contains NULL-bytes.

### Changelog

Version | Description
--- | ---
8.2.9 | The `` (space) specifier now also supports NBSP (U+A0) and NNBSP (U+202F) characters.
8.2.0 | The `X` and `x` `format` specifiers have been added.
8.0.21, 8.1.8, 8.2.0 | Now throws ValueError when NULL-bytes are passed into `datetime`, which previously was silently ignored.
7.3.0 | The `v` `format` specifier has been added.

### Examples

Example #1 DateTimeImmutable::createFromFormat() example

Object-oriented style

`<?php
$date = DateTimeImmutable::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');`

Example #2 Using predefined format constants with DateTimeImmutable::createFromFormat()

Object-oriented style

`<?php
$date = DateTimeImmutable::createFromFormat(
DateTimeInterface::ISO8601,
'2004-02-12T15:19:21+00:00'
);
echo $date->format('c e') . "\n";
$date = DateTimeImmutable::createFromFormat(
DateTimeInterface::RFC3339_EXTENDED,
'2013-10-14T09:00:00.000+02:00'
);
echo $date->format('c e') . "\n";`

The formatting constants as used in this example consist of a string of characters for formatting a DateTimeImmutable object. In most cases, these letters match with the same elements of date/time information as the ones defined in the parameters section above, but they tend to be more lenient.

Example #3 Intricacies of DateTimeImmutable::createFromFormat()

`<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d H:i:s';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-!d H:i:s';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = '!d';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'i';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";`

The above example will output something similar to:

    Current time: 2022-06-02 15:50:46
    Format: Y-m-d; 2009-02-15 15:50:46
    Format: Y-m-d H:i:s; 2009-02-15 15:16:17
    Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
    Format: !d; 1970-01-15 00:00:00
    Format: i; 2022-06-02 00:15:00

Example #4 Format string with literal characters

`<?php
echo DateTimeImmutable::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');`

The above example will output something similar to:

    23:15:03

Example #5 Overflow behaviour

`<?php
echo DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97')->format(DateTimeImmutable::RFC2822);`

The above example will output something similar to:

    Sat, 04 Jun 2022 17:01:37 +0000

Although the result looks odd, it is correct, as the following overflows happen:

1. `97` seconds overflows to `1` minute, leaving `37` seconds.
2. `61` minutes overflows to `1` hour, leaving `1` minutes.
3. `35` days overflows to `1` month, leaving `4` days. The amount of days that are left over depends on the month, as not every month has the same amount of days.
4. `18` months overflows to `1` year, leaving `6` months.

Example #6 Overflowing day name behaviour

`<?php
$d = DateTime::createFromFormat(DateTimeInterface::RFC1123, 'Mon, 3 Aug 2020 25:00:00 +0000');
echo $d->format(DateTime::RFC1123), "\n";`

The above example will output something similar to:

    Mon, 10 Aug 2020 01:00:00 +0000

Although the result looks odd, it is correct, as the following overflows happen:

1. `3 Aug 2020 25:00:00` overflows to `(Tue) 4 Aug 2020 01:00`.
2. `Mon` gets applied, which advances the date to `Mon, 10 Aug 2020 01:00:00`. The explanation of relative keywords such as `Mon` is explained in the section on relative formats.

In order to detect overflows in dates, you can use DateTimeImmutable::getLastErrors(), which will include a warning if an overflow occurred.

Example #7 Detecting overflown dates

`<?php
$d = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97');
echo $d->format(DateTimeImmutable::RFC2822), "\n\n";
var_dump(DateTimeImmutable::getLastErrors());`

The above example will output something similar to:

    Sat, 04 Jun 2022 17:01:37 +0000

    array(4) {
      'warning_count' =>
      int(2)
      'warnings' =>
      array(1) {
        [19] =>
        string(27) "The parsed date was invalid"
      }
      'error_count' =>
      int(0)
      'errors' =>
      array(0) {
      }
    }

Example #8 Greedy parsing behaviour

`<?php
print_r(date_parse_from_format('Gis', '60101'));`

The above example will output something similar to:

    Array
    (
        [year] =>
        [month] =>
        [day] =>
        [hour] => 60
        [minute] => 10
        [second] => 0
        [fraction] => 0
        [warning_count] => 1
        [warnings] => Array
            (
                [5] => The parsed time was invalid
            )

        [error_count] => 1
        [errors] => Array
            (
                [4] => A two digit second could not be found
            )

        [is_localtime] =>
    )

The `G` format is to parse 24 hour clock hours, with or without leading zero. This requires to parse 1 or 2 digits. Because there are two following digits, it greedily reads this as `60`.

The following `i` and `s` format characters both require two digits. This means that `10` is passed as minute (`i`), and that there are then not enough digits left to parse for as second (`s`).

The `errors` array indicates this problem.

Additionally, an hour of `60` is outside the range `0`-`24`, which causes the `warnings` array to include a warning that the time is invalid.

### See Also

- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
- DateTimeImmutable::getLastErrors() - Returns the warnings and errors
- checkdate() - Validate a Gregorian date
- strptime() - Parse a time/date generated with strftime

# DateTimeImmutable::createFromInterface

(PHP 8)

DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

### Description

public static DateTimeImmutable::createFromInterface(DateTimeInterface `$object`): DateTimeImmutable

### Parameters

`object`

  The DateTimeInterface object that needs to be converted to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date, time, and timezone information.

### Return Values

Returns a new DateTimeImmutable instance.

### Examples

Example #1 Creating an immutable date time object

`<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");
$immutable = DateTimeImmutable::createFromInterface($date);
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$also_immutable = DateTimeImmutable::createFromInterface($date);`

# DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object

### Description

public static DateTimeImmutable::createFromMutable(DateTime `$object`): static

### Parameters

`object`

  The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable instance is created containing the same date time and timezone information.

### Return Values

Returns a new DateTimeImmutable instance.

### Changelog

Version | Description
--- | ---
8.0.0 | The method returns an instance of the currently invoked class now. Previously, it created a new instance of DateTimeImmutable.

### Examples

Example #1 Creating an immutable date time object

`<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");
$immutable = DateTimeImmutable::createFromMutable( $date );`

# DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::getLastErrors — Returns the warnings and errors

### Description

public static DateTimeImmutable::getLastErrors(): array|false

Returns an array of warnings and errors found while parsing a date/time string.

### Parameters

This function has no parameters.

### Return Values

Returns array containing info about warnings and errors, or `false` if there are neither warnings nor errors.

### Changelog

Version | Description
--- | ---
8.2.0 | Before PHP 8.2.0, this function did not return `false` when there were no warnings or errors. Instead, it would always return the documented array structure.

### Examples

Example #1 DateTimeImmutable::getLastErrors() example

`<?php
try {
$date = new DateTimeImmutable('asdfasdf');
} catch (Exception $e) {
// For demonstration purposes only...
print_r(DateTimeImmutable::getLastErrors());
// The real object-oriented way to do this is
echo $e->getMessage();
}
?>`

The above example will output:

    Array
    (
        [warning_count] => 1
        [warnings] => Array
            (
                [6] => Double timezone specification
            )

        [error_count] => 1
        [errors] => Array
            (
                [0] => The timezone could not be found in the database
            )
    )
    Failed to parse time string (asdfasdf) at position 0 (a): The timezone could not be found in the database

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.

Example #2 Detecting rolled over dates

`<?php
$date = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-02-30');
print_r(DateTimeImmutable::getLastErrors());`

The above example will output:

    Array
    (
        [warning_count] => 1
        [warnings] => Array
            (
                [10] => The parsed date was invalid
            )

        [error_count] => 0
        [errors] => Array
            (
            )
    )

# DateTimeImmutable::modify

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::modify — Creates a new object with modified timestamp

### Description

#[\NoDiscard]
public DateTimeImmutable::modify(string `$modifier`): DateTimeImmutable

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

### Parameters

`modifier`

  A date/time string. Valid formats are explained in Date and Time Formats.

### Return Values

Returns DateTimeImmutable on success. Procedural style returns `false` on failure.

### Errors/Exceptions

If an invalid Date/Time string is passed, DateMalformedStringException is thrown. Previous to PHP 8.3, this was a warning.

### Changelog

Version | Description
--- | ---
8.3.0 | DateTimeImmutable::modify() now throws DateMalformedStringException if an invalid string is passed. Previously, it returned `false`, and a warning was emitted.

### Examples

Example #1 DateTimeImmutable::modify() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2006-12-12');
$newDate = $date->modify('+1 day');
echo $newDate->format('Y-m-d');`

The above example will output:

    2006-12-13

Example #2 Beware when adding or subtracting months

`<?php
$date = new DateTimeImmutable('2000-12-31');
$newDate1 = $date->modify('+1 month');
echo $newDate1->format('Y-m-d') . "\n";
$newDate2 = $newDate1->modify('+1 month');
echo $newDate2->format('Y-m-d') . "\n";`

The above example will output:

    2001-01-31
    2001-03-03

### See Also

- DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds
- DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
- DateTimeImmutable::setDate() - Sets the date
- DateTimeImmutable::setISODate() - Sets the ISO date
- DateTimeImmutable::setTime() - Sets the time
- DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp

# DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::__set_state — The __set_state handler

### Description

public static DateTimeImmutable::__set_state(array `$array`): DateTimeImmutable

The __set_state() handler.

### Parameters

`array`

  Initialization array.

### Return Values

Returns a new instance of a DateTimeImmutable object.

# DateTimeImmutable::setDate

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setDate — Sets the date

### Description

#[\NoDiscard]
public DateTimeImmutable::setDate(int `$year`, int `$month`, int `$day`): DateTimeImmutable

Returns a new DateTimeImmutable object with the current date of the DateTimeImmutable object set to the given date.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

`year`

  Year of the date.

`month`

  Month of the date.

`day`

  Day of the date.

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Examples

Example #1 DateTimeImmutable::setDate() example

Object-oriented style

`<?php
$date = new DateTimeImmutable();
$newDate = $date->setDate(2001, 2, 3);
echo $newDate->format('Y-m-d');`

The above example will output:

    2001-02-03

Example #2 Values exceeding ranges are added to their parent values

`<?php
$date = new DateTimeImmutable();
$newDate = $date->setDate(2001, 2, 28);
echo $newDate->format('Y-m-d') . "\n";
$newDate = $date->setDate(2001, 2, 29);
echo $newDate->format('Y-m-d') . "\n";
$newDate = $date->setDate(2001, 14, 3);
echo $newDate->format('Y-m-d') . "\n";`

The above example will output:

    2001-02-28
    2001-03-01
    2002-02-03

### See Also

- DateTimeImmutable::setISODate() - Sets the ISO date
- DateTimeImmutable::setTime() - Sets the time

# DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setISODate — Sets the ISO date

### Description

#[\NoDiscard]
public DateTimeImmutable::setISODate(int `$year`, int `$week`, int `$dayOfWeek` = 1): DateTimeImmutable

Returns a new DateTimeImmutable object with the date set according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

### Parameters

`year`

  Year of the date.

`week`

  Week of the date.

`dayOfWeek`

  Offset from the first day of the week.

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Examples

Example #1 DateTimeImmutable::setISODate() example

Object-oriented style

`<?php
$date = new DateTimeImmutable();
$newDate = $date->setISODate(2008, 2);
echo $newDate->format('Y-m-d') . "\n";
$newDate = $date->setISODate(2008, 2, 7);
echo $newDate->format('Y-m-d') . "\n";`

The above example will output:

    2008-01-07
    2008-01-13

Procedural style

`<?php
$date = date_create();
date_isodate_set($date, 2008, 2);
echo date_format($date, 'Y-m-d') . "\n";
date_isodate_set($date, 2008, 2, 7);
echo date_format($date, 'Y-m-d') . "\n";`

The above example will output:

    2008-01-07
    2008-01-13

Example #2 Values exceeding ranges are added to their parent values

`<?php
$date = new DateTimeImmutable();
$newDate = $date->setISODate(2008, 2, 7);
echo $newDate->format('Y-m-d') . "\n";
$newDate = $date->setISODate(2008, 2, 8);
echo $newDate->format('Y-m-d') . "\n";
$newDate = $date->setISODate(2008, 53, 7);
echo $newDate->format('Y-m-d') . "\n";`

The above example will output:

    2008-01-13
    2008-01-14
    2009-01-04

Example #3 Finding the month a week is in

`<?php
$date = new DateTimeImmutable();
$newDate = $date->setISODate(2008, 14);
echo $newDate->format('n');`

The above example will output:

    3

### See Also

- DateTimeImmutable::setDate() - Sets the date
- DateTimeImmutable::setTime() - Sets the time

# DateTimeImmutable::setTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTime — Sets the time

### Description

#[\NoDiscard]
public DateTimeImmutable::setTime(
int `$hour`,
int `$minute`,
int `$second` = 0,
int `$microsecond` = 0
): DateTimeImmutable

Returns a new DateTimeImmutable object with the time set to the given time.

### Parameters

`hour`

  Hour of the time.

`minute`

  Minute of the time.

`second`

  Second of the time.

`microsecond`

  Microsecond of the time.

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Changelog

Version | Description
--- | ---
8.1.0 | The behaviour with double existing hours (during the fall-back DST transition) changed. Previously PHP would pick the second occurrence (after the DST transition), instead of the first occurrence (before DST transition).
7.1.0 | The `microsecond` parameter was added.

### Examples

Example #1 DateTimeImmutable::setTime() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2001-01-01');
$newDate = $date->setTime(14, 55);
echo $newDate->format('Y-m-d H:i:s') . "\n";
$newDate = $date->setTime(14, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>`

The above example will output something similar to:

    2001-01-01 14:55:00
    2001-01-01 14:55:24

Example #2 Values exceeding ranges are added to their parent values

`<?php
$date = new DateTimeImmutable('2001-01-01');
$newDate = $date->setTime(14, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
$newDate = $date->setTime(14, 55, 65);
echo $newDate->format('Y-m-d H:i:s') . "\n";
$newDate = $date->setTime(14, 65, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
$newDate = $date->setTime(25, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>`

The above example will output:

    2001-01-01 14:55:24
    2001-01-01 14:56:05
    2001-01-01 15:05:24
    2001-01-02 01:55:24

### See Also

- DateTimeImmutable::setDate() - Sets the date
- DateTimeImmutable::setISODate() - Sets the ISO date

# DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp

### Description

#[\NoDiscard]
public DateTimeImmutable::setTimestamp(int `$timestamp`): DateTimeImmutable

Returns a new DateTimeImmutable object constructed from the old one, with the date and time set based on an Unix timestamp.

### Parameters

`timestamp`

  Unix timestamp representing the date. Setting timestamps outside the range of int is possible by using DateTimeImmutable::modify() with the `@` format.

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Examples

Example #1 DateTimeImmutable::setTimestamp() example

Object-oriented style

`<?php
$date = new DateTimeImmutable();
echo $date->format('U = Y-m-d H:i:s') . "\n";
$newDate = $date->setTimestamp(1171502725);
echo $newDate->format('U = Y-m-d H:i:s') . "\n";`

The above example will output something similar to:

    1272508903 = 2010-04-28 22:41:43
    1171502725 = 2007-02-14 20:25:25

### See Also

- DateTimeImmutable::getTimestamp() - Gets the Unix timestamp

# DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTimezone — Sets the time zone

### Description

#[\NoDiscard]
public DateTimeImmutable::setTimezone(DateTimeZone `$timezone`): DateTimeImmutable

Returns a new DateTimeImmutable object with a new timezone set.

### Parameters

`timezone`

  A DateTimeZone object representing the desired time zone.

### Return Values

Returns a new modified DateTimeImmutable object for method chaining. The underlaying point-in-time is not changed when calling this method.

### Examples

Example #1 DateTimeImmutable::setTimeZone() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$newDate = $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $newDate->format('Y-m-d H:i:sP') . "\n";
?>`

The above example will output:

    2000-01-01 00:00:00+12:00
    2000-01-01 01:45:00+13:45

### See Also

- DateTimeImmutable::getTimezone() - Return time zone relative to given DateTime
- DateTimeZone::__construct() - Creates new DateTimeZone object

# DateTimeImmutable::sub

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

### Description

#[\NoDiscard]
public DateTimeImmutable::sub(DateInterval `$interval`): DateTimeImmutable

Returns a new DateTimeImmutable object, with the specified DateInterval object subtracted from the specified DateTimeImmutable object.

### Parameters

`interval`

  A DateInterval object

### Return Values

Returns a new DateTimeImmutable object with the modified data.

### Errors/Exceptions

If an unsupported operation is attempted, such as using a DateInterval object representing relative time specifications such as `next weekday`, a DateInvalidOperationException is thrown.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws a DateInvalidOperationException instead of a warning when an unsupported operation is attempted.

### Examples

Example #1 DateTimeImmutable::sub() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('P10D'));
echo $newDate->format('Y-m-d') . "\n";
?>`

The above example will output:

    2000-01-10

Example #2 Further DateTimeImmutable::sub() examples

`<?php
$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('PT10H30S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>`

The above example will output:

    2000-01-19 13:59:30
    1992-08-15 19:56:58

Example #3 Beware when subtracting months

`<?php
$date = new DateTimeImmutable('2001-04-30');
$interval = new DateInterval('P1M');
$newDate1 = $date->sub($interval);
echo $newDate1->format('Y-m-d') . "\n";
$newDate2 = $newDate1->sub($interval);
echo $newDate2->format('Y-m-d') . "\n";
?>`

The above example will output:

    2001-03-30
    2001-03-02

### See Also

- DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds
- DateTimeImmutable::diff() - Returns the difference between two DateTime objects
- DateTimeImmutable::modify() - Creates a new object with modified timestamp

## Table of Contents

- DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
- DateTimeImmutable::__construct — Returns new DateTimeImmutable object
- DateTimeImmutable::createFromFormat — Parses a time string according to a specified format
- DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
- DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object
- DateTimeImmutable::getLastErrors — Returns the warnings and errors
- DateTimeImmutable::modify — Creates a new object with modified timestamp
- DateTimeImmutable::__set_state — The __set_state handler
- DateTimeImmutable::setDate — Sets the date
- DateTimeImmutable::setISODate — Sets the ISO date
- DateTimeImmutable::setTime — Sets the time
- DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp
- DateTimeImmutable::setTimezone — Sets the time zone
- DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

# The DateTimeInterface interface

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

DateTimeInterface was created so that parameter, return, or property type declarations may accept either DateTimeImmutable or DateTime as a value. It is not possible to implement this interface with userland classes.

Common constants that allow for formatting DateTimeImmutable or DateTime objects through DateTimeImmutable::format() and DateTime::format() are also defined on this interface.

## Interface synopsis

interface DateTimeInterface {
/* Constants */
public const string ATOM = "Y-m-d\\TH:i:sP";
public const string COOKIE = "l, d-M-Y H:i:s T";
public const string ISO8601 = "Y-m-d\\TH:i:sO";
public const string ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string RFC822 = "D, d M y H:i:s O";
public const string RFC850 = "l, d-M-y H:i:s T";
public const string RFC1036 = "D, d M y H:i:s O";
public const string RFC1123 = "D, d M Y H:i:s O";
public const string RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string RFC2822 = "D, d M Y H:i:s O";
public const string RFC3339 = "Y-m-d\\TH:i:sP";
public const string RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string RSS = "D, d M Y H:i:s O";
public const string W3C = "Y-m-d\\TH:i:sP";
/* Methods */
public diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval
public format(string `$format`): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __serialize(): array
public __unserialize(array `$data`): void
#[\Deprecated]
public __wakeup(): void
}

## Predefined Constants

`DateTimeInterface::ATOM` string
`DATE_ATOM`
  Atom (example: 2005-08-15T15:52:01+00:00); compatible with ISO-8601, RFC 3339, and XML Schema
`DateTimeInterface::COOKIE` string
`DATE_COOKIE`
  HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC)
`DateTimeInterface::ISO8601` string
`DATE_ISO8601`
  ISO-8601-like (example: 2005-08-15T15:52:01+0000)

  > Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use `DateTimeInterface::ISO8601_EXPANDED`, `DateTimeInterface::ATOM` for compatibility with ISO-8601 instead. (ref ISO8601:2004 section 4.3.3 clause d)

`DateTimeInterface::ISO8601_EXPANDED` string
`DATE_ISO8601_EXPANDED`
  ISO-8601 Expanded (example: +10191-07-26T08:59:52+01:00)

  > Note: This format allows for year ranges outside of ISO-8601's normal range of `0000`-`9999` by always including a sign character. It also ensures that the timezone part (`+01:00`) is compatible with ISO-8601.

`DateTimeInterface::RFC822` string
`DATE_RFC822`
  RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
`DateTimeInterface::RFC850` string
`DATE_RFC850`
  RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
`DateTimeInterface::RFC1036` string
`DATE_RFC1036`
  RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
`DateTimeInterface::RFC1123` string
`DATE_RFC1123`
  RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
`DateTimeInterface::RFC7231` string
`DATE_RFC7231`
  RFC 7231 (since PHP 7.0.19 and 7.1.5) (example: Sat, 30 Apr 2016 17:52:13 GMT)
`DateTimeInterface::RFC2822` string
`DATE_RFC2822`
  RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000)
`DateTimeInterface::RFC3339` string
`DATE_RFC3339`
  Same as `DATE_ATOM`
`DateTimeInterface::RFC3339_EXTENDED` string
`DATE_RFC3339_EXTENDED`
  RFC 3339 EXTENDED format (example: 2005-08-15T15:52:01.000+00:00)
`DateTimeInterface::RSS` string
`DATE_RSS`
  RSS (example: Mon, 15 Aug 2005 15:52:01 +0000)
`DateTimeInterface::W3C` string
`DATE_W3C`
  World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

## Changelog

Version | Description
--- | ---
8.5.0 | The `DATE_RFC7231` and `DateTimeInterface::RFC7231` constants have been deprecated.
8.4.0 | The class constants are now typed.
8.2.0 | The constant `DateTimeInterface::ISO8601_EXPANDED` was added.
7.2.0 | The class constants of DateTime are now defined on DateTimeInterface.

# DateTimeInterface::diff

# DateTimeImmutable::diff

# DateTime::diff

# date_diff

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeInterface::diff -- DateTimeImmutable::diff -- DateTime::diff -- date_diff — Returns the difference between two DateTime objects

### Description

Object-oriented style

public DateTimeInterface::diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval
public DateTimeImmutable::diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval
public DateTime::diff(DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval

Procedural style

date_diff(DateTimeInterface `$baseObject`, DateTimeInterface `$targetObject`, bool `$absolute` = `false`): DateInterval

Returns the difference between two DateTimeInterface objects.

### Parameters

`datetime`

  The date to compare to.

`absolute`

  Should the interval be forced to be positive?

### Return Values

The DateInterval object represents the difference between the two dates.

The `absolute` parameter only affects the `invert` property of a DateInterval object.

The return value more specifically represents the clock-time interval to apply to the original object (`$this` or `$originObject`) to arrive at the `$targetObject`. This process is not always reversible.

The method is aware of DST changeovers, and hence can return an interval of `24 hours and 30 minutes`, as per one of the examples. If you want to calculate with absolute time, you need to convert both the `$this`/`$baseObject`, and `$targetObject` to UTC first.

### Examples

Example #1 DateTimeImmutable::diff() example

Object-oriented style

`<?php
$origin = new DateTimeImmutable('2009-10-11');
$target = new DateTimeImmutable('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');`

The above example will output:

    +2 days

Procedural style

`<?php
$origin = date_create('2009-10-11');
$target = date_create('2009-10-13');
$interval = date_diff($origin, $target);
echo $interval->format('%R%a days');`

The above example will output:

    +2 days

Example #2 DateTimeInterface::diff() during DST changeover

`<?php
$originalTime = new DateTimeImmutable("2021-10-30 09:00:00 Europe/London");
$targetTime = new DateTimeImmutable("2021-10-31 08:30:00 Europe/London");
$interval = $originalTime->diff($targetTime);
echo $interval->format("%H:%I:%S (Full days: %a)"), "\n";`

The above example will output:

    24:30:00 (Full days: 0)

Example #3 DateTimeInterface::diff() range

The value that the method returns is the exact amount of time to get from `$this` to `$targetObject`. Comparing January 1st to December 31st returns therefore 364, and not 365, days (for non-leap years).

`<?php
$originalTime = new DateTimeImmutable("2023-01-01 UTC");
$targetTime = new DateTimeImmutable("2023-12-31 UTC");
$interval = $originalTime->diff($targetTime);
echo "Full days: ", $interval->format("%a"), "\n";`

The above example will output:

    Full days: 364

Example #4 DateTime object comparison

> Note:

> DateTimeImmutable and DateTime objects can be compared using comparison operators.

`<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);`

The above example will output:

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

### See Also

- DateInterval::format() - Formats the interval
- DateTime::add() - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

# DateTimeInterface::format

# DateTimeImmutable::format

# DateTime::format

# date_format

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::format -- DateTimeImmutable::format -- DateTime::format -- date_format — Returns date formatted according to given format

### Description

Object-oriented style

public DateTimeInterface::format(string `$format`): string
public DateTimeImmutable::format(string `$format`): string
public DateTime::format(string `$format`): string

Procedural style

date_format(DateTimeInterface `$object`, string `$format`): string

Returns date formatted according to given format.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create()

`format`

  The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example `DATE_RSS` contains the format string `'D, d M Y H:i:s'`.

  The following characters are recognized in the `format` parameter string
  `format` character | Description | Example returned values
  --- | --- | ---
  Day | --- | ---
  `d` | Day of the month, 2 digits with leading zeros | `01` to `31`
  `D` | A textual representation of a day, three letters | `Mon` through `Sun`
  `j` | Day of the month without leading zeros | `1` to `31`
  `l` (lowercase 'L') | A full textual representation of the day of the week | `Sunday` through `Saturday`
  `N` | ISO 8601 numeric representation of the day of the week | `1` (for Monday) through `7` (for Sunday)
  `S` | English ordinal suffix for the day of the month, 2 characters | `st`, `nd`, `rd` or `th`. Works well with `j`
  `w` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday)
  `z` | The day of the year (starting from 0) | `0` through `365`
  Week | --- | ---
  `W` | ISO 8601 week number of year, weeks starting on Monday | Example: `42` (the 42nd week in the year)
  Month | --- | ---
  `F` | A full textual representation of a month, such as January or March | `January` through `December`
  `m` | Numeric representation of a month, with leading zeros | `01` through `12`
  `M` | A short textual representation of a month, three letters | `Jan` through `Dec`
  `n` | Numeric representation of a month, without leading zeros | `1` through `12`
  `t` | Number of days in the given month | `28` through `31`
  Year | --- | ---
  `L` | Whether it's a leap year | `1` if it is a leap year, `0` otherwise.
  `o` | ISO 8601 week-numbering year. This has the same value as `Y`, except that if the ISO week number (`W`) belongs to the previous or next year, that year is used instead. | Examples: `1999` or `2003`
  `X` | An expanded full numeric representation of a year, at least 4 digits, with `-` for years BCE, and `+` for years CE. | Examples: `-0055`, `+0787`, `+1999`, `+10191`
  `x` | An expanded full numeric representation if required, or a standard full numeral representation if possible (like `Y`). At least four digits. Years BCE are prefixed with a `-`. Years beyond (and including) `10000` are prefixed by a `+`. | Examples: `-0055`, `0787`, `1999`, `+10191`
  `Y` | A full numeric representation of a year, at least 4 digits, with `-` for years BCE. | Examples: `-0055`, `0787`, `1999`, `2003`, `10191`
  `y` | A two digit representation of a year | Examples: `99` or `03`
  Time | --- | ---
  `a` | Lowercase Ante meridiem and Post meridiem | `am` or `pm`
  `A` | Uppercase Ante meridiem and Post meridiem | `AM` or `PM`
  `B` | Swatch Internet time | `000` through `999`
  `g` | 12-hour format of an hour without leading zeros | `1` through `12`
  `G` | 24-hour format of an hour without leading zeros | `0` through `23`
  `h` | 12-hour format of an hour with leading zeros | `01` through `12`
  `H` | 24-hour format of an hour with leading zeros | `00` through `23`
  `i` | Minutes with leading zeros | `00` to `59`
  `s` | Seconds with leading zeros | `00` through `59`
  `u` | Microseconds. Note that date() will always generate `000000` since it takes an int parameter, whereas DateTimeInterface::format() does support microseconds if an object of type DateTimeInterface was created with microseconds. | Example: `654321`
  `v` | Milliseconds. Same note applies as for `u`. | Example: `654`
  Timezone | --- | ---
  `e` | Timezone identifier | Examples: `UTC`, `GMT`, `Atlantic/Azores`
  `I` (capital i) | Whether or not the date is in daylight saving time | `1` if Daylight Saving Time, `0` otherwise.
  `O` | Difference to Greenwich time (GMT) without colon between hours and minutes | Example: `+0200`
  `P` | Difference to Greenwich time (GMT) with colon between hours and minutes | Example: `+02:00`
  `p` | The same as `P`, but returns `Z` instead of `+00:00` (available as of PHP 8.0.0) | Examples: `Z` or `+02:00`
  `T` | Timezone abbreviation, if known; otherwise the GMT offset. | Examples: `EST`, `MDT`, `+05`
  `Z` | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | `-43200` through `50400`
  Full Date/Time | --- | ---
  `c` | ISO 8601 date. Only compatible with the non-expanded format (up to year 9999). Later dates will result in an invalid string. For later dates and expanded format, see `x` and `X`. | 2004-02-12T15:19:21+00:00
  `r` | » RFC 2822/» RFC 5322 formatted date | Example: `Thu, 21 Dec 2000 16:01:07 +0200`
  `U` | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time()

  Unrecognized characters in the format string will be printed as-is. The `Z` format will always return `0` when using gmdate().

  > Note:

  > Since this function only accepts int timestamps the `u` format character is only useful when using the date_format() function with user based timestamps created with date_create().

### Return Values

Returns the formatted date string on success.

### Changelog

Version | Description
--- | ---
8.2.0 | The format characters `X` and `x` have been added.
8.0.0 | The format character `p` has been added.

### Examples

Example #1 DateTimeInterface::format() example

Object-oriented style

`<?php
$date = new DateTimeImmutable('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>`

The above example will output:

    2000-01-01 00:00:00

Procedural style

`<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>`

The above example will output:

    2000-01-01 00:00:00

Example #2 More examples

`<?php
// set the default timezone to use.
date_default_timezone_set('UTC');
// now
$date = new DateTimeImmutable();
// Prints something like: Wednesday
echo $date->format('l'), "\n";
// Prints something like: Wednesday 19th of October 2022 08:40:48 AM
echo $date->format('l jS \o\f F Y h:i:s A'), "\n";
/* use the constants in the format parameter */
// prints something like: Wed, 19 Oct 2022 08:40:48 +0000
echo $date->format(DateTimeInterface::RFC2822), "\n";
?>`

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #3 Escaping characters while formatting

`<?php
$date = new DateTimeImmutable();
// prints something like: Wednesday the 19th
echo $date->format('l \t\h\e jS');
?>`

To format dates in other languages, IntlDateFormatter::format() can be used instead of DateTimeInterface::format().

### Notes

This method does not use locales. All output is in English.

### See Also

- IntlDateFormatter::format() - Format the date/time value as a string

# DateTimeInterface::getOffset

# DateTimeImmutable::getOffset

# DateTime::getOffset

# date_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::getOffset -- DateTimeImmutable::getOffset -- DateTime::getOffset -- date_offset_get — Returns the timezone offset

### Description

Object-oriented style

public DateTimeInterface::getOffset(): int
public DateTimeImmutable::getOffset(): int
public DateTime::getOffset(): int

Procedural style

date_offset_get(DateTimeInterface `$object`): int

Returns the timezone offset.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create()

### Return Values

Returns the timezone offset in seconds from UTC on success.

### Examples

Example #1 DateTime::getOffset() example

Object-oriented style

`<?php
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTimeImmutable('2008-06-21', new DateTimeZone('America/New_York'));
echo $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";`

The above example will output:

    -18000
    -14400

Procedural style

`<?php
$winter = date_create('2010-12-21', timezone_open('America/New_York'));
$summer = date_create('2008-06-21', timezone_open('America/New_York'));
echo date_offset_get($winter) . "\n";
echo date_offset_get($summer) . "\n";`

The above example will output:

    -18000
    -14400

Note: -18000 = -5 hours, -14400 = -4 hours.

# DateTimeInterface::getTimestamp

# DateTimeImmutable::getTimestamp

# DateTime::getTimestamp

# date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeInterface::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTime::getTimestamp -- date_timestamp_get — Gets the Unix timestamp

### Description

Object-oriented style

public DateTimeInterface::getTimestamp(): int
public DateTimeImmutable::getTimestamp(): int
public DateTime::getTimestamp(): int

Procedural style

date_timestamp_get(DateTimeInterface `$object`): int

Gets the Unix timestamp.

### Parameters

This function has no parameters.

### Return Values

Returns the Unix timestamp representing the date.

### Errors/Exceptions

If the timestamp cannot be represented as int, a DateRangeError is thrown. Prior to PHP 8.3.0, a ValueError is thrown. And, prior to PHP 8.0.0, `false` was returned in this case. Still, the timestamp can be retrieved as string by using DateTimeInterface::format() with the `U` format.

### Changelog

Version | Description
--- | ---
8.3.0 | The out-of-range exception is now DateRangeError.
8.0.0 | These functions no longer return `false` on failure.

### Examples

Example #1 DateTime::getTimestamp() example

Object-oriented style

`<?php
$date = new DateTimeImmutable();
echo $date->getTimestamp();`

The above example will output something similar to:

    1272509157

Procedural style

`<?php
$date = date_create();
echo date_timestamp_get($date);`

The above example will output something similar to:

    1272509157

If you need to retrieve the timestamp with millisecond or microsecond resolution, then you can use the DateTimeInterface::format() function.

Example #2 Retrieving timestamp with milli and microsecond resolution

Object-oriented style

`<?php
$date = new DateTimeImmutable();
$milli = (int) $date->format('Uv'); // Timestamp in milliseconds
$micro = (int) $date->format('Uu'); // Timestamp in microseconds
echo $milli, "\n", $micro, "\n";`

The above example will output something similar to:

    1674057635586
    1674057635586918

### See Also

- DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp
- DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp
- DateTimeInterface::format() - Returns date formatted according to given format

# DateTimeInterface::getTimezone

# DateTimeImmutable::getTimezone

# DateTime::getTimezone

# date_timezone_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::getTimezone -- DateTimeImmutable::getTimezone -- DateTime::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

### Description

Object-oriented style

public DateTimeInterface::getTimezone(): DateTimeZone|false
public DateTimeImmutable::getTimezone(): DateTimeZone|false
public DateTime::getTimezone(): DateTimeZone|false

Procedural style

date_timezone_get(DateTimeInterface `$object`): DateTimeZone|false

Return time zone relative to given DateTime.

### Parameters

`object`

  Procedural style only: A DateTime object returned by date_create()

### Return Values

Returns a DateTimeZone object on success or `false` on failure.

### Examples

Example #1 DateTime::getTimezone() example

Object-oriented style

`<?php
$date = new DateTimeImmutable("now", new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();`

The above example will output:

    Europe/London

Procedural style

`<?php
$date = date_create("now", timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);`

The above example will output:

    Europe/London

### See Also

- DateTime::setTimezone() - Sets the time zone for the DateTime object

# DateTime::__serialize

# DateTimeImmutable::__serialize

# DateTimeInterface::__serialize

(PHP 8 >= 8.2.0)

DateTime::__serialize -- DateTimeImmutable::__serialize -- DateTimeInterface::__serialize — Serialize a DateTime

### Description

public DateTime::__serialize(): array
public DateTimeImmutable::__serialize(): array
public DateTimeInterface::__serialize(): array

The __serialize() handler.

### Parameters

This function has no parameters.

### Return Values

The serialized representation of the DateTime object.

### Examples

Example #1 DateTime::serialize() example

`<?php
$date = new DateTime('2025-03-27');
var_dump(serialize($date));`

The above example will output:

    string(114) "O:8:"DateTime":3:{s:4:"date";s:26:"2025-03-27 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:3:"UTC";}"

### See Also

- DateTime::__unserialize() - Unserialize an Datetime

# DateTime::__unserialize

# DateTimeImmutable::__unserialize

# DateTimeInterface::__unserialize

(PHP 8 >= 8.2.0)

DateTime::__unserialize -- DateTimeImmutable::__unserialize -- DateTimeInterface::__unserialize — Unserialize an Datetime

### Description

public DateTime::__unserialize(array `$data`): void
public DateTimeImmutable::__unserialize(array `$data`): void
public DateTimeInterface::__unserialize(array `$data`): void

The __unserialize() handler.

### Parameters

`data`

  The serialized DateTime.

### Return Values

The DateTime object.

### Examples

Example #1 DateTime::unserialize() example

`<?php
$serializedDate = 'O:8:"DateTime":3:{s:4:"date";s:26:"2025-03-27 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:3:"UTC";}';
var_dump(unserialize($serializedDate));`

The above example will output:

    object(DateTime)#1 (3) {
      ["date"]=>
      string(26) "2025-03-27 00:00:00.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(3) "UTC"
    }

### See Also

- DateTime::__serialize() - Serialize a DateTime

# DateTime::__wakeup

# DateTimeImmutable::__wakeup

# DateTimeInterface::__wakeup

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler

Warning

This function has been DEPRECATED as of PHP 8.5.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
public DateTime::__wakeup(): void
#[\Deprecated]
public DateTimeImmutable::__wakeup(): void
#[\Deprecated]
public DateTimeInterface::__wakeup(): void

The __wakeup() handler.

### Parameters

This function has no parameters.

### Return Values

Initializes a DateTime object.

## Table of Contents

- DateTimeInterface::diff — Returns the difference between two DateTime objects
- DateTimeInterface::format — Returns date formatted according to given format
- DateTimeInterface::getOffset — Returns the timezone offset
- DateTimeInterface::getTimestamp — Gets the Unix timestamp
- DateTimeInterface::getTimezone — Return time zone relative to given DateTime
- DateTime::__serialize — Serialize a DateTime
- DateTime::__unserialize — Unserialize an Datetime
- DateTime::__wakeup — The __wakeup handler

# The DateTimeZone class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

## Introduction

Representation of time zone.

## Class synopsis

class DateTimeZone {
/* Constants */
public const int AFRICA;
public const int AMERICA;
public const int ANTARCTICA;
public const int ARCTIC;
public const int ASIA;
public const int ATLANTIC;
public const int AUSTRALIA;
public const int EUROPE;
public const int INDIAN;
public const int PACIFIC;
public const int UTC;
public const int ALL;
public const int ALL_WITH_BC;
public const int PER_COUNTRY;
/* Methods */
public __construct(string `$timezone`)
public getLocation(): array|false
public getName(): string
public getOffset(DateTimeInterface `$datetime`): int
public getTransitions(int `$timestampBegin` = `PHP_INT_MIN`, int `$timestampEnd` = 2147483647): array|false
public static listAbbreviations(): array
public static listIdentifiers(int `$timezoneGroup` = `DateTimeZone::ALL`, ?string `$countryCode` = `null`): array
}

## Predefined Constants

`DateTimeZone::AFRICA` int

  Africa time zones.

`DateTimeZone::AMERICA` int

  America time zones.

`DateTimeZone::ANTARCTICA` int

  Antarctica time zones.

`DateTimeZone::ARCTIC` int

  Arctic time zones.

`DateTimeZone::ASIA` int

  Asia time zones.

`DateTimeZone::ATLANTIC` int

  Atlantic time zones.

`DateTimeZone::AUSTRALIA` int

  Australia time zones.

`DateTimeZone::EUROPE` int

  Europe time zones.

`DateTimeZone::INDIAN` int

  Indian time zones.

`DateTimeZone::PACIFIC` int

  Pacific time zones.

`DateTimeZone::UTC` int

  UTC time zones.

`DateTimeZone::ALL` int

  All time zones.

`DateTimeZone::ALL_WITH_BC` int

  All time zones including backwards compatible.

`DateTimeZone::PER_COUNTRY` int

  Time zones per country.

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# DateTimeZone::__construct

# timezone_open

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object

### Description

Object-oriented style

public DateTimeZone::__construct(string `$timezone`)

Procedural style

timezone_open(string `$timezone`): DateTimeZone|false

Creates a new DateTimeZone object.

A DateTimeZone object provides access to three different types of timezone rules: UTC offset (type `1`), timezone abbreviation (type `2`), and timezone identifiers as published in the IANA timezone database (type `3`).

The DateTimeZone object can be attached to DateTime and DateTimeImmutable objects to be able to render the timezone encapsulated by these objects in a local timezone.

### Parameters

`timezone`

  One of the supported timezone names, an offset value (+0200), or a timezone abbreviation (BST).

### Return Values

Returns DateTimeZone on success. Procedural style returns `false` on failure.

### Errors/Exceptions

This method throws DateInvalidTimeZoneException if the timezone supplied is not recognised as a valid timezone. Prior to PHP 8.3, this was an Exception instead.

### Changelog

Version | Description
--- | ---
8.3.0 | Invalid values now return a DateInvalidTimeZoneException instead of a generic Exception.

### Examples

Example #1 Creating and attaching DateTimeZone to a DateTimeImmutable

`<?php
$d = new DateTimeImmutable("2022-06-02 15:44:48 UTC");
$timezones = [ 'Europe/London', 'GMT+04:45', '-06:00', 'CEST' ];
foreach ($timezones as $tz) {
$tzo = new DateTimeZone($tz);
$local = $d->setTimezone($tzo);
echo $local->format(DateTimeInterface::RFC2822 . ' — e') . "\n";
}`

The above example will output:

    Thu, 02 Jun 2022 16:44:48 +0100 — Europe/London
    Thu, 02 Jun 2022 20:29:48 +0445 — +04:45
    Thu, 02 Jun 2022 09:44:48 -0600 — -06:00
    Thu, 02 Jun 2022 17:44:48 +0200 — CEST

Example #2 Catching errors when instantiating DateTimeZone

`<?php
// Error handling by catching exceptions
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');
foreach ($timezones as $tz) {
try {
$mars = new DateTimeZone($tz);
echo $mars->getName() . "\n";
} catch(Exception $e) {
echo $e->getMessage() . "\n";
}
}`

The above example will output:

    Europe/London
    DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
    DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)

# DateTimeZone::getLocation

# timezone_location_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone

### Description

Object-oriented style

public DateTimeZone::getLocation(): array|false

Procedural style

timezone_location_get(DateTimeZone `$object`): array|false

Returns location information for a timezone, including country code, latitude/longitude and comments.

### Parameters

`object`

  Procedural style only: A DateTimeZone object returned by timezone_open()

### Return Values

Array containing location information about timezone or `false` on failure.

### Examples

Example #1 DateTimeZone::getLocation() example

`<?php
$tz = new DateTimeZone("Asia/Jakarta");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));`

The above example will output:

    Array
    (
        [country_code] => ID
        [latitude] => -6.16667
        [longitude] => 106.8
        [comments] => Java, Sumatra
    )
    Array
    (
        [country_code] => ID
        [latitude] => -6.16667
        [longitude] => 106.8
        [comments] => Java, Sumatra
    )

The `country_code` elements contains the ISO 3166-1 alpha-2 country code for each entry. The `latitude` and `longitude` elements the coordinates of the named city from the time zone identifier, and `comments` contain (when not `false`) a hint of where in the given country this timezone applies. This information is suitable to present to end-users.

### See Also

- DateTimeZone::listIdentifiers() - Returns a numerically indexed array containing all defined timezone identifiers to get a full or partial list of all supported timezone identifiers

# DateTimeZone::getName

# timezone_name_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getName -- timezone_name_get — Returns the name of the timezone

### Description

Object-oriented style

public DateTimeZone::getName(): string

Procedural style

timezone_name_get(DateTimeZone `$object`): string

Returns the name of the timezone.

### Parameters

`object`

  The DateTimeZone for which to get a name.

### Return Values

Depending on zone type, UTC offset (type 1), timezone abbreviation (type 2), and timezone identifiers as published in the IANA timezone database (type 3), the descriptor string to create a new DateTimeZone object with the same offset and/or rules. For example `02:00`, `CEST`, or one of the timezone names in the list of timezones.

# DateTimeZone::getOffset

# timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getOffset -- timezone_offset_get — Returns the timezone offset from GMT

### Description

Object-oriented style

public DateTimeZone::getOffset(DateTimeInterface `$datetime`): int

Procedural style

timezone_offset_get(DateTimeZone `$object`, DateTimeInterface `$datetime`): int

This function returns the offset to GMT for the date/time specified in the `datetime` parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

### Parameters

`object`

  Procedural style only: A DateTimeZone object returned by timezone_open()

`datetime`

  DateTime that contains the date/time to compute the offset from.

### Return Values

Returns time zone offset in seconds.

### Examples

Example #1 DateTimeZone::getOffset() examples

`<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);
// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);`

The above example will output:

    int(32400)

# DateTimeZone::getTransitions

# timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone

### Description

Object-oriented style

public DateTimeZone::getTransitions(int `$timestampBegin` = `PHP_INT_MIN`, int `$timestampEnd` = 2147483647): array|false

Procedural style

timezone_transitions_get(DateTimeZone `$object`, int `$timestampBegin` = `PHP_INT_MIN`, int `$timestampEnd` = 2147483647): array|false

### Parameters

`object`

  Procedural style only: A DateTimeZone object returned by timezone_open()

`timestampBegin`

  Begin timestamp.

`timestampEnd`

  End timestamp.

### Return Values

Returns a numerically indexed array of transition arrays on success, or `false` on failure. DateTimeZone objects wrapping type 1 (UTC offsets) and type 2 (abbreviations) do not contain any transitions, and calling this method on them will return `false`.

If `timestampBegin` is given, the first entry in the returned array will contain a transition element at the time of `timestampBegin`.

Transition Array Structure
Key | Type | Description
--- | --- | ---
`ts` | int | Unix timestamp
`time` | string | `DateTimeInterface::ISO8601_EXPANDED` (PHP 8.2 and later), or `DateTimeInterface::ISO8601` (PHP 8.1 and lower) time string
`offset` | int | Offset to UTC in seconds
`isdst` | bool | Whether daylight saving time is active
`abbr` | string | Timezone abbreviation

### Changelog

Version | Description
--- | ---
8.1.0 | The default value of `timestampEnd` has been changed to 2147483647. Previously, it was `PHP_INT_MAX`.

### Examples

Example #1 A timezone_transitions_get() example

`<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [ts] => -2147483648
                [time] => 1901-12-13T20:45:52+00:00
                [offset] => -75
                [isdst] =>
                [abbr] => LMT
            )

        [1] => Array
            (
                [ts] => 442304971
                [time] => 1847-12-01T00:01:15+00:00
                [offset] => 0
                [isdst] =>
                [abbr] => GMT
            )

        [2] => Array
            (
                [ts] => -1691964000
                [time] => 1916-05-21T02:00:00+00:00
                [offset] => 3600
                [isdst] => 1
                [abbr] => BST
            )

    )

Example #2 A timezone_transitions_get() example with `timestampBegin` set

`<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions(time());
print_r(array_slice($transitions, 0, 3));
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [ts] => 1759058251
                [time] => 2025-09-28T11:17:31+00:00
                [offset] => 3600
                [isdst] => 1
                [abbr] => BST
            )

        [1] => Array
            (
                [ts] => 1761440400
                [time] => 2025-10-26T01:00:00+00:00
                [offset] => 0
                [isdst] =>
                [abbr] => GMT
            )

        [2] => Array
            (
                [ts] => 1774746000
                [time] => 2026-03-29T01:00:00+00:00
                [offset] => 3600
                [isdst] => 1
                [abbr] => BST
            )

    )

# DateTimeZone::listAbbreviations

# timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name

### Description

Object-oriented style

public static DateTimeZone::listAbbreviations(): array

Procedural style

timezone_abbreviations_list(): array

The returned list of abbreviations includes all historical use of abbreviations, which can lead to correct, but confusing entries. There are also conflicts, as `PST` is used both in the US and in the Philippines.

The list that this function returns is therefore not suitable for building an array with options to present a choice of timezone to users.

> Note:

> The data for this function are precompiled for performance reasons, and are not updated when using a newer » timezonedb.

### Parameters

This function has no parameters.

### Return Values

Returns the array of timezone abbreviations.

### Examples

Example #1 A timezone_abbreviations_list() example

`<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/Adelaide
            )

        [1] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/Broken_Hill
            )

        [2] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/Darwin
            )

        [3] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/North
            )

        [4] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/South
            )

        [5] => Array
            (
                [dst] =>
                [offset] => 34200
                [timezone_id] => Australia/Yancowinna
            )

    )

### See Also

- timezone_identifiers_list() - Alias of DateTimeZone::listIdentifiers

# DateTimeZone::listIdentifiers

# timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns a numerically indexed array containing all defined timezone identifiers

### Description

Object-oriented style

public static DateTimeZone::listIdentifiers(int `$timezoneGroup` = `DateTimeZone::ALL`, ?string `$countryCode` = `null`): array

Procedural style

timezone_identifiers_list(int `$timezoneGroup` = `DateTimeZone::ALL`, ?string `$countryCode` = `null`): array

Return the list of » IANA Time Zone identifiers.

> Note: It's possible to detect the client (browser) timezone with JavaScript using » Intl.DateTimeFormat or » Temporal.ZonedDateTime.

### Parameters

`timezoneGroup`

  One of the DateTimeZone class constants (or a combination).

`countryCode`

  A two-letter (uppercase) ISO 3166-1 compatible country code.

  > Note: This option is only used when `timezoneGroup` is set to `DateTimeZone::PER_COUNTRY`.

### Return Values

Returns the array of timezone identifiers. Only non-outdated items are returned. To get all, including outdated timezone identifiers, use the `DateTimeZone::ALL_WITH_BC` as value for `timezoneGroup`.

### Changelog

Version | Description
--- | ---
8.0.0 | Prior to this version, `false` was returned on failure.
7.1.0 | `countryCode` is nullable now.

### Examples

Example #1 List identifiers with location comments

`<?php
$identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
foreach ($identifiers as $tzid) {
$tz = new DateTimeZone($tzid);
$comments = $tz->getLocation()['comments'];
echo $tzid . " (" . ($comments ?: 'Whole region') . ")\n";
}`

The above example will output something similar to:

    America/Antigua (Whole region)
    America/Araguaina (Tocantins)
    America/Argentina/Buenos_Aires (Buenos Aires (BA, CF))
    America/Argentina/Catamarca (Catamarca (CT), Chubut (CH))
    America/Argentina/Cordoba (Argentina (most areas: CB, CC, CN, ER, FM, MN, SE, SF))
    // (Output trimmed due to length)

Example #2 Listing identifiers for a specific region

`<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::ASIA );
for ($i=0; $i < 5; $i++) {
echo "$timezone_identifiers[$i]\n";
}`

The above example will output something similar to:

    Asia/Aden
    Asia/Almaty
    Asia/Amman
    Asia/Anadyr
    Asia/Aqtau

Example #3 Listing identifiers for multiple regions

`<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::ASIA | DateTimeZone::PACIFIC );
echo join( ', ', $timezone_identifiers );`

The above example will output something similar to:

    Asia/Aden, Asia/Almaty, Asia/Amman, Asia/Anadyr, Asia/Aqtau, Asia/Aqtobe,
    Asia/Ashgabat, Asia/Atyrau, Asia/Baghdad, Asia/Bahrain, Asia/Baku,
    Asia/Bangkok, Asia/Barnaul, Asia/Beirut, Asia/Bishkek, Asia/Brunei,
    Asia/Chita, Asia/Choibalsan, Asia/Colombo, Asia/Damascus, Asia/Dhaka,
    Asia/Dili, Asia/Dubai, Asia/Dushanbe, Asia/Famagusta, Asia/Gaza, Asia/Hebron,
    Asia/Ho_Chi_Minh, Asia/Hong_Kong, Asia/Hovd, Asia/Irkutsk, Asia/Jakarta,
    Asia/Jayapura, Asia/Jerusalem, Asia/Kabul, Asia/Kamchatka, Asia/Karachi,
    Asia/Kathmandu, Asia/Khandyga, Asia/Kolkata, Asia/Krasnoyarsk,
    Asia/Kuala_Lumpur, Asia/Kuching, Asia/Kuwait, Asia/Macau, Asia/Magadan,
    Asia/Makassar, Asia/Manila, Asia/Muscat, Asia/Nicosia, Asia/Novokuznetsk,
    Asia/Novosibirsk, Asia/Omsk, Asia/Oral, Asia/Phnom_Penh, Asia/Pontianak,
    Asia/Pyongyang, Asia/Qatar, Asia/Qostanay, Asia/Qyzylorda, Asia/Riyadh,
    Asia/Sakhalin, Asia/Samarkand, Asia/Seoul, Asia/Shanghai, Asia/Singapore,
    Asia/Srednekolymsk, Asia/Taipei, Asia/Tashkent, Asia/Tbilisi, Asia/Tehran,
    Asia/Thimphu, Asia/Tokyo, Asia/Tomsk, Asia/Ulaanbaatar, Asia/Urumqi,
    Asia/Ust-Nera, Asia/Vientiane, Asia/Vladivostok, Asia/Yakutsk, Asia/Yangon,
    Asia/Yekaterinburg, Asia/Yerevan, Pacific/Apia, Pacific/Auckland,
    Pacific/Bougainville, Pacific/Chatham, Pacific/Chuuk, Pacific/Easter,
    Pacific/Efate, Pacific/Fakaofo, Pacific/Fiji, Pacific/Funafuti,
    Pacific/Galapagos, Pacific/Gambier, Pacific/Guadalcanal, Pacific/Guam,
    Pacific/Honolulu, Pacific/Kanton, Pacific/Kiritimati, Pacific/Kosrae,
    Pacific/Kwajalein, Pacific/Majuro, Pacific/Marquesas, Pacific/Midway,
    Pacific/Nauru, Pacific/Niue, Pacific/Norfolk, Pacific/Noumea,
    Pacific/Pago_Pago, Pacific/Palau, Pacific/Pitcairn, Pacific/Pohnpei,
    Pacific/Port_Moresby, Pacific/Rarotonga, Pacific/Saipan, Pacific/Tahiti,
    Pacific/Tarawa, Pacific/Tongatapu, Pacific/Wake, Pacific/Wallis

Example #4 Listing identifiers for a single country

`<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::PER_COUNTRY, "UA" );
foreach( $timezone_identifiers as $identifier ) {
echo "$identifier\n";
}`

The above example will output something similar to:

    Europe/Kyiv
    Europe/Simferopol
    Europe/Uzhgorod
    Europe/Zaporozhye

### See Also

- timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

## Table of Contents

- DateTimeZone::__construct — Creates new DateTimeZone object
- DateTimeZone::getLocation — Returns location information for a timezone
- DateTimeZone::getName — Returns the name of the timezone
- DateTimeZone::getOffset — Returns the timezone offset from GMT
- DateTimeZone::getTransitions — Returns all transitions for the timezone
- DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
- DateTimeZone::listIdentifiers — Returns a numerically indexed array containing all defined timezone identifiers

# The DateInterval class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

Represents a date interval.

A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable's and DateTime's constructors support.

More specifically, the information in an object of the DateInterval class is an instruction to get from one date/time to another date/time. This process is not always reversible.

A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff().

Since there is no well defined way to compare date intervals, DateInterval instances are incomparable.

## Class synopsis

class DateInterval {
/* Properties */
public int $y;
public int $m;
public int $d;
public int $h;
public int $i;
public int $s;
public float $f;
public int $invert;
public mixed $days;
public bool $from_string;
public string $date_string;
/* Methods */
public __construct(string `$duration`)
public static createFromDateString(string `$datetime`): DateInterval
public format(string `$format`): string
}

## Properties

Warning

The available properties listed below depend on PHP version, and should be considered as readonly.

y

  Number of years.

m

  Number of months.

d

  Number of days.

h

  Number of hours.

i

  Number of minutes.

s

  Number of seconds.

f

  Number of microseconds, as a fraction of a second.

invert

  Is `1` if the interval represents a negative time period and `0` otherwise. See DateInterval::format().

days

  If the DateInterval object was created by DateTimeImmutable::diff() or DateTime::diff(), then this is the total number of full days between the start and end dates. Otherwise, days will be `false`.

from_string

  If the DateInterval object was created by DateInterval::createFromDateString(), then this property's value will be `true`, and the date_string property will be populated. Otherwise, the value will be `false`, and the y to f, invert, and days properties will be populated.

date_string

  The string used as argument to DateInterval::createFromDateString().

## Changelog

Version | Description
--- | ---
8.2.0 | The from_string and date_string properties were added for DateInterval instances that were created using the DateInterval::createFromDateString() method.
8.2.0 | Only the `y` to `f`, `invert`, and `days` will be visible.
7.4.0 | DateInterval instances are incomparable now; previously, all DateInterval instances were considered equal.
7.1.0 | The f property was added.

# DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::__construct — Creates a new DateInterval object

### Description

public DateInterval::__construct(string `$duration`)

Creates a new DateInterval object.

### Parameters

`duration`

  An interval specification.

  The format starts with the letter `P`, for period. Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter `T`.

  `duration` Period Designators
  Period Designator | Description
  --- | ---
  `Y` | years
  `M` | months
  `D` | days
  `W` | weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with `D`.
  `H` | hours
  `M` | minutes
  `S` | seconds

  Here are some simple examples. Two days is `P2D`. Two seconds is `PT2S`. Six years and five minutes is `P6YT5M`.

  > Note:

  > The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as `P1Y4D`, not `P4D1Y`.

  The specification can also be represented as a date time. A sample of one year and four days would be `P0001-00-04T00:00:00`. But the values in this format can not exceed a given period's roll-over-point (e.g. `25` hours is invalid).

  These formats are based on the » ISO 8601 duration specification.

### Errors/Exceptions

Throws an DateMalformedIntervalStringException when the `duration` cannot be parsed as an interval. Prior to PHP 8.3, this was Exception.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws DateMalformedIntervalStringException instead of Exception.
8.2.0 | Only the `y` to `f`, `invert`, and `days` will be visible, including a new `from_string` boolean property.
8.0.0 | `W` can be combined with `D`.

### Examples

Example #1 Constructing and using DateInterval objects

`<?php
// Create a specific date
$someDate = \DateTime::createFromFormat("Y-m-d H:i", "2022-08-25 14:18");
// Create interval
$interval = new \DateInterval("P7D");
// Add interval
$someDate->add($interval);
// Convert interval to string
echo $interval->format("%d");`

The above example will output:

    7

Example #2 DateInterval example

`<?php
$interval = new DateInterval('P1W2D');
var_dump($interval);`

Output of the above example in PHP 8.2:

    object(DateInterval)#1 (10) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(0)
      ["d"]=>
      int(9)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["invert"]=>
      int(0)
      ["days"]=>
      bool(false)
      ["from_string"]=>
      bool(false)
    }

Output of the above example in PHP 8:

    object(DateInterval)#1 (16) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(0)
      ["d"]=>
      int(9)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["weekday"]=>
      int(0)
      ["weekday_behavior"]=>
      int(0)
      ["first_last_day_of"]=>
      int(0)
      ["invert"]=>
      int(0)
      ["days"]=>
      bool(false)
      ["special_type"]=>
      int(0)
      ["special_amount"]=>
      int(0)
      ["have_weekday_relative"]=>
      int(0)
      ["have_special_relative"]=>
      int(0)
    }

Output of the above example in PHP 7:

    object(DateInterval)#1 (16) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(0)
      ["d"]=>
      int(2)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["weekday"]=>
      int(0)
      ["weekday_behavior"]=>
      int(0)
      ["first_last_day_of"]=>
      int(0)
      ["invert"]=>
      int(0)
      ["days"]=>
      bool(false)
      ["special_type"]=>
      int(0)
      ["special_amount"]=>
      int(0)
      ["have_weekday_relative"]=>
      int(0)
      ["have_special_relative"]=>
      int(0)
    }

### See Also

- DateInterval::format() - Formats the interval
- DateTime::add() - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTime::diff() - Returns the difference between two DateTime objects

# DateInterval::createFromDateString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

### Description

Object-oriented style

public static DateInterval::createFromDateString(string `$datetime`): DateInterval

Procedural style

date_interval_create_from_date_string(string `$datetime`): DateInterval|false

Uses the date/time parsers as used in the DateTimeImmutable constructor to create a DateInterval from the relative parts of the parsed string.

### Parameters

`datetime`

  A date with relative parts. Specifically, the relative formats supported by the parser used for DateTimeImmutable, DateTime, and strtotime() will be used to construct the DateInterval.

  To use an ISO-8601 format string like `P7D`, you must use the DateInterval::__construct().

### Return Values

Returns DateInterval on success. Procedural style returns `false` on failure.

### Errors/Exceptions

Object Oriented API only: If an invalid Date/Time string is passed, DateMalformedStringException is thrown.

### Changelog

Version | Description
--- | ---
8.3.0 | DateInterval::createFromDateString() now throws DateMalformedStringException if an invalid string is passed. Previously, it returned `false`, and a warning was emitted. date_interval_create_from_date_string() has not been changed.
8.2.0 | Only the `from_string` and `date_string` properties will be visible when a DateInterval is created with this method.

### Examples

Example #1 Parsing valid date intervals

`<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');
$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');
$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');
$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');
$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');
$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');
$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');`

Example #2 Parsing combinations and negative intervals

`<?php
$i = DateInterval::createFromDateString('62 weeks + 1 day + 2 weeks + 2 hours + 70 minutes');
echo $i->format('%d %h %i'), "\n";
$i = DateInterval::createFromDateString('1 year - 10 days');
echo $i->format('%y %d'), "\n";`

The above example will output:

    449 2 70
    1 -10

Example #3 Parsing special relative date intervals

`<?php
$i = DateInterval::createFromDateString('last day of next month');
var_dump($i);
$i = DateInterval::createFromDateString('last weekday');
var_dump($i);`

Output of the above example in PHP 8.2:

    object(DateInterval)#1 (2) {
      ["from_string"]=>
      bool(true)
      ["date_string"]=>
      string(22) "last day of next month"
    }
    object(DateInterval)#2 (2) {
      ["from_string"]=>
      bool(true)
      ["date_string"]=>
      string(12) "last weekday"
    }

Output of the above example in PHP 8 is similar to:

    object(DateInterval)#1 (16) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(1)
      ["d"]=>
      int(0)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["weekday"]=>
      int(0)
      ["weekday_behavior"]=>
      int(0)
      ["first_last_day_of"]=>
      int(2)
      ["invert"]=>
      int(0)
      ["days"]=>
      bool(false)
      ["special_type"]=>
      int(0)
      ["special_amount"]=>
      int(0)
      ["have_weekday_relative"]=>
      int(0)
      ["have_special_relative"]=>
      int(0)
    }
    object(DateInterval)#2 (16) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(0)
      ["d"]=>
      int(0)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["weekday"]=>
      int(0)
      ["weekday_behavior"]=>
      int(0)
      ["first_last_day_of"]=>
      int(0)
      ["invert"]=>
      int(0)
      ["days"]=>
      bool(false)
      ["special_type"]=>
      int(1)
      ["special_amount"]=>
      int(-1)
      ["have_weekday_relative"]=>
      int(0)
      ["have_special_relative"]=>
      int(1)
    }

# DateInterval::format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::format — Formats the interval

### Description

public DateInterval::format(string `$format`): string

Formats the interval.

### Parameters

`format`

  The following characters are recognized in the `format` parameter string. Each format character must be prefixed by a percent sign (`%`).
  `format` character | Description | Example values
  --- | --- | ---
  `%` | Literal `%` | `%`
  `Y` | Years, numeric, at least 2 digits with leading 0 | `01`, `03`
  `y` | Years, numeric | `1`, `3`
  `M` | Months, numeric, at least 2 digits with leading 0 | `01`, `03`, `12`
  `m` | Months, numeric | `1`, `3`, `12`
  `D` | Days, numeric, at least 2 digits with leading 0 | `01`, `03`, `31`
  `d` | Days, numeric | `1`, `3`, `31`
  `a` | Total number of days as a result of a DateTime::diff() or `(unknown)` otherwise | `4`, `18`, `8123`
  `H` | Hours, numeric, at least 2 digits with leading 0 | `01`, `03`, `23`
  `h` | Hours, numeric | `1`, `3`, `23`
  `I` | Minutes, numeric, at least 2 digits with leading 0 | `01`, `03`, `59`
  `i` | Minutes, numeric | `1`, `3`, `59`
  `S` | Seconds, numeric, at least 2 digits with leading 0 | `01`, `03`, `57`
  `s` | Seconds, numeric | `1`, `3`, `57`
  `F` | Microseconds, numeric, at least 6 digits with leading 0 | `007701`, `052738`, `428291`
  `f` | Microseconds, numeric | `7701`, `52738`, `428291`
  `R` | Sign "`-`" when negative, "`+`" when positive | `-`, `+`
  `r` | Sign "`-`" when negative, empty when positive | `-`, ``

### Return Values

Returns the formatted interval.

### Changelog

Version | Description
--- | ---
7.2.12 | The `F` and `f` format will now always be positive.
7.1.0 | The `F` and `f` format characters were added.

### Examples

Example #1 DateInterval example

`<?php
$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');`

The above example will output:

    4 days

Example #2 DateInterval and carry over points

`<?php
$interval = new DateInterval('P32D');
echo $interval->format('%d days');`

The above example will output:

    32 days

Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers

`<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');`

The above example will output:

    31 total days
    1 month, 0 days

### Notes

> Note:

> The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like `"32 days"` which could be interpreted as anything from `"1 month and 4 days"` to `"1 month and 1 day"`.

### See Also

- DateTime::diff() - Returns the difference between two DateTime objects

## Table of Contents

- DateInterval::__construct — Creates a new DateInterval object
- DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
- DateInterval::format — Formats the interval

# The DatePeriod class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

## Introduction

Represents a date period.

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

## Class synopsis

class DatePeriod implements IteratorAggregate {
/* Constants */
public const int EXCLUDE_START_DATE;
public const int INCLUDE_END_DATE;
/* Properties */
public readonly ?DateTimeInterface $start;
public readonly ?DateTimeInterface $current;
public readonly ?DateTimeInterface $end;
public readonly ?DateInterval $interval;
public readonly int $recurrences;
public readonly bool $include_start_date;
public readonly bool $include_end_date;
/* Methods */
public __construct(
DateTimeInterface `$start`,
DateInterval `$interval`,
int `$recurrences`,
int `$options` = 0
)
public __construct(
DateTimeInterface `$start`,
DateInterval `$interval`,
DateTimeInterface `$end`,
int `$options` = 0
)
public __construct(string `$isostr`, int `$options` = 0)
public static createFromISO8601String(string `$specification`, int `$options` = 0): static
public getDateInterval(): DateInterval
public getEndDate(): ?DateTimeInterface
public getRecurrences(): ?int
public getStartDate(): DateTimeInterface
}

## Predefined Constants

`DatePeriod::EXCLUDE_START_DATE` int

  Exclude start date, used in DatePeriod::__construct().

`DatePeriod::INCLUDE_END_DATE` int

  Include end date, used in DatePeriod::__construct().

## Properties

recurrences

  The minimum amount of instances as retured by the iterator.

  If the number of recurrences has been explicitly passed through the recurrences parameter in the constructor of the DatePeriod instance, then this property contains this value, plus one if the start date has not been disabled through `DatePeriod::EXCLUDE_START_DATE`, plus one if the end date has been enabled through `DatePeriod::INCLUDE_END_DATE`.

  If the number of recurrences has not been explicitly passed, then this property contains the minimum number of returned instances. This would be `0`, plus one if the start date has not been disabled through `DatePeriod::EXCLUDE_START_DATE`, plus one if the end date has been enabled through `DatePeriod::INCLUDE_END_DATE`.

  `<?php
  $start = new DateTime('2018-12-31 00:00:00');
  $end = new DateTime('2021-12-31 00:00:00');
  $interval = new DateInterval('P1M');
  $recurrences = 5;
  // recurrences explicitly set through the constructor
  $period = new DatePeriod($start, $interval, $recurrences, DatePeriod::EXCLUDE_START_DATE);
  echo $period->recurrences, "\n";
  $period = new DatePeriod($start, $interval, $recurrences);
  echo $period->recurrences, "\n";
  $period = new DatePeriod($start, $interval, $recurrences, DatePeriod::INCLUDE_END_DATE);
  echo $period->recurrences, "\n";
  // recurrences not set in the constructor
  $period = new DatePeriod($start, $interval, $end);
  echo $period->recurrences, "\n";
  $period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
  echo $period->recurrences, "\n";`

  The above example will output:

      5
      6
      7
      1
      0

  See also DatePeriod::getRecurrences().

include_end_date

  Whether to include the end date in the set of recurring dates or not.

include_start_date

  Whether to include the start date in the set of recurring dates or not.

start

  The start date of the period.

current

  During iteration this will contain the current date within the period.

end

  The end date of the period.

interval

  An ISO 8601 repeating interval specification.

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
8.2.0 | The `DatePeriod::INCLUDE_END_DATE` constant and include_end_date property have been added.
8.0.0 | DatePeriod implements IteratorAggregate now. Previously, Traversable was implemented instead.

# DatePeriod::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DatePeriod::__construct — Creates a new DatePeriod object

### Description

public DatePeriod::__construct(
DateTimeInterface `$start`,
DateInterval `$interval`,
int `$recurrences`,
int `$options` = 0
)
public DatePeriod::__construct(
DateTimeInterface `$start`,
DateInterval `$interval`,
DateTimeInterface `$end`,
int `$options` = 0
)
Warning

The following constructor variant has been deprecated:

public DatePeriod::__construct(string `$isostr`, int `$options` = 0)

Instead the DatePeriod::createFromISO8601String() static factory method should be used.

Creates a new DatePeriod object.

DatePeriod objects can be used as an iterator to generate a number of DateTimeImmutable or DateTime object from a `start` date, a `interval`, and an `end` date or the number of `recurrences`.

The class of returned objects is equivalent to the DateTimeImmutable or DateTime ancestor class of the `start` object.

### Parameters

`start`

  The start date of the period. Included by default in the result set.

`interval`

  The interval between recurrences within the period.

`recurrences`

  The number of recurrences. The number of returned results is one higher than this, as the start date is included in the result set by default. Must be greater than `0`.

`end`

  The end date of the period. Excluded by default from the result set.

`isostr`

  A subset of the » ISO 8601 repeating interval specification.

  Examples of some ISO 8601 interval specification features that PHP does not support are:

  1. zero occurrences (`R0/`)
  2. time offsets other than UTC (`Z`), such as `+02:00`.
`options`

  A bit field which can be used to control certain behaviour with start- and end- dates.

  With `DatePeriod::EXCLUDE_START_DATE` you exclude the start date from the set of recurring dates within the period.

  With `DatePeriod::INCLUDE_END_DATE` you include the end date in the set of recurring dates within the period.

### Errors/Exceptions

Throws an DateMalformedPeriodStringException when the `isostr` cannot be parsed as a valid ISO 8601 period. Prior to PHP 8.3, this was Exception.

### Changelog

Version | Description
--- | ---
8.3.0 | Now throws DateMalformedPeriodStringException instead of Exception.
8.2.0 | The `DatePeriod::INCLUDE_END_DATE` constant has been added.
7.2.19, 7.3.6, 7.4.0 | `recurrences` must be greater than `0` now.

### Examples

Example #1 DatePeriod example

`<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences = 4;
$iso = 'R4/2012-07-01T00:00:00Z/P7D';
// All of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);
// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}`

The above example will output:

    Deprecated: Calling DatePeriod::__construct(string $isostr, int $options = 0) is deprecated, use DatePeriod::createFromISO8601String() instead in script on line 11
    2012-07-01
    2012-07-08
    2012-07-15
    2012-07-22
    2012-07-29

Example #2 DatePeriod example with `DatePeriod::EXCLUDE_START_DATE`

`<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$period = new DatePeriod($start, $interval, $end,
DatePeriod::EXCLUDE_START_DATE);
// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}`

The above example will output:

    2012-07-08
    2012-07-15
    2012-07-22
    2012-07-29

Example #3 DatePeriod example showing all last Thursdays in a year

`<?php
$begin = new DateTime('2021-12-31');
$end = new DateTime('2022-12-31 23:59:59');
$interval = DateInterval::createFromDateString('last thursday of next month');
$period = new DatePeriod($begin, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
foreach ($period as $dt) {
echo $dt->format('l Y-m-d'), "\n";
}`

The above example will output:

    Thursday 2022-01-27
    Thursday 2022-02-24
    Thursday 2022-03-31
    Thursday 2022-04-28
    Thursday 2022-05-26
    Thursday 2022-06-30
    Thursday 2022-07-28
    Thursday 2022-08-25
    Thursday 2022-09-29
    Thursday 2022-10-27
    Thursday 2022-11-24
    Thursday 2022-12-29

### Notes

Unbound numbers of repetitions as specified by ISO 8601 section 4.5 "Recurring time interval" are not supported, i.e. neither passing `"R/..."` as `isostr` nor passing `null` as `end` would work.

# DatePeriod::createFromISO8601String

(PHP 8 >= 8.3.0)

DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string

### Description

public static DatePeriod::createFromISO8601String(string `$specification`, int `$options` = 0): static

Creates a new DatePeriod object from an ISO8601 string, as specified with `specification`.

### Parameters

`specification`

  A subset of the » ISO 8601 repeating interval specification.

  An example of an accepted ISO 8601 interval specifications is `R5/2008-03-01T13:00:00Z/P1Y2M10DT2H30M`, which specifies:

  - 5 iterations (`R5/`)
  - Starting at `2008-03-01T13:00:00Z`.
  - Each iteration is an 1 year, 2 months, 10 days, 2 hours, and 30 minute interval (`/P1Y2M10DT2H30M`).

  Examples of some ISO 8601 interval specification features that PHP does not support are:

  1. zero occurrences (`R0/`)
  2. time offsets other than UTC (`Z`), such as `+02:00`.
`options`

  A bit field which can be used to control certain behaviour with start- and end- dates.

  With `DatePeriod::EXCLUDE_START_DATE` you exclude the start date from the set of recurring dates within the period.

  With `DatePeriod::INCLUDE_END_DATE` you include the end date in the set of recurring dates within the period.

### Return Values

Creates a new DatePeriod object.

DatePeriod objects created with this method can be used as an iterator to generate a number of DateTimeImmutable objects.

### Errors/Exceptions

Throws an DateMalformedPeriodStringException when the `specification` cannot be parsed as a valid ISO 8601 period.

### Examples

Example #1 DatePeriod::createFromISO8601String example

`<?php
$iso = 'R4/2023-07-01T00:00:00Z/P7D';
$period = DatePeriod::createFromISO8601String($iso);
// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
echo $date->format('Y-m-d'), "\n";
}`

The above example will output:

    2023-07-01
    2023-07-08
    2023-07-15
    2023-07-22
    2023-07-29

# DatePeriod::getDateInterval

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getDateInterval — Gets the interval

### Description

Object-oriented style

public DatePeriod::getDateInterval(): DateInterval

Gets a DateInterval object representing the interval used for the period.

### Parameters

This function has no parameters.

### Return Values

Returns a DateInterval object

### Examples

Example #1 DatePeriod::getDateInterval() example

`<?php
$period = DatePeriod::createFromIso8601String('R7/2016-05-16T00:00:00Z/P1D');
$interval = $period->getDateInterval();
echo $interval->format('%d day');`

The above example will output:

    1 day

### See Also

- DatePeriod::getStartDate() - Gets the start date
- DatePeriod::getEndDate() - Gets the end date

# DatePeriod::getEndDate

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getEndDate — Gets the end date

### Description

Object-oriented style

public DatePeriod::getEndDate(): ?DateTimeInterface

Gets the end date of the period.

### Parameters

This function has no parameters.

### Return Values

Returns `null` if the DatePeriod does not have an end date. For example, when initialized with the `recurrences` parameter, or the `isostr` parameter without an end date.

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the `end` parameter.

Returns a cloned DateTime object representing the end date otherwise.

### Examples

Example #1 DatePeriod::getEndDate() example

`<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
new DateTime('2016-05-20T00:00:00Z')
);
$start = $period->getEndDate();
echo $start->format(DateTime::ISO8601);`

The above examples will output:

    2016-05-20T00:00:00+0000

Example #2 DatePeriod::getEndDate() without an end date

`<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
7
);
var_dump($period->getEndDate());`

The above example will output:

    NULL

### See Also

- DatePeriod::getStartDate() - Gets the start date
- DatePeriod::getDateInterval() - Gets the interval

# DatePeriod::getRecurrences

(PHP 7 >= 7.2.17/7.3.4, PHP 8)

DatePeriod::getRecurrences — Gets the number of recurrences

### Description

Object-oriented style

public DatePeriod::getRecurrences(): ?int

Get the number of recurrences.

### Parameters

This function has no parameters.

### Return Values

The number of recurrences as set by explicitly passing the `$recurrences` to the constructor of the DatePeriod class, or `null` otherwise.

### Examples

Example #1 Different values for DatePeriod::getRecurrences()

`<?php
$start = new DateTime('2018-12-31 00:00:00');
$end = new DateTime('2021-12-31 00:00:00');
$interval = new DateInterval('P1M');
$recurrences = 5;
// recurrences explicitly set through the constructor
$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::EXCLUDE_START_DATE);
echo $period->getRecurrences(), "\n";
$period = new DatePeriod($start, $interval, $recurrences);
echo $period->getRecurrences(), "\n";
$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::INCLUDE_END_DATE);
echo $period->getRecurrences(), "\n\n";
// recurrences not set in the constructor
$period = new DatePeriod($start, $interval, $end);
var_dump($period->getRecurrences());
$period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
var_dump($period->getRecurrences());`

The above example will output:

    5
    5
    5

    NULL
    NULL

### See Also

- DatePeriod::$recurrences

# DatePeriod::getStartDate

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getStartDate — Gets the start date

### Description

Object-oriented style

public DatePeriod::getStartDate(): DateTimeInterface

Gets the start date of the period.

### Parameters

This function has no parameters.

### Return Values

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the `start` parameter.

Returns a DateTime object otherwise.

### Examples

Example #1 DatePeriod::getStartDate() example

`<?php
$period = DatePeriod::createFromIso8601String('R7/2016-05-16T00:00:00Z/P1D');
$start = $period->getStartDate();
echo $start->format(DateTime::ISO8601);`

The above example will output:

    2016-05-16T00:00:00+0000

### See Also

- DatePeriod::getEndDate() - Gets the end date
- DatePeriod::getDateInterval() - Gets the interval

## Table of Contents

- DatePeriod::__construct — Creates a new DatePeriod object
- DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string
- DatePeriod::getDateInterval — Gets the interval
- DatePeriod::getEndDate — Gets the end date
- DatePeriod::getRecurrences — Gets the number of recurrences
- DatePeriod::getStartDate — Gets the start date

# Date/Time Functions

# checkdate

(PHP 4, PHP 5, PHP 7, PHP 8)

checkdate — Validate a Gregorian date

### Description

checkdate(int `$month`, int `$day`, int `$year`): bool

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

### Parameters

`month`

  The month is between 1 and 12 inclusive.

`day`

  The day is within the allowed number of days for the given `month`. Leap `year`s are taken into consideration.

`year`

  The year is between 1 and 32767 inclusive.

### Return Values

Returns `true` if the date given is valid; otherwise returns `false`.

### Examples

Example #1 checkdate() example

`<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));`

The above example will output:

    bool(true)
    bool(false)

### See Also

- mktime() - Get Unix timestamp for a date
- strtotime() - Parse about any English textual datetime description into a Unix timestamp

# date

(PHP 4, PHP 5, PHP 7, PHP 8)

date — Format a Unix timestamp

### Description

date(string `$format`, ?int `$timestamp` = `null`): string

Returns a string formatted according to the given format string using the given integer `timestamp` (Unix timestamp) or the current time if no timestamp is given. In other words, `timestamp` is optional and defaults to the value of time().

Warning

Unix timestamps do not handle timezones. Use the DateTimeImmutable class, and its DateTimeInterface::format() formatting method to format date/time information with a timezone attached.

### Parameters

`format`

  Format accepted by DateTimeInterface::format().

  > Note: date() will always generate `000000` as microseconds since it takes an int parameter, whereas DateTimeInterface::format() does support microseconds if an object of type DateTimeInterface was created with microseconds.

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns a formatted date string.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 date() examples

`<?php
// set the default timezone to use.
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l") . "\n";
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A') . "\n";
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000)) . "\n";
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822) . "\n";
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));`

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

`<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');`

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #3 date() Formatting

`<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
date_default_timezone_set("America/Phoenix");
echo date("F j, Y, g:i a") . "\n"; // March 10, 2001, 5:16 pm
echo date("m.d.y") . "\n"; // 03.10.01
echo date("j, n, Y") . "\n"; // 10, 3, 2001
echo date("Ymd") . "\n"; // 20010310
echo date('h-i-s, j-m-y, it is w Day') . "\n"; // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
echo date('\i\t \i\s \t\h\e jS \d\a\y.') . "\n"; // it is the 10th day.
echo date("D M j G:i:s T Y") . "\n"; // Sat Mar 10 17:16:18 MST 2001
echo date('H:m:s \m \i\s\ \m\o\n\t\h') . "\n"; // 17:03:18 m is month
echo date("H:i:s") . "\n"; // 17:16:18
echo date("Y-m-d H:i:s") . "\n"; // 2001-03-10 17:16:18 (the MySQL DATETIME format)`

To format dates in other languages, IntlDateFormatter::format() can be used instead of date().

### Notes

> Note:

> To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'].

### See Also

- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
- DateTimeInterface::format() - Returns date formatted according to given format
- gmdate() - Format a GMT/UTC date/time
- idate() - Format a local time/date part as integer
- getdate() - Get date/time information
- getlastmod() - Gets time of last page modification
- mktime() - Get Unix timestamp for a date
- IntlDateFormatter::format() - Format the date/time value as a string
- time() - Return current Unix timestamp
- Predefined DateTime Constants

# date_add

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_add — Alias of DateTime::add()

### Description

This function is an alias of: DateTime::add()

# date_create

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_create — create a new DateTime object

### Description

date_create(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`): DateTime|false

This is the procedural version of DateTime::__construct().

Unlike the DateTime constructor, it will return `false` instead of an exception if the passed in `datetime` string is invalid.

### Parameters

See DateTimeImmutable::__construct.

### Return Values

Returns a new DateTime instance or `false` on failure

### See Also

- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
- DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
- DateTime::__construct() - Returns new DateTime object

# date_create_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_create_from_format — Alias of DateTime::createFromFormat()

### Description

This function is an alias of: DateTime::createFromFormat()

# date_create_immutable

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

date_create_immutable — create a new DateTimeImmutable object

### Description

date_create_immutable(string `$datetime` = "now", ?DateTimeZone `$timezone` = `null`): DateTimeImmutable|false

This is the procedural version of DateTimeImmutable::__construct().

Unlike the DateTimeImmutable constructor, it will return `false` instead of an exception if the passed in `datetime` string is invalid.

### Parameters

See DateTimeImmutable::__construct.

### Return Values

Returns a new DateTimeImmutable instance or `false` on failure

### See Also

- DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format

# date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat()

### Description

This function is an alias of: DateTimeImmutable::createFromFormat()

# date_date_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_date_set — Alias of DateTime::setDate()

### Description

This function is an alias of: DateTime::setDate()

# date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

### Description

date_default_timezone_get(): string

In order of preference, this function returns the default timezone by:

- Reading the timezone set using the date_default_timezone_set() function (if any)

- Reading the value of the date.timezone ini option (if set)

If none of the above succeed, date_default_timezone_get() will return a default timezone of `UTC`.

### Parameters

This function has no parameters.

### Return Values

Returns a string.

### Examples

Example #1 Getting the default timezone

`<?php
date_default_timezone_set('Europe/London');
if (date_default_timezone_get()) {
echo 'date_default_timezone_set: ' . date_default_timezone_get() . "\n";
}
if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
}`

The above example will output something similar to:

    date_default_timezone_set: Europe/London
    date.timezone: Europe/London

Example #2 Getting the abbreviation of a timezone

`<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');`

The above example will output:

    America/Los_Angeles => America/Los_Angeles => PST

### See Also

- date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
- List of Supported Timezones

# date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

### Description

date_default_timezone_set(string `$timezoneId`): bool

date_default_timezone_set() sets the default timezone used by all date/time functions.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

### Parameters

`timezoneId`

  The timezone identifier, like `UTC`, `Africa/Lagos`, `Asia/Hong_Kong`, or `Europe/Lisbon`. The list of valid identifiers is available in the List of Supported Timezones.

### Return Values

This function returns `false` if the `timezoneId` isn't valid, or `true` otherwise.

### Examples

Example #1 Getting the default timezone

`<?php
date_default_timezone_set('America/Los_Angeles');
$script_tz = date_default_timezone_get();
$ini_tz = ini_get('date.timezone');
if (strcmp($script_tz, $ini_tz)){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}`

### See Also

- date_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
- List of Supported Timezones

# date_diff

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_diff — Alias of DateTime::diff()

### Description

This function is an alias of: DateTime::diff()

# date_format

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_format — Alias of DateTime::format()

### Description

This function is an alias of: DateTime::format()

# date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_get_last_errors — Alias of DateTimeImmutable::getLastErrors()

### Description

This function is an alias of: DateTimeImmutable::getLastErrors()

# date_interval_create_from_date_string

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_interval_create_from_date_string — Alias of DateInterval::createFromDateString()

### Description

This function is an alias of: DateInterval::createFromDateString()

# date_interval_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_interval_format — Alias of DateInterval::format()

### Description

This function is an alias of: DateInterval::format()

# date_isodate_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_isodate_set — Alias of DateTime::setISODate()

### Description

This function is an alias of: DateTime::setISODate()

# date_modify

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_modify — Alias of DateTime::modify()

### Description

This function is an alias of: DateTime::modify()

# date_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_offset_get — Alias of DateTime::getOffset()

### Description

This function is an alias of: DateTime::getOffset()

# date_parse

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_parse — Returns associative array with detailed info about given date/time

### Description

date_parse(string `$datetime`): array

date_parse() parses the given `datetime` string according to the same rules as strtotime() and DateTimeImmutable::__construct(). Instead of returning a Unix timestamp (with strtotime()) or a DateTimeImmutable object (with DateTimeImmutable::__construct()), it returns an associative array with the information that it could detect in the given `datetime` string.

If no information about a certain group of elements can be found, these array elements will be set to `false` or are missing. If needed for constructing a timestamp or DateTimeImmutable object from the same `datetime` string, more fields can be set to a non-`false` value. See the examples for cases where that happens.

### Parameters

`datetime`

  Date/time in format accepted by DateTimeImmutable::__construct().

### Return Values

Returns array with information about the parsed date/time.

The returned array has keys for `year`, `month`, `day`, `hour`, `minute`, `second`, `fraction`, and `is_localtime`.

If `is_localtime` is present then `zone_type` indicates the type of timezone. For type `1` (UTC offset) the `zone`, `is_dst` fields are added; for type `2` (abbreviation) the fields `tz_abbr`, `is_dst` are added; and for type `3` (timezone identifier) the `tz_abbr`, `tz_id` are added.

If relative time elements are present in the `datetime` string such as `+3 days`, the then returned array includes a nested array with the key `relative`. This array then contains the keys `year`, `month`, `day`, `hour`, `minute`, `second`, and if necessary `weekday`, and `weekdays`, depending on the string that was passed in.

The array includes `warning_count` and `warnings` fields. The first one indicate how many warnings there were. The keys of elements `warnings` array indicate the position in the given `datetime` where the warning occurred, with the string value describing the warning itself.

The array also contains `error_count` and `errors` fields. The first one indicate how many errors were found. The keys of elements `errors` array indicate the position in the given `datetime` where the error occurred, with the string value describing the error itself.

Warning

The number of array elements in the `warnings` and `errors` arrays might be less than `warning_count` or `error_count` if they occurred at the same position.

### Errors/Exceptions

In case the date/time format has an error, the element 'errors' will contain the error messages.

### Changelog

Version | Description
--- | ---
7.2.0 | The `zone` element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance `-120` is now `7200`.

### Examples

Example #1 A date_parse() example with a comprehensive `datetime` string

`<?php
var_dump(date_parse("2006-12-12 10:00:00.5"));`

The above example will output:

    array(12) {
      ["year"]=>
      int(2006)
      ["month"]=>
      int(12)
      ["day"]=>
      int(12)
      ["hour"]=>
      int(10)
      ["minute"]=>
      int(0)
      ["second"]=>
      int(0)
      ["fraction"]=>
      float(0.5)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(false)
    }

The timezone elements only show up if they are included in the given `datetime` string. In that case there will always be a `zone_type` element and a few more depending on its value.

Example #2 date_parse() with timezone abbreviation information

`<?php
var_dump(date_parse("June 2nd, 2022, 10:28:17 BST"));`

The above example will output:

    array(16) {
      ["year"]=>
      int(2022)
      ["month"]=>
      int(6)
      ["day"]=>
      int(2)
      ["hour"]=>
      int(10)
      ["minute"]=>
      int(28)
      ["second"]=>
      int(17)
      ["fraction"]=>
      float(0)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(true)
      ["zone_type"]=>
      int(2)
      ["zone"]=>
      int(0)
      ["is_dst"]=>
      bool(true)
      ["tz_abbr"]=>
      string(3) "BST"
    }

Example #3 date_parse() with timezone identifier information

`<?php
var_dump(date_parse("June 2nd, 2022, 10:28:17 Europe/London"));`

The above example will output:

    array(14) {
      ["year"]=>
      int(2022)
      ["month"]=>
      int(6)
      ["day"]=>
      int(2)
      ["hour"]=>
      int(10)
      ["minute"]=>
      int(28)
      ["second"]=>
      int(17)
      ["fraction"]=>
      float(0)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(true)
      ["zone_type"]=>
      int(3)
      ["tz_id"]=>
      string(13) "Europe/London"
    }

If a more minimal `datetime` string is parsed, less information is available. In this example, all the time parts are returned as `false`.

Example #4 date_parse() with a minimal string

`<?php
var_dump(date_parse("June 2nd, 2022"));`

The above example will output:

    array(12) {
      ["year"]=>
      int(2022)
      ["month"]=>
      int(6)
      ["day"]=>
      int(2)
      ["hour"]=>
      bool(false)
      ["minute"]=>
      bool(false)
      ["second"]=>
      bool(false)
      ["fraction"]=>
      bool(false)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(false)
    }

Relative formats do not influence the values parsed from absolute formats, but are parsed into the "relative" element.

Example #5 date_parse() with relative formats

`<?php
var_dump(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));`

The above example will output:

    array(13) {
      ["year"]=>
      int(2006)
      ["month"]=>
      int(12)
      ["day"]=>
      int(12)
      ["hour"]=>
      int(10)
      ["minute"]=>
      int(0)
      ["second"]=>
      int(0)
      ["fraction"]=>
      float(0.5)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(false)
      ["relative"]=>
      array(6) {
        ["year"]=>
        int(0)
        ["month"]=>
        int(0)
        ["day"]=>
        int(7)
        ["hour"]=>
        int(1)
        ["minute"]=>
        int(0)
        ["second"]=>
        int(0)
      }
    }

Some stanzas, such as `Thursday` will set the time portion of the string to `0`. If `Thursday` is passed to DateTimeImmutable::__construct() it would also have resulted in the hour, minute, second, and fraction being set to `0`. In the example below, the year element is however left as `false`.

Example #6 date_parse() with side-effects

`<?php
var_dump(date_parse("Thursday, June 2nd"));`

The above example will output:

    array(13) {
      ["year"]=>
      bool(false)
      ["month"]=>
      int(6)
      ["day"]=>
      int(2)
      ["hour"]=>
      int(0)
      ["minute"]=>
      int(0)
      ["second"]=>
      int(0)
      ["fraction"]=>
      float(0)
      ["warning_count"]=>
      int(0)
      ["warnings"]=>
      array(0) {
      }
      ["error_count"]=>
      int(0)
      ["errors"]=>
      array(0) {
      }
      ["is_localtime"]=>
      bool(false)
      ["relative"]=>
      array(7) {
        ["year"]=>
        int(0)
        ["month"]=>
        int(0)
        ["day"]=>
        int(0)
        ["hour"]=>
        int(0)
        ["minute"]=>
        int(0)
        ["second"]=>
        int(0)
        ["weekday"]=>
        int(4)
      }
    }

### See Also

- date_parse_from_format() - Get info about given date formatted according to the specified format for parsing a `datetime` with a specific given format
- checkdate() - Validate a Gregorian date for Gregorian date validation
- getdate() - Get date/time information

# date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_parse_from_format — Get info about given date formatted according to the specified format

### Description

date_parse_from_format(string `$format`, string `$datetime`): array

Returns associative array with detailed info about given date/time.

### Parameters

`format`

  Documentation on how the `format` is used, please refer to the documentation of DateTimeImmutable::createFromFormat(). The same rules apply.

`datetime`

  String representing the date/time.

### Return Values

Returns associative array with detailed info about given date/time.

The returned array has keys for `year`, `month`, `day`, `hour`, `minute`, `second`, `fraction`, and `is_localtime`.

If `is_localtime` is present then `zone_type` indicates the type of timezone. For type `1` (UTC offset) the `zone`, `is_dst` fields are added; for type `2` (abbreviation) the fields `tz_abbr`, `is_dst` are added; and for type `3` (timezone identifier) the `tz_abbr`, `tz_id` are added.

The array includes `warning_count` and `warnings` fields. The first one indicate how many warnings there were. The keys of elements `warnings` array indicate the position in the given `datetime` where the warning occurred, with the string value describing the warning itself. An example below shows such a warning.

The array also contains `error_count` and `errors` fields. The first one indicate how many errors were found. The keys of elements `errors` array indicate the position in the given `datetime` where the error occurred, with the string value describing the error itself. An example below shows such an error.

Warning

The number of array elements in the `warnings` and `errors` arrays might be less than `warning_count` or `error_count` if they occurred at the same position.

### Errors/Exceptions

This functions throws ValueError when the `datetime` contains NULL-bytes.

### Changelog

Version | Description
--- | ---
8.0.21, 8.1.8, 8.2.0 | Now throws ValueError when NULL-bytes are passed into `datetime`, which previously was silently ignored.
7.2.0 | The `zone` element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance `-120` is now `7200`.

### Examples

Example #1 date_parse_from_format() example

`<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));`

The above example will output:

    Array
    (
        [year] => 2009
        [month] => 1
        [day] => 6
        [hour] => 13
        [minute] => 0
        [second] => 0
        [fraction] => 0
        [warning_count] => 0
        [warnings] => Array
            (
            )

        [error_count] => 0
        [errors] => Array
            (
            )

        [is_localtime] => 1
        [zone_type] => 1
        [zone] => 3600
        [is_dst] =>
    )

Example #2 date_parse_from_format() with warnings example

`<?php
$date = "26 August 2022 22:30 pm";
$parsed = date_parse_from_format("j F Y G:i a", $date);
echo "Warnings count: ", $parsed['warning_count'], "\n";
foreach ($parsed['warnings'] as $position => $message) {
echo "\tOn position {$position}: {$message}\n";
}`

The above example will output:

    Warnings count: 1
    	On position 23: The parsed time was invalid

Example #3 date_parse_from_format() with errors example

`<?php
$date = "26 August 2022 CEST";
$parsed = date_parse_from_format("j F Y H:i", $date);
echo "Errors count: ", $parsed['error_count'], "\n";
foreach ($parsed['errors'] as $position => $message) {
echo "\tOn position {$position}: {$message}\n";
}`

The above example will output:

    Errors count: 3
    	On position 15: A two digit hour could not be found
    	On position 19: Not enough data available to satisfy format

### See Also

- DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
- checkdate() - Validate a Gregorian date

# date_sub

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_sub — Alias of DateTime::sub()

### Description

This function is an alias of: DateTime::sub()

### See Also

- DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
- DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

# date_sun_info

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

### Description

date_sun_info(int `$timestamp`, float `$latitude`, float `$longitude`): array

### Parameters

`timestamp`

  Unix timestamp.

`latitude`

  Latitude in degrees.

`longitude`

  Longitude in degrees.

### Return Values

Returns an array whose structure is detailed in the following list:

`sunrise`
  The timestamp of the sunrise (zenith angle = 90°35').
`sunset`
  The timestamp of the sunset (zenith angle = 90°35').
`transit`
  The timestamp when the sun is at its zenith, i.e. has reached its topmost point.
`civil_twilight_begin`
  The start of the civil dawn (zenith angle = 96°). It ends at `sunrise`.
`civil_twilight_end`
  The end of the civil dusk (zenith angle = 96°). It starts at `sunset`.
`nautical_twilight_begin`
  The start of the nautical dawn (zenith angle = 102°). It ends at `civil_twilight_begin`.
`nautical_twilight_end`
  The end of the nautical dusk (zenith angle = 102°). It starts at `civil_twilight_end`.
`astronomical_twilight_begin`
  The start of the astronomical dawn (zenith angle = 108°). It ends at `nautical_twilight_begin`.
`astronomical_twilight_end`
  The end of the astronomical dusk (zenith angle = 108°). It starts at `nautical_twilight_end`.

The values of the array elements are either UNIX timestamps, `false` if the sun is below the respective zenith for the whole day, or `true` if the sun is above the respective zenith for the whole day.

### Changelog

Version | Description
--- | ---
7.2.0 | The calculation was fixed with regards to local midnight instead of local noon, which changes the results slightly.

### Examples

Example #1 A date_sun_info() example

`<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
echo "$key: " . date("H:i:s", $val) . "\n";
}`

The above example will output:

    sunrise: 05:52:11
    sunset: 15:41:21
    transit: 10:46:46
    civil_twilight_begin: 05:24:08
    civil_twilight_end: 16:09:24
    nautical_twilight_begin: 04:52:25
    nautical_twilight_end: 16:41:06
    astronomical_twilight_begin: 04:21:32
    astronomical_twilight_end: 17:12:00

Example #2 Polar night, with some processing

`<?php
$tz = new \DateTimeZone('America/Anchorage');
$si = date_sun_info(strtotime("2022-12-21"), 70.21, -148.51);
foreach ($si as $key => $value) {
echo
match ($value) {
true => 'always',
false => 'never',
default => date_create("@{$value}")->setTimeZone($tz)->format( 'H:i:s T' ),
},
": {$key}",
"\n";
}`

The above example will output:

    never: sunrise
    never: sunset
    12:52:18 AKST: transit
    10:53:19 AKST: civil_twilight_begin
    14:51:17 AKST: civil_twilight_end
    09:01:47 AKST: nautical_twilight_begin
    16:42:48 AKST: nautical_twilight_end
    07:40:47 AKST: astronomical_twilight_begin
    18:03:49 AKST: astronomical_twilight_end

Example #3 Midnight sun (Tromsø, Norway)

`<?php
$si = date_sun_info(strtotime("2022-06-26"), 69.68, 18.94);
print_r($si);`

The above example will output:

    Array
    (
        [sunrise] => 1
        [sunset] => 1
        [transit] => 1656240426
        [civil_twilight_begin] => 1
        [civil_twilight_end] => 1
        [nautical_twilight_begin] => 1
        [nautical_twilight_end] => 1
        [astronomical_twilight_begin] => 1
        [astronomical_twilight_end] => 1
    )

Example #4 Calculating length of day (Kyiv)

`<?php
$si = date_sun_info(strtotime('2022-08-26'), 50.45, 30.52);
$diff = $si['sunset'] - $si['sunrise'];
echo "Length of day: ",
floor($diff / 3600), "h ",
floor(($diff % 3600) / 60), "s\n";`

The above example will output:

    Length of day: 13h 56s

# date_sunrise

(PHP 5, PHP 7, PHP 8)

date_sunrise — Returns time of sunrise for a given day and location

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged. Use date_sun_info() instead.

### Description

#[\Deprecated]
date_sunrise(
int `$timestamp`,
int `$returnFormat` = `SUNFUNCS_RET_STRING`,
?float `$latitude` = `null`,
?float `$longitude` = `null`,
?float `$zenith` = `null`,
?float `$utcOffset` = `null`
): string|int|float|false

date_sunrise() returns the sunrise time for a given day (specified as a `timestamp`) and location.

### Parameters

`timestamp`

  The `timestamp` of the day from which the sunrise time is taken.

`returnFormat`

  `returnFormat` constants
  constant | description | example
  --- | --- | ---
  SUNFUNCS_RET_STRING | returns the result as string | 16:46
  SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
  SUNFUNCS_RET_TIMESTAMP | returns the result as int (timestamp) | 1095034606

`latitude`

  Defaults to North, pass in a negative value for South. See also: date.default_latitude

`longitude`

  Defaults to East, pass in a negative value for West. See also: date.default_longitude

`zenith`

  `zenith` is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunrise_zenith

  Common `zenith` angles
  Angle | Description
  --- | ---
  90°50' | Sunrise: the point where the sun becomes visible.
  96° | Civil twilight: conventionally used to signify the start of dawn.
  102° | Nautical twilight: the point at which the horizon starts being visible at sea.
  108° | Astronomical twilight: the point at which the sun starts being the source of any illumination.

`utcOffset`

  Specified in hours. The `utcOffset` is ignored, if `returnFormat` is `SUNFUNCS_RET_TIMESTAMP`.

### Return Values

Returns the sunrise time in a specified `returnFormat` on success or `false` on failure. One potential reason for failure is that the sun does not rise at all, which happens inside the polar circles for part of the year.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated in favor of date_sun_info().
8.0.0 | `latitude`, `longitude`, `zenith` and `utcOffset` are nullable now.

### Examples

Example #1 date_sunrise() example

`<?php
/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);`

The above example will output something similar to:

    Deprecated: Constant SUNFUNCS_RET_STRING is deprecated in script on line 10
    Deprecated: Function date_sunrise() is deprecated since 8.1, use date_sun_info() instead in script on line 10
    Mon Dec 20 2004, sunrise time : 08:54

Example #2 No sunrise

`<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunrise($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));`

The above example will output:

    Deprecated: Constant SUNFUNCS_RET_STRING is deprecated in script on line 3
    Deprecated: Function date_sunrise() is deprecated since 8.1, use date_sun_info() instead in script on line 3
    bool(false)

### See Also

- date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end

# date_sunset

(PHP 5, PHP 7, PHP 8)

date_sunset — Returns time of sunset for a given day and location

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged. Use date_sun_info() instead.

### Description

#[\Deprecated]
date_sunset(
int `$timestamp`,
int `$returnFormat` = `SUNFUNCS_RET_STRING`,
?float `$latitude` = `null`,
?float `$longitude` = `null`,
?float `$zenith` = `null`,
?float `$utcOffset` = `null`
): string|int|float|false

date_sunset() returns the sunset time for a given day (specified as a `timestamp`) and location.

### Parameters

`timestamp`

  The `timestamp` of the day from which the sunset time is taken.

`returnFormat`

  `returnFormat` constants
  constant | description | example
  --- | --- | ---
  SUNFUNCS_RET_STRING | returns the result as string | 16:46
  SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
  SUNFUNCS_RET_TIMESTAMP | returns the result as int (timestamp) | 1095034606

`latitude`

  Defaults to North, pass in a negative value for South. See also: date.default_latitude

`longitude`

  Defaults to East, pass in a negative value for West. See also: date.default_longitude

`zenith`

  `zenith` is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunset_zenith

  Common `zenith` angles
  Angle | Description
  --- | ---
  90°50' | Sunset: the point where the sun becomes invisible.
  96° | Civil twilight: conventionally used to signify the end of dusk.
  102° | Nautical twilight: the point at which the horizon ends being visible at sea.
  108° | Astronomical twilight: the point at which the sun ends being the source of any illumination.

`utcOffset`

  Specified in hours. The `utcOffset` is ignored, if `returnFormat` is `SUNFUNCS_RET_TIMESTAMP`.

### Return Values

Returns the sunset time in a specified `returnFormat` on success or `false` on failure. One potential reason for failure is that the sun does not set at all, which happens inside the polar circles for part of the year.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated in favor of date_sun_info().
8.0.0 | `latitude`, `longitude`, `zenith` and `utcOffset` are nullable now.

### Examples

Example #1 date_sunset() example

`<?php
/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);`

The above example will output something similar to:

    Deprecated: Constant SUNFUNCS_RET_STRING is deprecated in script on line 10
    Deprecated: Function date_sunset() is deprecated since 8.1, use date_sun_info() instead in script on line 10
    Mon Dec 20 2004, sunset time : 18:13

Example #2 No sunset

`<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunset($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));`

The above example will output:

    Deprecated: Constant SUNFUNCS_RET_STRING is deprecated in script on line 3
    Deprecated: Function date_sunset() is deprecated since 8.1, use date_sun_info() instead in script on line 3
    bool(false)

### See Also

- date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end

# date_time_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_time_set — Alias of DateTime::setTime()

### Description

This function is an alias of: DateTime::setTime()

# date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_timestamp_get — Alias of DateTime::getTimestamp()

### Description

This function is an alias of: DateTime::getTimestamp()

# date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_timestamp_set — Alias of DateTime::setTimestamp()

### Description

This function is an alias of: DateTime::setTimestamp()

# date_timezone_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_timezone_get — Alias of DateTime::getTimezone()

### Description

This function is an alias of: DateTime::getTimezone()

# date_timezone_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_timezone_set — Alias of DateTime::setTimezone()

### Description

This function is an alias of: DateTime::setTimezone()

# getdate

(PHP 4, PHP 5, PHP 7, PHP 8)

getdate — Get date/time information

### Description

getdate(?int `$timestamp` = `null`): array

Returns an associative array containing the date information of the `timestamp`, or the current local time if `timestamp` is omitted or `null`.

### Parameters

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns an associative array of information related to the `timestamp`. Elements from the returned associative array are as follows:

Key elements of the returned associative array
Key | Description | Example returned values
--- | --- | ---
`"seconds"` | Numeric representation of seconds | `0` to `59`
`"minutes"` | Numeric representation of minutes | `0` to `59`
`"hours"` | Numeric representation of hours | `0` to `23`
`"mday"` | Numeric representation of the day of the month | `1` to `31`
`"wday"` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday)
`"mon"` | Numeric representation of a month | `1` through `12`
`"year"` | A full numeric representation of a year, 4 digits | Examples: `1999` or `2003`
`"yday"` | Numeric representation of the day of the year | `0` through `365`
`"weekday"` | A full textual representation of the day of the week | `Sunday` through `Saturday`
`"month"` | A full textual representation of a month, such as January or March | `January` through `December`
`0` | Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). | System Dependent, typically `-2147483648` through `2147483647`.

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 getdate() example

`<?php
$today = getdate();
print_r($today);`

The above example will output something similar to:

    Array
    (
        [seconds] => 40
        [minutes] => 58
        [hours] => 21
        [mday] => 17
        [wday] => 2
        [mon] => 6
        [year] => 2003
        [yday] => 167
        [weekday] => Tuesday
        [month] => June
        [0] => 1055901520
    )

### See Also

- date() - Format a Unix timestamp
- idate() - Format a local time/date part as integer
- localtime() - Get the local time
- time() - Return current Unix timestamp
- setlocale() - Set locale information

# gettimeofday

(PHP 4, PHP 5, PHP 7, PHP 8)

gettimeofday — Get current time

### Description

gettimeofday(bool `$as_float` = `false`): array|float

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

### Parameters

`as_float`

  When set to `true`, a float instead of an array is returned.

### Return Values

By default an array is returned. If `as_float` is set, then a float is returned.

Array keys:

- "sec" - seconds since the Unix Epoch
- "usec" - microseconds
- "minuteswest" - minutes west of Greenwich
- "dsttime" - type of dst correction

### Examples

Example #1 gettimeofday() example

`<?php
print_r(gettimeofday());
echo gettimeofday(true);`

The above example will output something similar to:

    Array
    (
        [sec] => 1073504408
        [usec] => 238215
        [minuteswest] => 0
        [dsttime] => 1
    )
    1073504408.23910

# gmdate

(PHP 4, PHP 5, PHP 7, PHP 8)

gmdate — Format a GMT/UTC date/time

### Description

gmdate(string `$format`, ?int `$timestamp` = `null`): string

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

### Parameters

`format`

  The format of the outputted date string. See the formatting options for the date() function.

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns a formatted date string.

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 gmdate() example

`<?php
date_default_timezone_set("Europe/Helsinki");
echo date("M d Y H:i:s e", mktime(0, 0, 0, 1, 1, 1998)) . "\n";
echo gmdate("M d Y H:i:s e", mktime(0, 0, 0, 1, 1, 1998));`

The above example will output:

    Jan 01 1998 00:00:00 Europe/Helsinki
    Dec 31 1997 22:00:00 UTC

### See Also

- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
- DateTimeInterface::format() - Returns date formatted according to given format
- date() - Format a Unix timestamp
- mktime() - Get Unix timestamp for a date
- gmmktime() - Get Unix timestamp for a GMT date
- IntlDateFormatter::format() - Format the date/time value as a string

# gmmktime

(PHP 4, PHP 5, PHP 7, PHP 8)

gmmktime — Get Unix timestamp for a GMT date

### Description

gmmktime(
int `$hour`,
?int `$minute` = `null`,
?int `$second` = `null`,
?int `$month` = `null`,
?int `$day` = `null`,
?int `$year` = `null`
): int|false

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), optional arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

Calling gmmktime() without any arguments is not supported, and will result in an ArgumentCountError. time() can be used to get the current timestamp.

### Parameters

`hour`

  The number of the hour relative to the start of the day determined by `month`, `day` and `year`. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

`minute`

  The number of the minute relative to the start of the `hour`. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

`second`

  The number of seconds relative to the start of the `minute`. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

`month`

  The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

`day`

  The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

`year`

  The year

### Return Values

Returns a int Unix timestamp on success, or `false` if the timestamp doesn't fit in a PHP integer.

### Changelog

Version | Description
--- | ---
8.0.0 | `hour` is no longer optional. If you need a Unix timestamp, use time().
8.0.0 | `minute`, `second`, `month`, `day` and `year` are nullable now.

### Examples

Example #1 gmmktime() basic example

`<?php
date_default_timezone_set("Indian/Maldives");
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));`

The above example will output:

    July 1, 2000 is on a Saturday

### See Also

- The DateTimeImmutable class
- mktime() - Get Unix timestamp for a date
- date() - Format a Unix timestamp
- time() - Return current Unix timestamp

# gmstrftime

(PHP 4, PHP 5, PHP 7, PHP 8)

gmstrftime — Format a GMT/UTC time/date according to locale settings

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

Alternatives to this function include:

- gmdate()
- IntlDateFormatter::format()

### Description

#[\Deprecated]
gmstrftime(string `$format`, ?int `$timestamp` = `null`): string|false

Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".

Warning

This function depends on operating system locale information, which might be inconsistent with each other, or not available at all. Instead use the IntlDateFormatter::format() method.

### Parameters

`format`

  See description in strftime().

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns a string formatted according to the given format string using the given `timestamp` or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale(). On failure, `false` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 gmstrftime() example

`<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";`

### See Also

- IntlDateFormatter::format() - Format the date/time value as a string
- DateTimeInterface::format() - Returns date formatted according to given format
- strftime() - Format a local time/date according to locale settings

# idate

(PHP 5, PHP 7, PHP 8)

idate — Format a local time/date part as integer

### Description

idate(string `$format`, ?int `$timestamp` = `null`): int|false

Returns a number formatted according to the given format string using the given integer `timestamp` or the current local time if no timestamp is given. In other words, `timestamp` is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the `format` parameter.

### Parameters

`format`

  The following characters are recognized in the `format` parameter string
  `format` character | Description
  --- | ---
  `B` | Swatch Beat/Internet Time
  `d` | Day of the month
  `h` | Hour (12 hour format)
  `H` | Hour (24 hour format)
  `i` | Minutes
  `I` (uppercase i) | returns `1` if DST is activated, `0` otherwise
  `L` (uppercase l) | returns `1` for leap year, `0` otherwise
  `m` | Month number
  `N` | ISO-8601 day of the week (`1` for Monday through `7` for Sunday)
  `o` | ISO-8601 year (4 digits)
  `s` | Seconds
  `t` | Days in current month
  `U` | Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time()
  `w` | Day of the week (`0` on Sunday)
  `W` | ISO-8601 week number of year, weeks starting on Monday
  `y` | Year (1 or 2 digits - check note below)
  `Y` | Year (4 digits)
  `z` | Day of the year
  `Z` | Timezone offset in seconds

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns an int on success, or `false` on failure.

As idate() always returns an int and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.2.0 | Adds the `N` (ISO-8601 day of the week) and `o` (ISO-8601 year) format characters.
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 idate() example

`<?php
$timestamp = strtotime('1st January 2004'); // 1072915200
// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp) . "\n";
$timestamp = strtotime('1st January 2024'); // 1704067200
echo idate('y', $timestamp);`

The above example will output:

    4
    24

### See Also

- DateTimeInterface::format() - Returns date formatted according to given format
- date() - Format a Unix timestamp
- getdate() - Get date/time information
- time() - Return current Unix timestamp

# localtime

(PHP 4, PHP 5, PHP 7, PHP 8)

localtime — Get the local time

### Description

localtime(?int `$timestamp` = `null`, bool `$associative` = `false`): array

The localtime() function returns an array identical to that of the structure returned by the C function call.

### Parameters

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

`associative`

  Determines whether the function should return a regular, numerically indexed array, or an associative one.

### Return Values

If `associative` is set to `false` or not supplied then the array is returned as a regular, numerically indexed array. If `associative` is set to `true` then localtime() returns an associative array containing the elements of the structure returned by the C function call to localtime. The keys of the associative array are as follows:

- "tm_sec" - seconds, `0` to `59`
- "tm_min" - minutes, `0` to `59`
- "tm_hour" - hours, `0` to `23`
- "tm_mday" - day of the month, `1` to `31`
- "tm_mon" - month of the year, `0` (Jan) to `11` (Dec)
- "tm_year" - years since 1900
- "tm_wday" - day of the week, `0` (Sun) to `6` (Sat)
- "tm_yday" - day of the year, `0` to `365`
- "tm_isdst" - is daylight savings time in effect? Positive if yes, `0` if not, negative if unknown.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

Example #1 localtime() example

`<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);`

The above example will output something similar to:

    Array
    (
        [0] => 24
        [1] => 3
        [2] => 19
        [3] => 3
        [4] => 3
        [5] => 105
        [6] => 0
        [7] => 92
        [8] => 1
    )

    Array
    (
        [tm_sec] => 24
        [tm_min] => 3
        [tm_hour] => 19
        [tm_mday] => 3
        [tm_mon] => 3
        [tm_year] => 105
        [tm_wday] => 0
        [tm_yday] => 92
        [tm_isdst] => 1
    )

### See Also

- getdate() - Get date/time information

# microtime

(PHP 4, PHP 5, PHP 7, PHP 8)

microtime — Return current Unix timestamp with microseconds

### Description

microtime(bool `$as_float` = `false`): string|float

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

For performance measurements, using hrtime() is recommended.

### Parameters

`as_float`

  If used and set to `true`, microtime() will return a float instead of a string, as described in the return values section below.

### Return Values

By default, microtime() returns a string in the form "msec sec", where `sec` is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and `msec` measures microseconds that have elapsed since `sec` and is also expressed in seconds as a decimal fraction.

If `as_float` is set to `true`, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

### Examples

Example #1 Timing script execution

`<?php
$time_start = microtime(true);
// Sleep for a while
usleep(10_000);
$time_end = microtime(true);
$time = $time_end - $time_start;
print "Did nothing in $time seconds\n";`

Example #2 microtime() and `REQUEST_TIME_FLOAT`

`<?php
// Randomize sleeping time
usleep(random_int(10_000, 1_000_000));
// REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";`

### See Also

- time() - Return current Unix timestamp
- hrtime() - Get the system's high resolution time

# mktime

(PHP 4, PHP 5, PHP 7, PHP 8)

mktime — Get Unix timestamp for a date

### Description

mktime(
int `$hour`,
?int `$minute` = `null`,
?int `$second` = `null`,
?int `$month` = `null`,
?int `$day` = `null`,
?int `$year` = `null`
): int|false

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

Any optional arguments omitted or `null` will be set to the current value according to the local date and time.

Warning

Please note that the ordering of arguments is in an odd order: `month`, `day`, `year`, and not in the more reasonable order of `year`, `month`, `day`.

Calling mktime() without arguments is not supported, and will result in an ArgumentCountError. time() can be used to get the current timestamp.

### Parameters

`hour`

  The number of the hour relative to the start of the day determined by `month`, `day` and `year`. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

`minute`

  The number of the minute relative to the start of the `hour`. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

`second`

  The number of seconds relative to the start of the `minute`. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

`month`

  The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

`day`

  The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

`year`

  The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for `year` is somewhere between 1901 and 2038.

### Return Values

mktime() returns the Unix timestamp of the arguments given, or `false` if the timestamp doesn't fit in a PHP integer.

### Changelog

Version | Description
--- | ---
8.0.0 | `hour` is no longer optional. If you need a Unix timestamp, use time().
8.0.0 | `minute`, `second`, `month`, `day` and `year` are nullable now.

### Examples

Example #1 mktime() basic example

`<?php
// Set the default timezone to use.
date_default_timezone_set('UTC');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000)) . "\n";
// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006)) . "\n";`

The above example will output something similar to:

    July 1, 2000 is on a Saturday
    2006-04-05T01:02:03+00:00

Example #2 mktime() example

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

`<?php
date_default_timezone_set('America/New_York');
echo date("c", mktime(0, 0, 0, 12, 32, 1997)) . "\n";
echo date("c", mktime(0, 0, 0, 13, 1, 1997)) . "\n";
echo date("c", mktime(0, 0, 0, 1, 1, 1998)) . "\n";
echo date("c", mktime(0, 0, 0, 1, 1, 98)) . "\n";`

The above example will output something similar to:

    1998-01-01T00:00:00-05:00
    1998-01-01T00:00:00-05:00
    1998-01-01T00:00:00-05:00
    1998-01-01T00:00:00-05:00

Example #3 Using mktime to find relative dates

`<?php
date_default_timezone_set('Asia/Tokyo');
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
print date('c', $tomorrow) . "\n";
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
print date('c', $lastmonth) . "\n";
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1) . "\n";
print date('c', $nextyear) . "\n";`

The above example will output something similar to:

    2025-09-30T00:00:00+09:00
    2025-08-29T00:00:00+09:00
    2026-09-29T00:00:00+09:00

> Note:

> This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Example #4 Last day of a month

The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".

`<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo 'Last day in Feb 2000 is: ', date('d', $lastday) . "\n";
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo 'Last day in Feb 2000 is: ', date('d', $lastday) . "\n";`

The above example will output:

    Last day in Feb 2000 is: 29
    Last day in Feb 2000 is: 29

### See Also

- The DateTimeImmutable class
- checkdate() - Validate a Gregorian date
- gmmktime() - Get Unix timestamp for a GMT date
- date() - Format a Unix timestamp
- time() - Return current Unix timestamp

# strftime

(PHP 4, PHP 5, PHP 7, PHP 8)

strftime — Format a local time/date according to locale settings

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

Alternatives to this function include:

- date()
- IntlDateFormatter::format()

### Description

#[\Deprecated]
strftime(string `$format`, ?int `$timestamp` = `null`): string|false

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Warning

Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to `Jan 1, 1970` - will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems, a complete overview of supported conversion specifiers can be found at » MSDN. Instead use the IntlDateFormatter::format() method.

### Parameters

`format`

  The following characters are recognized in the `format` parameter string
  `format` | Description | Example returned values
  --- | --- | ---
  Day | --- | ---
  `%a` | An abbreviated textual representation of the day | `Sun` through `Sat`
  `%A` | A full textual representation of the day | `Sunday` through `Saturday`
  `%d` | Two-digit day of the month (with leading zeros) | `01` to `31`
  `%e` | Day of the month, with a space preceding single digits. Not implemented as described on Windows. See below for more information. | `1` to `31`
  `%j` | Day of the year, 3 digits with leading zeros | `001` to `366`
  `%u` | ISO-8601 numeric representation of the day of the week | `1` (for Monday) through `7` (for Sunday)
  `%w` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday)
  Week | --- | ---
  `%U` | Week number of the given year, starting with the first Sunday as the first week | `13` (for the 13th full week of the year)
  `%V` | ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week | `01` through `53` (where 53 accounts for an overlapping week)
  `%W` | A numeric representation of the week of the year, starting with the first Monday as the first week | `46` (for the 46th week of the year beginning with a Monday)
  Month | --- | ---
  `%b` | Abbreviated month name, based on the locale | `Jan` through `Dec`
  `%B` | Full month name, based on the locale | `January` through `December`
  `%h` | Abbreviated month name, based on the locale (an alias of %b) | `Jan` through `Dec`
  `%m` | Two digit representation of the month | `01` (for January) through `12` (for December)
  Year | --- | ---
  `%C` | Two digit representation of the century (year divided by 100, truncated to an integer) | `19` for the 20th Century
  `%g` | Two digit representation of the year going by ISO-8601:1988 standards (see %V) | Example: `09` for the week of January 6, 2009
  `%G` | The full four-digit version of %g | Example: `2008` for the week of January 3, 2009
  `%y` | Two digit representation of the year | Example: `09` for 2009, `79` for 1979
  `%Y` | Four digit representation for the year | Example: `2038`
  Time | --- | ---
  `%H` | Two digit representation of the hour in 24-hour format | `00` through `23`
  `%k` | Hour in 24-hour format, with a space preceding single digits | `0` through `23`
  `%I` | Two digit representation of the hour in 12-hour format | `01` through `12`
  `%l (lower-case 'L')` | Hour in 12-hour format, with a space preceding single digits | `1` through `12`
  `%M` | Two digit representation of the minute | `00` through `59`
  `%p` | UPPER-CASE 'AM' or 'PM' based on the given time | Example: `AM` for 00:31, `PM` for 22:23. The exact result depends on the Operating System, and they can also return lower-case variants, or variants with dots (such as `a.m.`).
  `%P` | lower-case 'am' or 'pm' based on the given time | Example: `am` for 00:31, `pm` for 22:23. Not supported by all Operating Systems.
  `%r` | Same as "%I:%M:%S %p" | Example: `09:34:17 PM` for 21:34:17
  `%R` | Same as "%H:%M" | Example: `00:35` for 12:35 AM, `16:44` for 4:44 PM
  `%S` | Two digit representation of the second | `00` through `59`
  `%T` | Same as "%H:%M:%S" | Example: `21:34:17` for 09:34:17 PM
  `%X` | Preferred time representation based on locale, without the date | Example: `03:59:16` or `15:59:16`
  `%z` | The time zone offset. Not implemented as described on Windows. See below for more information. | Example: `-0500` for US Eastern Time
  `%Z` | The time zone abbreviation. Not implemented as described on Windows. See below for more information. | Example: `EST` for Eastern Time
  Time and Date Stamps | --- | ---
  `%c` | Preferred date and time stamp based on locale | Example: `Tue Feb 5 00:45:10 2009` for February 5, 2009 at 12:45:10 AM
  `%D` | Same as "%m/%d/%y" | Example: `02/05/09` for February 5, 2009
  `%F` | Same as "%Y-%m-%d" (commonly used in database datestamps) | Example: `2009-02-05` for February 5, 2009
  `%s` | Unix Epoch Time timestamp (same as the time() function) | Example: `305815200` for September 10, 1979 08:40:00 AM
  `%x` | Preferred date representation based on locale, without the time | Example: `02/05/09` for February 5, 2009
  Miscellaneous | --- | ---
  `%n` | A newline character ("\n") | ---
  `%t` | A Tab character ("\t") | ---
  `%%` | A literal percentage character ("%") | ---

  Warning

  Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a result, `%u` may not function as described in this manual.

  Warning

  Windows only:

  The `%e` modifier is not supported in the Windows implementation of this function. To achieve this value, the `%#d` modifier can be used instead. The example below illustrates how to write a cross platform compatible function.

  The `%z` and `%Z` modifiers both return the time zone name instead of the offset or abbreviation.

  Warning

  macOS and musl only: The `%P` modifier is not supported in the macOS implementation of this function.

`timestamp`

  The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

### Return Values

Returns a string formatted according `format` using the given `timestamp` or the current local time if no timestamp is given. Month and weekday names and other language-dependent strings respect the current locale set with setlocale(). The function returns `false` if `format` is empty, contains unsupported conversion specifiers, or if the length of the returned string would be greater than `4095`.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 `E_WARNING` messages and return `false`. On other operating systems you may not get any `E_WARNING` messages and the output may contain the conversion specifiers unconverted.

### Changelog

Version | Description
--- | ---
8.0.0 | `timestamp` is nullable now.

### Examples

This example will work if you have the respective locales installed in your system.

Example #1 strftime() locale examples

`<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");`

Example #2 ISO 8601:1988 week number example

`<?php
/* December 2002 / January 2003
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 16 17 18 19 20 21 22
52 23 24 25 26 27 28 29
1 30 31 1 2 3 4 5
2 6 7 8 9 10 11 12
3 13 14 15 16 17 18 19 */
// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";
// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";
// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";
// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";
/* December 2004 / January 2005
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 13 14 15 16 17 18 19
52 20 21 22 23 24 25 26
53 27 28 29 30 31 1 2
1 3 4 5 6 7 8 9
2 10 11 12 13 14 15 16 */
// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";
// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";
// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";
// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";`

Example #3 Cross platform compatible example using the `%e` modifier

`<?php
// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';
// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
}
echo strftime($format);`

Example #4 Display all known and unknown formats

`<?php
// Describe the formats
$strftimeFormats = array(
'A' => 'A full textual representation of the day',
'B' => 'Full month name, based on the locale',
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
'D' => 'Same as "%m/%d/%y"',
'E' => '',
'F' => 'Same as "%Y-%m-%d"',
'G' => 'The full four-digit version of %g',
'H' => 'Two digit representation of the hour in 24-hour format',
'I' => 'Two digit representation of the hour in 12-hour format',
'J' => '',
'K' => '',
'L' => '',
'M' => 'Two digit representation of the minute',
'N' => '',
'O' => '',
'P' => 'lower-case "am" or "pm" based on the given time',
'Q' => '',
'R' => 'Same as "%H:%M"',
'S' => 'Two digit representation of the second',
'T' => 'Same as "%H:%M:%S"',
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
'X' => 'Preferred time representation based on locale, without the date',
'Y' => 'Four digit representation for the year',
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
'a' => 'An abbreviated textual representation of the day',
'b' => 'Abbreviated month name, based on the locale',
'c' => 'Preferred date and time stamp based on local',
'd' => 'Two-digit day of the month (with leading zeros)',
'e' => 'Day of the month, with a space preceding single digits',
'f' => '',
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
'i' => '',
'j' => 'Day of the year, 3 digits with leading zeros',
'k' => 'Hour in 24-hour format, with a space preceding single digits',
'l' => 'Hour in 12-hour format, with a space preceding single digits',
'm' => 'Two digit representation of the month',
'n' => 'A newline character ("\n")',
'o' => '',
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
'q' => '',
'r' => 'Same as "%I:%M:%S %p"',
's' => 'Unix Epoch Time timestamp',
't' => 'A Tab character ("\t")',
'u' => 'ISO-8601 numeric representation of the day of the week',
'v' => '',
'w' => 'Numeric representation of the day of the week',
'x' => 'Preferred date representation based on locale, without the time',
'y' => 'Two digit representation of the year',
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
'%' => 'A literal percentage character ("%")',
);
// Results
$strftimeValues = array();
// Evaluate the formats whilst suppressing any errors
foreach ($strftimeFormats as $format => $description) {
if (false !== ($value = @strftime("%{$format}"))) {
$strftimeValues[$format] = $value;
}
}
// Find the longest value
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));
// Report known formats
foreach ($strftimeValues as $format => $value) {
echo "Known format : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}
// Report unknown formats
foreach (array_diff_key($strftimeFormats, $strftimeValues) as $format => $description) {
echo "Unknown format : '{$format}' ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}`

The above example will output something similar to:

    Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
    Known format   : 'B' = 'December'          ( Full month name, based on the locale )
    Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
    Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
    Known format   : 'M' = '24'                ( Two digit representation of the minute )
    Known format   : 'S' = '44'                ( Two digit representation of the second )
    Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
    Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
    Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
    Known format   : 'Y' = '2010'              ( Four digit representation for the year )
    Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
    Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
    Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
    Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
    Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
    Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
    Known format   : 'm' = '12'                ( Two digit representation of the month )
    Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
    Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
    Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
    Known format   : 'y' = '10'                ( Two digit representation of the year )
    Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
    Known format   : '%' = '%'                 ( A literal percentage character ("%") )
    Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
    Unknown format : 'D'                       ( Same as "%m/%d/%y" )
    Unknown format : 'E'
    Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
    Unknown format : 'G'                       ( The full four-digit version of %g )
    Unknown format : 'J'
    Unknown format : 'K'
    Unknown format : 'L'
    Unknown format : 'N'
    Unknown format : 'O'
    Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
    Unknown format : 'Q'
    Unknown format : 'R'                       ( Same as "%H:%M" )
    Unknown format : 'T'                       ( Same as "%H:%M:%S" )
    Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
    Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
    Unknown format : 'f'
    Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
    Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
    Unknown format : 'i'
    Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
    Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
    Unknown format : 'n'                       ( A newline character ("\n") )
    Unknown format : 'o'
    Unknown format : 'q'
    Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
    Unknown format : 's'                       ( Unix Epoch Time timestamp )
    Unknown format : 't'                       ( A Tab character ("\t") )
    Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
    Unknown format : 'v'

### Notes

> Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.

### See Also

- IntlDateFormatter::format() - Format the date/time value as a string
- DateTimeInterface::format() - Returns date formatted according to given format
- » Online strftime() format design tool
- setlocale() - Set locale information
- mktime() - Get Unix timestamp for a date
- strptime() - Parse a time/date generated with strftime
- gmstrftime() - Format a GMT/UTC time/date according to locale settings
- » Open Group specification of strftime()

# strptime

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

strptime — Parse a time/date generated with strftime()

Warning

This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
strptime(string `$timestamp`, string `$format`): array|false

strptime() returns an array with the `timestamp` parsed, or `false` on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (`LC_TIME`).

### Parameters

`timestamp` (string)

  The string to parse (e.g. returned from strftime()).

`format` (string)

  The format used in `timestamp` (e.g. the same as used in strftime()). Note that some of the format options available to strftime() may not have any effect within strptime(); the exact subset that are supported will vary based on the operating system and C library in use.

  For more information about the format options, read the strftime() page.

### Return Values

Returns an array or `false` on failure.

The following parameters are returned in the array
parameters | Description
--- | ---
`"tm_sec"` | Seconds after the minute (0-61)
`"tm_min"` | Minutes after the hour (0-59)
`"tm_hour"` | Hour since midnight (0-23)
`"tm_mday"` | Day of the month (1-31)
`"tm_mon"` | Months since January (0-11)
`"tm_year"` | Years since 1900
`"tm_wday"` | Days since Sunday (0-6)
`"tm_yday"` | Days since January 1 (0-365)
`"unparsed"` | the `timestamp` part which was not recognized using the specified `format`

### Changelog

Version | Description
--- | ---
8.1.0 | This function has been deprecated. Use date_parse_from_format() instead (for locale-independent parsing), or IntlDateFormatter::parse() (for locale-dependent parsing)

### Examples

Example #1 strptime() example

`<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));`

The above example will output something similar to:

    03/10/2004 15:54:19

    Array
    (
        [tm_sec] => 19
        [tm_min] => 54
        [tm_hour] => 15
        [tm_mday] => 3
        [tm_mon] => 9
        [tm_year] => 104
        [tm_wday] => 0
        [tm_yday] => 276
        [unparsed] =>
    )

### Notes

> Note: This function is not implemented on Windows platforms.

> Note:

> Internally, this function calls the `strptime()` function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended.

> Note:

> `"tm_sec"` includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

### See Also

- IntlDateFormatter::parse() - Parse string to a timestamp value
- DateTime::createFromFormat() - Parses a time string according to a specified format
- checkdate() - Validate a Gregorian date
- strftime() - Format a local time/date according to locale settings
- date_parse_from_format() - Get info about given date formatted according to the specified format

# strtotime

(PHP 4, PHP 5, PHP 7, PHP 8)

strtotime — Parse about any English textual datetime description into a Unix timestamp

### Description

strtotime(string `$datetime`, ?int `$baseTimestamp` = `null`): int|false

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in `baseTimestamp`, or the current time if `baseTimestamp` is not supplied. The date string parsing is defined in Date and Time Formats, and has several subtle considerations. Reviewing the full details there is strongly recommended.

Warning

The Unix timestamp that this function returns does not contain information about time zones. In order to do calculations with date/time information, you should use the more capable DateTimeImmutable.

Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See date_default_timezone_get() on the various ways to define the default time zone.

### Parameters

`datetime`

  A date/time string. Valid formats are explained in Date and Time Formats.

`baseTimestamp`

  The timestamp which is used as a base for the calculation of relative dates.

### Return Values

Returns a timestamp on success, `false` otherwise.

### Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

### Changelog

Version | Description
--- | ---
8.0.0 | `baseTimestamp` is nullable now.

### Examples

Example #1 A strtotime() example

`<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";`

Example #2 Checking for failure

`<?php
$str = 'Not Good';
if (($timestamp = strtotime($str)) === false) {
echo "The string ($str) is bogus";
} else {
echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}`

### Notes

> Note:

> "Relative" date in this case also means that if a particular component of the date/time stamp is not provided, it will be taken verbatim from the `baseTimestamp`. That is, `strtotime('February')`, if run on the 31st of May 2022, will be interpreted as `31 February 2022`, which will overflow into a timestamp on `3 March`. (In a leap year, it would be `2 March`.) Using `strtotime('1 February')` or `strtotime('first day of February')` would avoid that problem.

> Note:

> If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

> Note:

> The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

> For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.

> Note:

> Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub().

### See Also

- DateTimeImmutable
- DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
- Date and Time Formats
- checkdate() - Validate a Gregorian date
- strptime() - Parse a time/date generated with strftime

# time

(PHP 4, PHP 5, PHP 7, PHP 8)

time — Return current Unix timestamp

### Description

time(): int

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

> Note:

> Unix timestamps do not contain any information with regards to any local timezone. It is recommended to use the DateTimeImmutable class for handling date and time information in order to avoid the pitfalls that come with just Unix timestamps.

### Parameters

This function has no parameters.

### Return Values

Returns the current timestamp.

### Examples

Example #1 time() example

`<?php
echo 'Now: '. time();`

The above example will output something similar to:

    Now: 1660338149

### Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'].

### See Also

- DateTimeImmutable
- date() - Format a Unix timestamp
- microtime() - Return current Unix timestamp with microseconds

# timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations()

### Description

This function is an alias of: DateTimeZone::listAbbreviations()

# timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers()

### Description

This function is an alias of: DateTimeZone::listIdentifiers()

# timezone_location_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

timezone_location_get — Alias of DateTimeZone::getLocation()

### Description

This function is an alias of: DateTimeZone::getLocation()

# timezone_name_from_abbr

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset

### Description

timezone_name_from_abbr(string `$abbr`, int `$utcOffset` = -1, int `$isDST` = -1): string|false

### Parameters

`abbr`

  Time zone abbreviation.

`utcOffset`

  Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to `abbr` is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

`isDST`

  Daylight saving time indicator. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the `utcOffset` is assumed to be an offset with daylight saving in effect; if 0, then `utcOffset` is assumed to be an offset without daylight saving in effect. If `abbr` doesn't exist then the time zone is searched solely by the `utcOffset` and `isDST`.

### Return Values

Returns time zone name on success or `false` on failure.

### Examples

Example #1 A timezone_name_from_abbr() example

`<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";`

The above example will output something similar to:

    Europe/Berlin
    Europe/Paris

### See Also

- timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

# timezone_name_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_name_get — Alias of DateTimeZone::getName()

### Description

This function is an alias of: DateTimeZone::getName()

# timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_offset_get — Alias of DateTimeZone::getOffset()

### Description

This function is an alias of: DateTimeZone::getOffset()

# timezone_open

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_open — Alias of DateTimeZone::__construct()

### Description

This function is an alias of: DateTimeZone::__construct()

# timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_transitions_get — Alias of DateTimeZone::getTransitions()

### Description

This function is an alias of: DateTimeZone::getTransitions()

# timezone_version_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

timezone_version_get — Gets the version of the timezonedb

### Description

timezone_version_get(): string

Returns the current version of the timezonedb.

### Parameters

This function has no parameters.

### Return Values

Returns a string in the format `YYYY.increment`, such as `2022.2`.

If you have a timezone database version that is old (for example, it doesn't show the current year), then you can update the timezone information by either upgrading your PHP version, or installing the » timezonedb PECL package.

Some Linux distributions patch PHP's date/time support to use an alternative source for timezone information. In which case this function will return `0.system`. You are encouraged to install the » timezonedb PECL package in that case as well.

### Examples

Example #1 Getting the timezonedb version

`<?php
echo timezone_version_get();`

The above example will output something similar to:

    2022.2

### See Also

- List of Supported Timezones

## Table of Contents

- checkdate — Validate a Gregorian date
- date — Format a Unix timestamp
- date_add — Alias of DateTime::add
- date_create — create a new DateTime object
- date_create_from_format — Alias of DateTime::createFromFormat
- date_create_immutable — create a new DateTimeImmutable object
- date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
- date_date_set — Alias of DateTime::setDate
- date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
- date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
- date_diff — Alias of DateTime::diff
- date_format — Alias of DateTime::format
- date_get_last_errors — Alias of DateTimeImmutable::getLastErrors
- date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
- date_interval_format — Alias of DateInterval::format
- date_isodate_set — Alias of DateTime::setISODate
- date_modify — Alias of DateTime::modify
- date_offset_get — Alias of DateTime::getOffset
- date_parse — Returns associative array with detailed info about given date/time
- date_parse_from_format — Get info about given date formatted according to the specified format
- date_sub — Alias of DateTime::sub
- date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
- date_sunrise — Returns time of sunrise for a given day and location
- date_sunset — Returns time of sunset for a given day and location
- date_time_set — Alias of DateTime::setTime
- date_timestamp_get — Alias of DateTime::getTimestamp
- date_timestamp_set — Alias of DateTime::setTimestamp
- date_timezone_get — Alias of DateTime::getTimezone
- date_timezone_set — Alias of DateTime::setTimezone
- getdate — Get date/time information
- gettimeofday — Get current time
- gmdate — Format a GMT/UTC date/time
- gmmktime — Get Unix timestamp for a GMT date
- gmstrftime — Format a GMT/UTC time/date according to locale settings
- idate — Format a local time/date part as integer
- localtime — Get the local time
- microtime — Return current Unix timestamp with microseconds
- mktime — Get Unix timestamp for a date
- strftime — Format a local time/date according to locale settings
- strptime — Parse a time/date generated with strftime
- strtotime — Parse about any English textual datetime description into a Unix timestamp
- time — Return current Unix timestamp
- timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations
- timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
- timezone_location_get — Alias of DateTimeZone::getLocation
- timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset
- timezone_name_get — Alias of DateTimeZone::getName
- timezone_offset_get — Alias of DateTimeZone::getOffset
- timezone_open — Alias of DateTimeZone::__construct
- timezone_transitions_get — Alias of DateTimeZone::getTransitions
- timezone_version_get — Gets the version of the timezonedb

# Date/Time Errors and Exceptions

- DateError (extends Error)
  - DateObjectError DateRangeError
- DateException (extends Exception)
  - - DateInvalidOperationException
    - DateInvalidTimezoneException
    - DateMalformedIntervalStringException
    - DateMalformedPeriodStringException
    - DateMalformedStringException

# Supported Date and Time Formats

This section describes all the different formats in a BNF-like format, that the DateTimeImmutable, DateTime, date_create_immutable(), date_create(), date_parse(), and strtotime() parser understands. The formats are grouped by section. In most cases formats from different sections, separated by whitespace, comma or dot, can be used in the same date/time string. For each of the supported formats, one or more examples are given, as well as a description for the format. Characters in single quotes in the formats are case-insensitive (`'t'` could be `t` or `T`), characters in double quotes are case-sensitive (`"T"` is only `T`).

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

A general set of rules should be taken into account.

1. The parser, allows for each unit (year, month, day, hour, minute, second) the full range of values. For a year that's just 4 digits, for a month that's 0-12, day is 0-31, hour is 0-24, and minute is 0-59.
2. 60 is allowed for seconds, as sometimes date strings with that leapsecond do show up. But PHP implements Unix time where "60" is not a valid second number and hence it overflows.
3. strtotime() returns `false` if any number is outside of the ranges, and DateTimeImmutable::__construct() throws an exception.
4. If a string contains a date, all time elements are reset to 0.
5. All less-significant time elements are reset to 0 if any part of a time is present in the given string.
6. The parser is dumb, and doesn't do any checks to make it faster (and more generic).
7. Besides rules for individual time elements, the parser also understand more specific compound formats, such as parsing Unix timestamps (`@1690388256`) and ISO Weekdates (`2008-W28-3`).

8. There is an additional check if an invalid date is provided:

   `<?php
   $res = date_parse("2015-09-31");
   var_dump($res["warnings"]);`

   The above example will output:

       array(1) {
         [11] =>
         string(27) "The parsed date was invalid"
       }

9. It is already possible to handle the edge cases, but then DateTimeImmutable::createFromFormat() must be used while supplying the correct format.

   `<?php
   $res = DateTimeImmutable::createFromFormat("Y-m-d", "2015-09-34");
   var_dump($res);`

   The above example will output:

       object(DateTimeImmutable)#1 (3) {
         ["date"]=>
         string(26) "2015-10-04 17:24:43.000000"
         ["timezone_type"]=>
         int(3)
         ["timezone"]=>
         string(13) "Europe/London"
       }

## Time Formats

This page describes the different date/time formats in a BNF-like syntax, that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Formats | Examples
--- | --- | ---
`frac` | . [0-9]+ | ".21342", ".85"
`hh` | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
`HH` | [01][0-9] | "2"[0-4] | "04", "07", "19"
`meridian` | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
`MM` | [0-5][0-9] | "00", "12", "59"
`II` | [0-5][0-9] | "00", "12", "59"
`space` | [ \t] |
`tz` | "("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ | "CEST", "Europe/Amsterdam", "America/Indiana/Knox"
`tzcorrection` | "GMT"? [+-] `hh` ":"? `MM`? | "+0400", "GMT-07:00", "-07:00"

12 Hour Notation
Description | Format | Examples
--- | --- | ---
Hour only, with meridian | `hh` `space`? `meridian` | "4 am", "5PM"
Hour and minutes, with meridian | `hh` [.:] `MM` `space`? `meridian` | "4:08 am", "7:19P.M."
Hour, minutes and seconds, with meridian | `hh` [.:] `MM` [.:] `II` `space`? `meridian` | "4:08:37 am", "7:19:19P.M."
MS SQL (Hour, minutes, seconds and fraction with meridian) | `hh` ":" `MM` ":" `II` [.:] [0-9]+ `meridian` | "4:08:39:12313am"

24 Hour Notation
Description | Format | Examples
--- | --- | ---
Hour and minutes | 't'? `HH` [.:] `MM` | "04:08", "19.19", "T23:43"
Hour and minutes, no colon | 't'? `HH` `MM` | "0408", "t1919", "T2343"
Hour, minutes and seconds | 't'? `HH` [.:] `MM` [.:] `II` | "04.08.37", "t19:19:19"
Hour, minutes and seconds, no colon | 't'? `HH` `MM` `II` | "040837", "T191919"
Hour, minutes, seconds and timezone | 't'? `HH` [.:] `MM` [.:] `II` `space`? ( `tzcorrection` | `tz` ) | "040837CEST", "T191919-0700"
Hour, minutes, seconds and fraction | 't'? `HH` [.:] `MM` [.:] `II` `frac` | "04.08.37.81412", "19:19:19.532453"
Time zone information | `tz` | `tzcorrection` | "CEST", "Europe/Amsterdam", "+0430", "GMT-06:00"

## Date Formats

This page describes the different date formats in a BNF-like syntax, that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Format | Examples
--- | --- | ---
`daysuf` | "st" | "nd" | "rd" | "th" |
`dd` | ([0-2]?[0-9] | "3"[01]) `daysuf`? | "7th", "22nd", "31"
`DD` | "0" [0-9] | [1-2][0-9] | "3" [01] | "07", "31"
`m` | 'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII" |
`M` | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
`mm` | "0"? [0-9] | "1"[0-2] | "0", "04", "7", "12"
`MM` | "0" [0-9] | "1"[0-2] | "00", "04", "07", "12"
`y` | [0-9]{1,4} | "00", "78", "08", "8", "2008"
`yy` | [0-9]{2} | "00", "08", "78"
`YY` | [0-9]{4} | "2000", "2008", "1978"
`YYY` | [0-9]{5,19} | "81412", "20192"

Localized Notations
Description | Format | Examples
--- | --- | ---
American month and day | `mm` "/" `dd` | "5/12", "10/27"
American month, day and year | `mm` "/" `dd` "/" `y` | "12/22/78", "1/17/2006", "1/17/6"
Four digit year, month and day with slashes | `YY` "/" `mm` "/" `dd` | "2008/6/30", "1978/12/22"
Four digit year and month (GNU) | `YY` "-" `mm` | "2008-6", "2008-06", "1978-12"
Year, month and day with dashes | `y` "-" `mm` "-" `dd` | "2008-6-30", "78-12-22", "8-6-21"
Day, month and four digit year, with dots, tabs or dashes | `dd` [.\t-] `mm` [.-] `YY` | "30-6-2008", "22.12.1978"
Day, month and two digit year, with dots or tabs | `dd` [.\t] `mm` "." `yy` | "30.6.08", "22\t12.78"
Day, textual month and year | `dd` ([ \t.-])* `m` ([ \t.-])* `y` | "30-June 2008", "22DEC78", "14 III 1879"
Textual month and four digit year (Day reset to 1) | `m` ([ \t.-])* `YY` | "June 2008", "DEC1978", "March 1879"
Four digit year and textual month (Day reset to 1) | `YY` ([ \t.-])* `m` | "2008 June", "1978-XII", "1879.MArCH"
Textual month, day and year | `m` ([ .\t-])* `dd` [,.stndrh\t ]+ `y` | "July 1st, 2008", "April 17, 1790", "May.9,78"
Textual month and day | `m` ([ .\t-])* `dd` [,.stndrh\t ]* | "July 1st,", "Apr 17", "May.9"
Day and textual month | `dd` ([ .\t-])* `m` | "1 July", "17 Apr", "9.May"
Month abbreviation, day and year | `M` "-" `DD` "-" `y` | "May-09-78", "Apr-17-1790"
Year, month abbreviation and day | `y` "-" `M` "-" `DD` | "78-Dec-22", "1814-MAY-17"
Year (and just the year) | `YY` | "1978", "2008"
Year (expanded, 5-19 digits with sign) | [+-] `YYY` | "-81120", "+20192"
Textual month (and just the month) | `m` | "March", "jun", "DEC"

ISO8601 Notations
Description | Format | Examples
--- | --- | ---
Eight digit year, month and day | `YY` `MM` `DD` | "15810726", "19780417", "18140517"
Four digit year, month and day with slashes | `YY` "/" `MM` "/" `DD` | "2008/06/30", "1978/12/22"
Two digit year, month and day with dashes | `yy` "-" `MM` "-" `DD` | "08-06-30", "78-12-22"
Four digit year with optional sign, month and day | [+-]? `YY` "-" `MM` "-" `DD` | "-0002-07-26", "+1978-04-17", "1814-05-17"
Five+ digit year with required sign, month and day | [+-] `YYY` "-" `MM` "-" `DD` | "-81120-02-26", "+20192-04-17"

> Note:

> For the `y` and `yy` formats, years below 100 are handled in a special way when the `y` or `yy` symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".

> Note:

> The "Day, month and two digit year, with dots or tabs" format (`dd` [.\t] `mm` "." `yy`) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "`HH` [.:] `MM` [.:] `SS`" has precedence.

> Note:

> The "Year (and just the year)" format only reliably works if a time string has already been found. Otherwise, if the four digit year matches `HH` `MM` then these two date elements are set instead.

> To consistently parse just a year, use DateTimeImmutable::createFromFormat() with the `Y` specifier.

Caution

It is possible to over- and underflow the `dd` and `DD` format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

Note that the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.

It is also possible to underflow the `mm` and `MM` formats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".

If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).

## Compound Formats

This page describes the different compound date/time formats in a BNF-like syntax, that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Formats | Examples
--- | --- | ---
`DD` | "0" [0-9] | [1-2][0-9] | "3" [01] | "02", "12", "31"
`doy` | "00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] | "001", "012", "180", "350", "366"
`frac` | . [0-9]+ | ".21342", ".85"
`hh` | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
`HH` | [01][0-9] | "2"[0-4] | "04", "07", "19"
`meridian` | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
`ii` | [0-5]?[0-9] | "04", "8", "59"
`II` | [0-5][0-9] | "04", "08", "59"
`M` | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
`MM` | [0-1][0-9] | "00", "12"
`space` | [ \t] |
`ss` | ([0-5]?[0-9])|60 | "04", "8", "59", "60" (leap second)
`SS` | [0-5][0-9] | "04", "08", "59"
`W` | "0"[1-9] | [1-4][0-9] | "5"[0-3] | "05", "17", "53"
`tzcorrection` | "GMT"? [+-] `hh` ":"? `II`? | "+0400", "GMT-07:00", "-07:00"
`YY` | [0-9]{4} | "2000", "2008", "1978"

Standards Formats
Description | Examples
--- | ---
ATOM | "2022-06-02T16:58:35+00:00"
COOKIE | "Thursday, 02-Jun-2022 16:58:35 UTC"
ISO8601 | "2022-06-02T16:58:35+0000"
» RFC 822 | "Thu, 02 Jun 22 16:58:35 +0000"
» RFC 850 | "Thursday, 02-Jun-22 16:58:35 UTC"
» RFC 1036 | "Thu, 02 Jun 22 16:58:35 +0000"
» RFC 1123 | "Thu, 02 Jun 2022 16:58:35 +0000"
» RFC 2822 | "Thu, 02 Jun 2022 16:58:35 +0000"
» RFC 3339 | "2022-06-02T16:58:35+00:00"
» RFC 3339 Extended | "2022-06-02T16:58:35.698+00:00"
» RFC 7231 | "Thu, 02 Jun 2022 16:58:35 GMT"
RSS | "Thu, 02 Jun 2022 16:58:35 +0000"
W3C | "2022-06-02T16:58:35+00:00"

Localized Notations
Description | Format | Examples
--- | --- | ---
Common Log Format | `dd` "/" `M` "/" `YY` : `HH` ":" `II` ":" `SS` `space` `tzcorrection` | "10/Oct/2000:13:55:36 -0700"
EXIF | `YY` ":" `MM` ":" `DD` " " `HH` ":" `II` ":" `SS` | "2008:08:07 18:11:31"
ISO year with ISO week | `YY` "-"? "W" `W` | "2008W27", "2008-W28"
ISO year with ISO week and day | `YY` "-"? "W" `W` "-"? [0-7] | "2008W273", "2008-W28-3"
MySQL | `YY` "-" `MM` "-" `DD` " " `HH` ":" `II` ":" `SS` | "2008-08-07 18:11:31"
PostgreSQL: Year with day-of-year | `YY` "."? `doy` | "2008.197", "2008197"
SOAP | `YY` "-" `MM` "-" `DD` "T" `HH` ":" `II` ":" `SS` `frac` `tzcorrection`? | "2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"
Unix Timestamp | "@" "-"? [0-9]+ | "@1215282385"
Unix Timestamp with microseconds | "@" "-"? [0-9]+ "." [0-9]{0,6} | "@1607974647.503686"
XMLRPC | `YY` `MM` `DD` "T" `hh` ":" `II` ":" `SS` | "20080701T22:38:07", "20080701T9:38:07"
XMLRPC (Compact) | `YY` `MM` `DD` 't' `hh` `II` `SS` | "20080701t223807", "20080701T093807"
WDDX | `YY` "-" `mm` "-" `dd` "T" `hh` ":" `ii` ":" `ss` | "2008-7-1T9:3:37"

> Note:

> The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

> The "T" in the SOAP, XMLRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

> The "Unix Timestamp" format sets the timezone to UTC.

## Relative Formats

This page describes the different relative date/time formats in a BNF-like syntax, that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Format
--- | ---
`dayname` | 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
`daytext` | 'weekday' | 'weekdays'
`number` | [+-]?[0-9]+
`ordinal` | 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this'
`reltext` | 'next' | 'last' | 'previous' | 'this'
`space` | [ \t]+
`unit` | 'ms' | 'µs' | (( 'msec' | 'millisecond' | 'µsec' | 'microsecond' | 'usec' | 'sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' | 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' | `daytext`

Day-based Notations
Format | Description | Examples
--- | --- | ---
'yesterday' | Midnight of yesterday | "yesterday 14:00"
'midnight' | The time is set to 00:00:00 |
'today' | The time is set to 00:00:00 |
'now' | Now - this is simply ignored |
'noon' | The time is set to 12:00:00 | "yesterday noon"
'tomorrow' | Midnight of tomorrow |
'back of' `hour` | 15 minutes past the specified hour | "back of 7pm", "back of 15"
'front of' `hour` | 15 minutes before the specified hour | "front of 5am", "front of 23"
'first day of' | Sets the day of the first of the current month. This phrase is usually best used together with a month name following it as it only effects the current month | "first day of January 2008"
'last day of' | Sets the day to the last day of the current month. This phrase is usually best used together with a month name following it as it only effects the current month | "last day of next month"
`ordinal` `space` `dayname` `space` 'of' | Calculates the `x`-th week day of the current month. | "first sat of July 2008"
'last' `space` `dayname` `space` 'of' | Calculates the last week day of the current month. | "last sat of July 2008"
`number` `space`? (`unit` | 'week') | Handles relative time items where the value is a number. | "+5 weeks", "12 day", "-7 weekdays"
(`ordinal` | `reltext`) `space` `unit` | Handles relative time items where the value is text. `last` and `previous` are equivalent to `-1`, `this` to nothing, and `next` to `+1`. | "fifth day", "second month", "last day", "previous year"
'ago' | Negates all the values of previously found relative time items. | "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago"
`dayname` | Moves to the next day of this name. (See note) | "Monday"
`reltext` `space` 'week' | Handles the special format "weekday + last/this/next week". | "Monday next week"

> Note:

> Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.

> Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.

> Keywords such as "first day of" depend on the context in which the relative format string is used. If used with a static method or function, the referent is the current system timestamp. However, if used in DateTime::modify() or DateTimeImmutable::modify(), the referent is the object on which the `modify()` method is called.

> Note:

> Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.

> 1. "`dayname`" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").
> 2. "`number` `dayname`" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").
> 3. "`number` week `dayname`" will first add the number of weeks, but does not advance to another day. In this case "`number` week" and "`dayname`" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").
> 4. "`ordinal` `dayname`" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
> 5. "`number` week `ordinal` `dayname`" will first add the number of weeks, and then advances to another day. In this case "`number` week" and "`ordinal` `dayname`" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").
> 6. "`ordinal` `dayname` 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

> Also observe that the "of" in "`ordinal` `space` `dayname` `space` 'of' " and "'last' `space` `dayname` `space` 'of' " does something special.

> 1. It sets the day-of-month to 1.
> 2. "`ordinal` `dayname` 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
> 3. "`ordinal` `dayname` " does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).
> 4. "'last' `dayname` 'of' " takes the last `dayname` of the current month. (Example: "last wed of july 2008" means "2008-07-30")
> 5. "'last' `dayname`" takes the last `dayname` from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

> Note:

> Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

> Note:

> `number` is an integer number; if a decimal number is given, the dot (or comma) is likely interpreted as delimiter. For instance, `'+1.5 hours'` is parsed like `'+1 5 hours'`, not as `'+1 hour +30 minutes'`.

### Changelog

Version | Description
--- | ---
8.4.0 | `number` now again accepts a plus sign followed by a minus sign, e.g. `+-2`, and other combinations of multiple signs.
8.2.0 | `number` no longer accepts a plus sign followed by a minus sign, e.g. `+-2`.
7.0.8 | Weeks always start on monday. Formerly, sunday would also be considered to start a week.

# List of Supported Timezones

## Table of Contents

- Africa
- America
- Antarctica
- Arctic
- Asia
- Atlantic
- Australia
- Europe
- Indian
- Pacific
- Others

Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set().

Caution

The behavior of timezones not listed here is undefined.

> Note: The latest version of the timezone database can be installed via PECL's » timezonedb.

> Note: This list is based upon the timezone database version 2026.1.

## Africa

Africa
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers
Africa/Asmara | Africa/Bamako | Africa/Bangui | Africa/Banjul
Africa/Bissau | Africa/Blantyre | Africa/Brazzaville | Africa/Bujumbura
Africa/Cairo | Africa/Casablanca | Africa/Ceuta | Africa/Conakry
Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti | Africa/Douala
Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare
Africa/Johannesburg | Africa/Juba | Africa/Kampala | Africa/Khartoum
Africa/Kigali | Africa/Kinshasa | Africa/Lagos | Africa/Libreville
Africa/Lome | Africa/Luanda | Africa/Lubumbashi | Africa/Lusaka
Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane
Africa/Mogadishu | Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena
Africa/Niamey | Africa/Nouakchott | Africa/Ouagadougou | Africa/Porto-Novo
Africa/Sao_Tome | Africa/Tripoli | Africa/Tunis | Africa/Windhoek

## America

America
America/Adak | America/Anchorage | America/Anguilla | America/Antigua
America/Araguaina | America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/Cordoba
America/Argentina/Jujuy | America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos
America/Argentina/Salta | America/Argentina/San_Juan | America/Argentina/San_Luis | America/Argentina/Tucuman
America/Argentina/Ushuaia | America/Aruba | America/Asuncion | America/Atikokan
America/Bahia | America/Bahia_Banderas | America/Barbados | America/Belem
America/Belize | America/Blanc-Sablon | America/Boa_Vista | America/Bogota
America/Boise | America/Cambridge_Bay | America/Campo_Grande | America/Cancun
America/Caracas | America/Cayenne | America/Cayman | America/Chicago
America/Chihuahua | America/Ciudad_Juarez | America/Costa_Rica | America/Coyhaique
America/Creston | America/Cuiaba | America/Curacao | America/Danmarkshavn
America/Dawson | America/Dawson_Creek | America/Denver | America/Detroit
America/Dominica | America/Edmonton | America/Eirunepe | America/El_Salvador
America/Fort_Nelson | America/Fortaleza | America/Glace_Bay | America/Goose_Bay
America/Grand_Turk | America/Grenada | America/Guadeloupe | America/Guatemala
America/Guayaquil | America/Guyana | America/Halifax | America/Havana
America/Hermosillo | America/Indiana/Indianapolis | America/Indiana/Knox | America/Indiana/Marengo
America/Indiana/Petersburg | America/Indiana/Tell_City | America/Indiana/Vevay | America/Indiana/Vincennes
America/Indiana/Winamac | America/Inuvik | America/Iqaluit | America/Jamaica
America/Juneau | America/Kentucky/Louisville | America/Kentucky/Monticello | America/Kralendijk
America/La_Paz | America/Lima | America/Los_Angeles | America/Lower_Princes
America/Maceio | America/Managua | America/Manaus | America/Marigot
America/Martinique | America/Matamoros | America/Mazatlan | America/Menominee
America/Merida | America/Metlakatla | America/Mexico_City | America/Miquelon
America/Moncton | America/Monterrey | America/Montevideo | America/Montserrat
America/Nassau | America/New_York | America/Nome | America/Noronha
America/North_Dakota/Beulah | America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Nuuk
America/Ojinaga | America/Panama | America/Paramaribo | America/Phoenix
America/Port-au-Prince | America/Port_of_Spain | America/Porto_Velho | America/Puerto_Rico
America/Punta_Arenas | America/Rankin_Inlet | America/Recife | America/Regina
America/Resolute | America/Rio_Branco | America/Santarem | America/Santiago
America/Santo_Domingo | America/Sao_Paulo | America/Scoresbysund | America/Sitka
America/St_Barthelemy | America/St_Johns | America/St_Kitts | America/St_Lucia
America/St_Thomas | America/St_Vincent | America/Swift_Current | America/Tegucigalpa
America/Thule | America/Tijuana | America/Toronto | America/Tortola
America/Vancouver | America/Whitehorse | America/Winnipeg | America/Yakutat

## Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie
Antarctica/Mawson | Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera
Antarctica/Syowa | Antarctica/Troll | Antarctica/Vostok |

## Arctic

Arctic
Arctic/Longyearbyen

## Asia

Asia
Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr
Asia/Aqtau | Asia/Aqtobe | Asia/Ashgabat | Asia/Atyrau
Asia/Baghdad | Asia/Bahrain | Asia/Baku | Asia/Bangkok
Asia/Barnaul | Asia/Beirut | Asia/Bishkek | Asia/Brunei
Asia/Chita | Asia/Colombo | Asia/Damascus | Asia/Dhaka
Asia/Dili | Asia/Dubai | Asia/Dushanbe | Asia/Famagusta
Asia/Gaza | Asia/Hebron | Asia/Ho_Chi_Minh | Asia/Hong_Kong
Asia/Hovd | Asia/Irkutsk | Asia/Jakarta | Asia/Jayapura
Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka | Asia/Karachi
Asia/Kathmandu | Asia/Khandyga | Asia/Kolkata | Asia/Krasnoyarsk
Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait | Asia/Macau
Asia/Magadan | Asia/Makassar | Asia/Manila | Asia/Muscat
Asia/Nicosia | Asia/Novokuznetsk | Asia/Novosibirsk | Asia/Omsk
Asia/Oral | Asia/Phnom_Penh | Asia/Pontianak | Asia/Pyongyang
Asia/Qatar | Asia/Qostanay | Asia/Qyzylorda | Asia/Riyadh
Asia/Sakhalin | Asia/Samarkand | Asia/Seoul | Asia/Shanghai
Asia/Singapore | Asia/Srednekolymsk | Asia/Taipei | Asia/Tashkent
Asia/Tbilisi | Asia/Tehran | Asia/Thimphu | Asia/Tokyo
Asia/Tomsk | Asia/Ulaanbaatar | Asia/Urumqi | Asia/Ust-Nera
Asia/Vientiane | Asia/Vladivostok | Asia/Yakutsk | Asia/Yangon
Asia/Yekaterinburg | Asia/Yerevan |  |

## Atlantic

Atlantic
Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde
Atlantic/Faroe | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia
Atlantic/St_Helena | Atlantic/Stanley |  |

## Australia

Australia
Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Darwin
Australia/Eucla | Australia/Hobart | Australia/Lindeman | Australia/Lord_Howe
Australia/Melbourne | Australia/Perth | Australia/Sydney |

## Europe

Europe
Europe/Amsterdam | Europe/Andorra | Europe/Astrakhan | Europe/Athens
Europe/Belgrade | Europe/Berlin | Europe/Bratislava | Europe/Brussels
Europe/Bucharest | Europe/Budapest | Europe/Busingen | Europe/Chisinau
Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey
Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey
Europe/Kaliningrad | Europe/Kirov | Europe/Kyiv | Europe/Lisbon
Europe/Ljubljana | Europe/London | Europe/Luxembourg | Europe/Madrid
Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Oslo | Europe/Paris | Europe/Podgorica
Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara
Europe/San_Marino | Europe/Sarajevo | Europe/Saratov | Europe/Simferopol
Europe/Skopje | Europe/Sofia | Europe/Stockholm | Europe/Tallinn
Europe/Tirane | Europe/Ulyanovsk | Europe/Vaduz | Europe/Vatican
Europe/Vienna | Europe/Vilnius | Europe/Volgograd | Europe/Warsaw
Europe/Zagreb | Europe/Zurich |  |

## Indian

Indian
Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos
Indian/Comoro | Indian/Kerguelen | Indian/Mahe | Indian/Maldives
Indian/Mauritius | Indian/Mayotte | Indian/Reunion |

## Pacific

Pacific
Pacific/Apia | Pacific/Auckland | Pacific/Bougainville | Pacific/Chatham
Pacific/Chuuk | Pacific/Easter | Pacific/Efate | Pacific/Fakaofo
Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos | Pacific/Gambier
Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu | Pacific/Kanton
Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro
Pacific/Marquesas | Pacific/Midway | Pacific/Nauru | Pacific/Niue
Pacific/Norfolk | Pacific/Noumea | Pacific/Pago_Pago | Pacific/Palau
Pacific/Pitcairn | Pacific/Pohnpei | Pacific/Port_Moresby | Pacific/Rarotonga
Pacific/Saipan | Pacific/Tahiti | Pacific/Tarawa | Pacific/Tongatapu
Pacific/Wake | Pacific/Wallis |  |

## Others

Warning

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons, and may expose erroneous behavior. Furthermore, these timezones may be removed from the IANA timezone database at any time.

Warning

If you disregard the above warning, please also note that the IANA timezone database that provides PHP's timezone support uses POSIX style signs, which results in the `Etc/GMT+n` and `Etc/GMT-n` time zones being reversed from common usage.

For example, the time zone 8 hours ahead of GMT that is used in China and Western Australia (among other places) is actually `Etc/GMT-8` in this database, not `Etc/GMT+8` as you would normally expect.

Once again, it is strongly recommended that you use the correct time zone for your location, such as `Asia/Shanghai` or `Australia/Perth` for the above examples.

Others
Africa/Asmera | Africa/Timbuktu | America/Argentina/ComodRivadavia | America/Atka
America/Buenos_Aires | America/Catamarca | America/Coral_Harbour | America/Cordoba
America/Ensenada | America/Fort_Wayne | America/Godthab | America/Indianapolis
America/Jujuy | America/Knox_IN | America/Louisville | America/Mendoza
America/Montreal | America/Nipigon | America/Pangnirtung | America/Porto_Acre
America/Rainy_River | America/Rosario | America/Santa_Isabel | America/Shiprock
America/Thunder_Bay | America/Virgin | America/Yellowknife | Antarctica/South_Pole
Asia/Ashkhabad | Asia/Calcutta | Asia/Choibalsan | Asia/Chongqing
Asia/Chungking | Asia/Dacca | Asia/Harbin | Asia/Istanbul
Asia/Kashgar | Asia/Katmandu | Asia/Macao | Asia/Rangoon
Asia/Saigon | Asia/Tel_Aviv | Asia/Thimbu | Asia/Ujung_Pandang
Asia/Ulan_Bator | Atlantic/Faeroe | Atlantic/Jan_Mayen | Australia/ACT
Australia/Canberra | Australia/Currie | Australia/LHI | Australia/North
Australia/NSW | Australia/Queensland | Australia/South | Australia/Tasmania
Australia/Victoria | Australia/West | Australia/Yancowinna | Brazil/Acre
Brazil/DeNoronha | Brazil/East | Brazil/West | Canada/Atlantic
Canada/Central | Canada/Eastern | Canada/Mountain | Canada/Newfoundland
Canada/Pacific | Canada/Saskatchewan | Canada/Yukon | CET
Chile/Continental | Chile/EasterIsland | CST6CDT | Cuba
EET | Egypt | Eire | EST
EST5EDT | Etc/GMT | Etc/GMT+0 | Etc/GMT+1
Etc/GMT+10 | Etc/GMT+11 | Etc/GMT+12 | Etc/GMT+2
Etc/GMT+3 | Etc/GMT+4 | Etc/GMT+5 | Etc/GMT+6
Etc/GMT+7 | Etc/GMT+8 | Etc/GMT+9 | Etc/GMT-0
Etc/GMT-1 | Etc/GMT-10 | Etc/GMT-11 | Etc/GMT-12
Etc/GMT-13 | Etc/GMT-14 | Etc/GMT-2 | Etc/GMT-3
Etc/GMT-4 | Etc/GMT-5 | Etc/GMT-6 | Etc/GMT-7
Etc/GMT-8 | Etc/GMT-9 | Etc/GMT0 | Etc/Greenwich
Etc/UCT | Etc/Universal | Etc/UTC | Etc/Zulu
Europe/Belfast | Europe/Kiev | Europe/Nicosia | Europe/Tiraspol
Europe/Uzhgorod | Europe/Zaporozhye | Factory | GB
GB-Eire | GMT | GMT+0 | GMT-0
GMT0 | Greenwich | Hongkong | HST
Iceland | Iran | Israel | Jamaica
Japan | Kwajalein | Libya | MET
Mexico/BajaNorte | Mexico/BajaSur | Mexico/General | MST
MST7MDT | Navajo | NZ | NZ-CHAT
Pacific/Enderbury | Pacific/Johnston | Pacific/Ponape | Pacific/Samoa
Pacific/Truk | Pacific/Yap | Poland | Portugal
PRC | PST8PDT | ROC | ROK
Singapore | Turkey | UCT | Universal
US/Alaska | US/Aleutian | US/Arizona | US/Central
US/East-Indiana | US/Eastern | US/Hawaii | US/Indiana-Starke
US/Michigan | US/Mountain | US/Pacific | US/Samoa
UTC | W-SU | WET | Zulu

# The DateError class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when the timezone database is not found, or contains invalid data.

This error should never occur, and is not dependent on code. There are two child-exceptions (DateObjectError and DateRangeError) which are thrown depending on programmer error or range related issues.

## Class synopsis

class DateError extends Error {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

## See Also

- DateObjectError
- DateRangeError

# The DateObjectError class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when one of the Date/Time classes has not been correctly initialised.

Because Date/Time classes are not final, these classes can be inherit. When the parent constructor is not called, this error is thrown. This is always a programming error.

## Class synopsis

class DateObjectError extends DateError {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

## See Also

- DateError
- DateRangeError

# The DateRangeError class

(PHP 8 >= 8.3.0)

## Introduction

Thrown by DateTime::getTimestamp(), DateTimeImmutable::getTimestamp(), and date_timestamp_get(), on 32-bit platforms if the date object represents a date outside of the 32-bit signed range.

## Class synopsis

class DateRangeError extends DateError {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Error::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

## See Also

- DateError
- DateObjectError

# The DateException class

(PHP 8 >= 8.3.0)

## Introduction

Parent class of Date/Time exceptions, for issues that come to light due to user input, or free form text arguments that need to be parsed.

The following child exceptions are thrown by the extension:

- DateInvalidOperationException
- DateInvalidTimezoneException
- DateMalformedIntervalStringException
- DateMalformedPeriodStringException
- DateMalformedStringException

## Class synopsis

class DateException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The DateInvalidOperationException class

(PHP 8 >= 8.3.0)

## Introduction

Thrown by DateTimeImmutable::sub() and DateTime::sub() when an unsupported operation is attempted.

An example of such an unsupported operation is using a DateInterval object representing relative time specifications such as `next weekday`, as no logical reversed statement can be constructed.

## Class synopsis

class DateInvalidOperationException extends DateException {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The DateInvalidTimeZoneException class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when an incorrect value is passed to DateTimeZone::__construct().

## Class synopsis

class DateInvalidTimeZoneException extends DateException {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The DateMalformedIntervalStringException class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when an invalid `duration` argument is passed to DateInterval::__construct().

## Class synopsis

class DateMalformedIntervalStringException extends DateException {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The DateMalformedPeriodStringException class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when an invalid `isostr` argument is passed to DatePeriod::__construct().

## Class synopsis

class DateMalformedPeriodStringException extends DateException {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The DateMalformedStringException class

(PHP 8 >= 8.3.0)

## Introduction

Thrown when an invalid Date/Time string is detected.

This can be as value to DateTimeImmutable::__construct(), DateTimeImmutable::modify(), DateTime::__construct(), or DateTime::modify().

## Class synopsis

class DateMalformedStringException extends DateException {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Predefined Constants
- Examples
  - Date/Time Arithmetic
- DateTime — The DateTime class
  - DateTime::add — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
  - DateTime::__construct — Returns new DateTime object
  - DateTime::createFromFormat — Parses a time string according to a specified format
  - DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object
  - DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object
  - DateTime::getLastErrors — Alias of DateTimeImmutable::getLastErrors
  - DateTime::modify — Alters the timestamp
  - DateTime::__set_state — The __set_state handler
  - DateTime::setDate — Sets the date
  - DateTime::setISODate — Sets the ISO date
  - DateTime::setTime — Sets the time
  - DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
  - DateTime::setTimezone — Sets the time zone for the DateTime object
  - DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTimeImmutable — The DateTimeImmutable class
  - DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
  - DateTimeImmutable::__construct — Returns new DateTimeImmutable object
  - DateTimeImmutable::createFromFormat — Parses a time string according to a specified format
  - DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
  - DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object
  - DateTimeImmutable::getLastErrors — Returns the warnings and errors
  - DateTimeImmutable::modify — Creates a new object with modified timestamp
  - DateTimeImmutable::__set_state — The __set_state handler
  - DateTimeImmutable::setDate — Sets the date
  - DateTimeImmutable::setISODate — Sets the ISO date
  - DateTimeImmutable::setTime — Sets the time
  - DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp
  - DateTimeImmutable::setTimezone — Sets the time zone
  - DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
- DateTimeInterface — The DateTimeInterface interface
  - DateTimeInterface::diff — Returns the difference between two DateTime objects
  - DateTimeInterface::format — Returns date formatted according to given format
  - DateTimeInterface::getOffset — Returns the timezone offset
  - DateTimeInterface::getTimestamp — Gets the Unix timestamp
  - DateTimeInterface::getTimezone — Return time zone relative to given DateTime
  - DateTime::__serialize — Serialize a DateTime
  - DateTime::__unserialize — Unserialize an Datetime
  - DateTime::__wakeup — The __wakeup handler
- DateTimeZone — The DateTimeZone class
  - DateTimeZone::__construct — Creates new DateTimeZone object
  - DateTimeZone::getLocation — Returns location information for a timezone
  - DateTimeZone::getName — Returns the name of the timezone
  - DateTimeZone::getOffset — Returns the timezone offset from GMT
  - DateTimeZone::getTransitions — Returns all transitions for the timezone
  - DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
  - DateTimeZone::listIdentifiers — Returns a numerically indexed array containing all defined timezone identifiers
- DateInterval — The DateInterval class
  - DateInterval::__construct — Creates a new DateInterval object
  - DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  - DateInterval::format — Formats the interval
- DatePeriod — The DatePeriod class
  - DatePeriod::__construct — Creates a new DatePeriod object
  - DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string
  - DatePeriod::getDateInterval — Gets the interval
  - DatePeriod::getEndDate — Gets the end date
  - DatePeriod::getRecurrences — Gets the number of recurrences
  - DatePeriod::getStartDate — Gets the start date
- Date/Time Functions
  - checkdate — Validate a Gregorian date
  - date — Format a Unix timestamp
  - date_add — Alias of DateTime::add
  - date_create — create a new DateTime object
  - date_create_from_format — Alias of DateTime::createFromFormat
  - date_create_immutable — create a new DateTimeImmutable object
  - date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
  - date_date_set — Alias of DateTime::setDate
  - date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
  - date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
  - date_diff — Alias of DateTime::diff
  - date_format — Alias of DateTime::format
  - date_get_last_errors — Alias of DateTimeImmutable::getLastErrors
  - date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
  - date_interval_format — Alias of DateInterval::format
  - date_isodate_set — Alias of DateTime::setISODate
  - date_modify — Alias of DateTime::modify
  - date_offset_get — Alias of DateTime::getOffset
  - date_parse — Returns associative array with detailed info about given date/time
  - date_parse_from_format — Get info about given date formatted according to the specified format
  - date_sub — Alias of DateTime::sub
  - date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
  - date_sunrise — Returns time of sunrise for a given day and location
  - date_sunset — Returns time of sunset for a given day and location
  - date_time_set — Alias of DateTime::setTime
  - date_timestamp_get — Alias of DateTime::getTimestamp
  - date_timestamp_set — Alias of DateTime::setTimestamp
  - date_timezone_get — Alias of DateTime::getTimezone
  - date_timezone_set — Alias of DateTime::setTimezone
  - getdate — Get date/time information
  - gettimeofday — Get current time
  - gmdate — Format a GMT/UTC date/time
  - gmmktime — Get Unix timestamp for a GMT date
  - gmstrftime — Format a GMT/UTC time/date according to locale settings
  - idate — Format a local time/date part as integer
  - localtime — Get the local time
  - microtime — Return current Unix timestamp with microseconds
  - mktime — Get Unix timestamp for a date
  - strftime — Format a local time/date according to locale settings
  - strptime — Parse a time/date generated with strftime
  - strtotime — Parse about any English textual datetime description into a Unix timestamp
  - time — Return current Unix timestamp
  - timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations
  - timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
  - timezone_location_get — Alias of DateTimeZone::getLocation
  - timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset
  - timezone_name_get — Alias of DateTimeZone::getName
  - timezone_offset_get — Alias of DateTimeZone::getOffset
  - timezone_open — Alias of DateTimeZone::__construct
  - timezone_transitions_get — Alias of DateTimeZone::getTransitions
  - timezone_version_get — Gets the version of the timezonedb
- Date/Time Errors and Exceptions
- Supported Date and Time Formats
- List of Supported Timezones
  - Africa
  - America
  - Antarctica
  - Arctic
  - Asia
  - Atlantic
  - Australia
  - Europe
  - Indian
  - Pacific
  - Others
- DateError — The DateError class
- DateObjectError — The DateObjectError class
- DateRangeError — The DateRangeError class
- DateException — The DateException class
- DateInvalidOperationException — The DateInvalidOperationException class
- DateInvalidTimeZoneException — The DateInvalidTimeZoneException class
- DateMalformedIntervalStringException — The DateMalformedIntervalStringException class
- DateMalformedPeriodStringException — The DateMalformedPeriodStringException class
- DateMalformedStringException — The DateMalformedStringException class

# High resolution timing

# Introduction

The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlying APIs.

> Note: As of PHP 7.3.0 the related function hrtime() is part of the core.

# Installing/Configuring

## Table of Contents

- Installation

## Installation

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: » https://pecl.php.net/package/hrtime.

# Examples

## Table of Contents

- Basic usage

## Basic usage

The example illustrates the basic StopWatch class usage

Example #1 Measure several code blocks execution and get the total

`<?php
$c = new HRTime\StopWatch;
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i++);
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);
?>`

# The HRTime\PerformanceCounter class

(PECL hrtime >= 0.4.3)

## Introduction

## Class synopsis

class HRTime\PerformanceCounter {
/* Methods */
public static getFrequency(): int
public static getTicks(): int
public static getTicksSince(int `$start`): int
}

# HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second

### Description

public static HRTime\PerformanceCounter::getFrequency(): int

Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.

### Parameters

This function has no parameters.

### Return Values

Returns int indicating the timer frequency.

# HRTime\PerformanceCounter::getTicks

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicks — Current ticks from the system

### Description

public static HRTime\PerformanceCounter::getTicks(): int

Returns the ticks count.

### Parameters

This function has no parameters.

### Return Values

Returns int indicating the ticks count.

# HRTime\PerformanceCounter::getTicksSince

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value

### Description

public static HRTime\PerformanceCounter::getTicksSince(int `$start`): int

Returns the ticks count elapsed since the given start value.

### Parameters

`start`
  Starting ticks value.

### Return Values

Returns int indicating the ticks count.

## Table of Contents

- HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
- HRTime\PerformanceCounter::getTicks — Current ticks from the system
- HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value

# The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

## Introduction

## Class synopsis

class HRTime\StopWatch extends HRTime\PerformanceCounter {
/* Methods */
public getElapsedTicks(): int
public getElapsedTime(int `$unit` = ?): float
public getLastElapsedTicks(): int
public getLastElapsedTime(int `$unit` = ?): float
public isRunning(): bool
public start(): void
public stop(): void
/* Inherited methods */
public static HRTime\PerformanceCounter::getFrequency(): int
public static HRTime\PerformanceCounter::getTicks(): int
public static HRTime\PerformanceCounter::getTicksSince(int `$start`): int
}

# HRTime\StopWatch::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals

### Description

public HRTime\StopWatch::getElapsedTicks(): int

Get elapsed ticks for all the previously closed intervals.

### Parameters

This function has no parameters.

### Return Values

Returns int indicating elapsed ticks.

# HRTime\StopWatch::getElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals

### Description

public HRTime\StopWatch::getElapsedTime(int `$unit` = ?): float

Get elapsed time for all the previously closed intervals.

### Parameters

`unit`
  Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

### Return Values

Returns float indicating elapsed time.

# HRTime\StopWatch::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval

### Description

public HRTime\StopWatch::getLastElapsedTicks(): int

Get elapsed ticks for the previously closed interval.

### Parameters

This function has no parameters.

### Return Values

Returns int indicating elapsed ticks.

# HRTime\StopWatch::getLastElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval

### Description

public HRTime\StopWatch::getLastElapsedTime(int `$unit` = ?): float

Get elapsed time for the previously closed interval.

### Parameters

`unit`
  Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

### Return Values

Returns float indicating elapsed time.

# HRTime\StopWatch::isRunning

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::isRunning — Whether the measurement is running

### Description

public HRTime\StopWatch::isRunning(): bool

Reveals whether the measurement was started.

### Parameters

This function has no parameters.

### Return Values

Returns bool indicating whether the measurement is running.

# HRTime\StopWatch::start

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::start — Start time measurement

### Description

public HRTime\StopWatch::start(): void

Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.

### Parameters

This function has no parameters.

### Return Values

Returns void.

# HRTime\StopWatch::stop

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::stop — Stop time measurement

### Description

public HRTime\StopWatch::stop(): void

Stop the time measurement for the previously started interval.

### Parameters

This function has no parameters.

### Return Values

Returns void.

## Table of Contents

- HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals
- HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals
- HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval
- HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval
- HRTime\StopWatch::isRunning — Whether the measurement is running
- HRTime\StopWatch::start — Start time measurement
- HRTime\StopWatch::stop — Stop time measurement

# The HRTime\Unit class

(PECL hrtime >= 0.4.3)

## Introduction

## Class synopsis

class HRTime\Unit {
/* Constants */
const int SECOND = 0;
const int MILLISECOND = 1;
const int MICROSECOND = 2;
const int NANOSECOND = 3;
/* Methods */
}

## Predefined Constants

`HRTime\Unit::SECOND`
`HRTime\Unit::MILLISECOND`
`HRTime\Unit::MICROSECOND`
`HRTime\Unit::NANOSECOND`

- Installing/Configuring
  - Installation
- Examples
  - Basic usage
- HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
  - HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
  - HRTime\PerformanceCounter::getTicks — Current ticks from the system
  - HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value
- HRTime\StopWatch — The HRTime\StopWatch class
  - HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals
  - HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals
  - HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval
  - HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval
  - HRTime\StopWatch::isRunning — Whether the measurement is running
  - HRTime\StopWatch::start — Start time measurement
  - HRTime\StopWatch::stop — Stop time measurement
- HRTime\Unit — The HRTime\Unit class

- Calendar
  - Installing/Configuring
  - Predefined Constants
  - Calendar Functions
- Date/Time — Date and Time
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - DateTime — The DateTime class
  - DateTimeImmutable — The DateTimeImmutable class
  - DateTimeInterface — The DateTimeInterface interface
  - DateTimeZone — The DateTimeZone class
  - DateInterval — The DateInterval class
  - DatePeriod — The DatePeriod class
  - Date/Time Functions
  - Date/Time Errors and Exceptions
  - Supported Date and Time Formats
  - List of Supported Timezones
  - DateError — The DateError class
  - DateObjectError — The DateObjectError class
  - DateRangeError — The DateRangeError class
  - DateException — The DateException class
  - DateInvalidOperationException — The DateInvalidOperationException class
  - DateInvalidTimeZoneException — The DateInvalidTimeZoneException class
  - DateMalformedIntervalStringException — The DateMalformedIntervalStringException class
  - DateMalformedPeriodStringException — The DateMalformedPeriodStringException class
  - DateMalformedStringException — The DateMalformedStringException class
- HRTime — High resolution timing
  - Installing/Configuring
  - Examples
  - HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
  - HRTime\StopWatch — The HRTime\StopWatch class
  - HRTime\Unit — The HRTime\Unit class

# File System Related Extensions

# Direct IO

# Introduction

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

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: » https://pecl.php.net/package/dio.

## Resource Types

One resource type is defined by this extension: a file descriptor returned by dio_open().

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

`F_DUPFD` (int)

`F_GETFD` (int)

`F_GETFL` (int)

`F_GETLK` (int)

`F_GETOWN` (int)

`F_RDLCK` (int)

`F_SETFL` (int)

`F_SETLK` (int)

`F_SETLKW` (int)

`F_SETOWN` (int)

`F_UNLCK` (int)

`F_WRLCK` (int)

`O_APPEND` (int)

`O_ASYNC` (int)

`O_CREAT` (int)

`O_EXCL` (int)

`O_NDELAY` (int)

`O_NOCTTY` (int)

`O_NONBLOCK` (int)

`O_RDONLY` (int)

`O_RDWR` (int)

`O_SYNC` (int)

`O_TRUNC` (int)

`O_WRONLY` (int)

`S_IRGRP` (int)

`S_IROTH` (int)

`S_IRUSR` (int)

`S_IRWXG` (int)

`S_IRWXO` (int)

`S_IRWXU` (int)

`S_IWGRP` (int)

`S_IWOTH` (int)

`S_IWUSR` (int)

`S_IXGRP` (int)

`S_IXOTH` (int)

`S_IXUSR` (int)

# Direct IO Functions

# dio_close

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_close — Closes the file descriptor given by fd

### Description

dio_close(resource `$fd`): void

The function dio_close() closes the file descriptor `fd`.

### Parameters

`fd`

  The file descriptor returned by dio_open().

### Return Values

No value is returned.

### Examples

Example #1 Closing an open file descriptor

`<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
dio_close($fd);
?>`

### See Also

- dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/output stream functions allow

# dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_fcntl — Performs a c library fcntl on fd

### Description

dio_fcntl(resource `$fd`, int `$cmd`, mixed `$args` = ?): mixed

The dio_fcntl() function performs the operation specified by `cmd` on the file descriptor `fd`. Some commands require additional arguments `args` to be supplied.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`cmd`

  Can be one of the following operations:

  - `F_SETLK` - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  - `F_SETLKW` - like `F_SETLK`, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  - `F_GETLK` - dio_fcntl() returns an associative array (as described below) if someone else prevents lock. If there is no obstruction key "type" will set to `F_UNLCK`.

  - `F_DUPFD` - finds the lowest numbered available file descriptor greater than or equal to `args` and returns them.

  - `F_SETFL` - Sets the file descriptors flags to the value specified by `args`, which can be `O_APPEND`, `O_NONBLOCK` or `O_ASYNC`. To use `O_ASYNC` you will need to use the PCNTL extension.

`args`

  `args` is an associative array, when `cmd` is `F_SETLK` or `F_SETLLW`, with the following keys:

  - `start` - offset where lock begins

  - `length` - size of locked area. zero means to end of file

  - `whence` - Where l_start is relative to: can be `SEEK_SET`, `SEEK_END` and `SEEK_CUR`

  - `type` - type of lock: can be `F_RDLCK` (read lock), `F_WRLCK` (write lock) or `F_UNLCK` (unlock)

### Return Values

Returns the result of the C call.

### Examples

Example #1 Setting and clearing a lock

`<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
// the file descriptor appears locked
echo "The lock can not be cleared. It is held by someone else.";
} else {
echo "Lock successfully set/cleared";
}
dio_close($fd);
?>`

### Notes

> Note: This function is not implemented on Windows platforms.

# dio_open

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/output stream functions allow

### Description

dio_open(string `$filename`, int `$flags`, int `$mode` = 0): resource

dio_open() opens a file and returns a new file descriptor for it.

### Parameters

`filename`

  The pathname of the file to open.

`flags`

  The `flags` parameter is a bitwise-ORed value comprising flags from the following list. This value must include one of `O_RDONLY`, `O_WRONLY`, or `O_RDWR`. Additionally, it may include any combination of the other flags from this list.

  - `O_RDONLY` - opens the file for read access.

  - `O_WRONLY` - opens the file for write access.

  - `O_RDWR` - opens the file for both reading and writing.

  - `O_CREAT` - creates the file, if it doesn't already exist.

  - `O_EXCL` - if both `O_CREAT` and `O_EXCL` are set and the file already exists, dio_open() will fail.

  - `O_TRUNC` - if the file exists and is opened for write access, the file will be truncated to zero length.

  - `O_APPEND` - write operations write data at the end of the file.

  - `O_NONBLOCK` - sets non blocking mode.

  - `O_NOCTTY` - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file.

`mode`

  If `flags` contains `O_CREAT`, `mode` will set the permissions of the file (creation permissions). `mode` is required for correct operation when `O_CREAT` is specified in `flags` and is ignored otherwise.

  The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

### Return Values

A file descriptor or `false` on error.

### Examples

Example #1 Opening a file descriptor

`<?php
$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
dio_close($fd);
?>`

### See Also

- dio_close() - Closes the file descriptor given by fd

# dio_read

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_read — Reads bytes from a file descriptor

### Description

dio_read(resource `$fd`, int `$len` = 1024): string

The function dio_read() reads and returns `len` bytes from file with descriptor `fd`.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`len`

  The number of bytes to read. If not specified, dio_read() reads 1K sized block.

### Return Values

The bytes read from `fd`.

### See Also

- dio_write() - Writes data to fd with optional truncation at length

# dio_seek

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_seek — Seeks to pos on fd from whence

### Description

dio_seek(resource `$fd`, int `$pos`, int `$whence` = SEEK_SET): int

The function dio_seek() is used to change the file position of the given file descriptor.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`pos`

  The new position.

`whence`

  Specifies how the position `pos` should be interpreted:

  - `SEEK_SET` (default) - specifies that `pos` is specified from the beginning of the file.

  - `SEEK_CUR` - Specifies that `pos` is a count of characters from the current file position. This count may be positive or negative.

  - `SEEK_END` - Specifies that `pos` is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

### Return Values

### Examples

Example #1 Positioning in a file

`<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file
dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file
dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file
dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.
dio_close($fd);
?>`

# dio_stat

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_stat — Gets stat information about the file descriptor fd

### Description

dio_stat(resource `$fd`): array

dio_stat() returns information about the given file descriptor.

### Parameters

`fd`

  The file descriptor returned by dio_open().

### Return Values

Returns an associative array with the following keys:

- "device" - device

- "inode" - inode

- "mode" - mode

- "nlink" - number of hard links

- "uid" - user id

- "gid" - group id

- "device_type" - device type (if inode device)

- "size" - total size in bytes

- "blocksize" - blocksize

- "blocks" - number of blocks allocated

- "atime" - time of last access

- "mtime" - time of last modification

- "ctime" - time of last change

On error dio_stat() returns `null`.

# dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 < 5.1.0)

dio_tcsetattr — Sets terminal attributes and baud rate for a serial port

### Description

dio_tcsetattr(resource `$fd`, array `$options`): bool

dio_tcsetattr() sets the terminal attributes and baud rate of the open `fd`.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`options`

  The currently available options are:

  - 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  - 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  - 'stop' - stop bits - can be 1 or 2. Default value is 1.

  - 'parity' - can be 0,1 or 2. Default value is 0.

### Return Values

No value is returned.

### Examples

Example #1 Setting the baud rate on a serial port

`<?php
$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
dio_fcntl($fd, F_SETFL, O_SYNC);
dio_tcsetattr($fd, array(
'baud' => 9600,
'bits' => 8,
'stop' => 1,
'parity' => 0
));
while (true) {
$data = dio_read($fd, 256);
if ($data !== null && $date !== '') {
echo $data;
}
}
?>`

### Notes

> Note: This function is not implemented on Windows platforms.

# dio_truncate

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_truncate — Truncates file descriptor fd to offset bytes

### Description

dio_truncate(resource `$fd`, int `$offset`): bool

dio_truncate() truncates a file to at most `offset` bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`offset`

  The offset in bytes.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

> Note: This function is not implemented on Windows platforms.

# dio_write

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_write — Writes data to fd with optional truncation at length

### Description

dio_write(resource `$fd`, string `$data`, int `$len` = 0): int

dio_write() writes up to `len` bytes from `data` to file `fd`.

### Parameters

`fd`

  The file descriptor returned by dio_open().

`data`

  The written data.

`len`

  The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

### Return Values

Returns the number of bytes written to `fd`.

### See Also

- dio_read() - Reads bytes from a file descriptor

## Table of Contents

- dio_close — Closes the file descriptor given by fd
- dio_fcntl — Performs a c library fcntl on fd
- dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/output stream functions allow
- dio_read — Reads bytes from a file descriptor
- dio_seek — Seeks to pos on fd from whence
- dio_stat — Gets stat information about the file descriptor fd
- dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
- dio_truncate — Truncates file descriptor fd to offset bytes
- dio_write — Writes data to fd with optional truncation at length

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- Direct IO Functions
  - dio_close — Closes the file descriptor given by fd
  - dio_fcntl — Performs a c library fcntl on fd
  - dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/output stream functions allow
  - dio_read — Reads bytes from a file descriptor
  - dio_seek — Seeks to pos on fd from whence
  - dio_stat — Gets stat information about the file descriptor fd
  - dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
  - dio_truncate — Truncates file descriptor fd to offset bytes
  - dio_write — Writes data to fd with optional truncation at length

# Directories

# Predefined Constants

`DIRECTORY_SEPARATOR` (string)
`PATH_SEPARATOR` (string)
  Semicolon on Windows, colon otherwise.
`SCANDIR_SORT_ASCENDING` (int)
`SCANDIR_SORT_DESCENDING` (int)
`SCANDIR_SORT_NONE` (int)

# The Directory class

(PHP 4, PHP 5, PHP 7, PHP 8)

## Introduction

Instances of Directory are created by calling the dir() function, not by the new operator.

## Class synopsis

final class Directory {
/* Properties */
public readonly string $path;
public readonly resource $handle;
/* Methods */
public close(): void
public read(): string|false
public rewind(): void
}

## Properties

path

  The directory that was opened.

handle

  Can be used with other directory functions such as readdir(), rewinddir() and closedir().

## Changelog

Version | Description
--- | ---
8.5.0 | The class is now final.
8.1.0 | The path and handle properties are now readonly.

# Directory::close

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::close — Close directory handle

### Description

public Directory::close(): void

### Changelog

Version | Description
--- | ---
8.0.0 | No parameter is accepted. Previously, a directory handle could be passed as argument.

# Directory::read

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::read — Read entry from directory handle

### Description

public Directory::read(): string|false

### Changelog

Version | Description
--- | ---
8.0.0 | No parameter is accepted. Previously, a directory handle could be passed as argument.

# Directory::rewind

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::rewind — Rewind directory handle

### Description

public Directory::rewind(): void

### Changelog

Version | Description
--- | ---
8.0.0 | No parameter is accepted. Previously, a directory handle could be passed as argument.

## Table of Contents

- Directory::close — Close directory handle
- Directory::read — Read entry from directory handle
- Directory::rewind — Rewind directory handle

# Directory Functions

# See Also

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.

# chdir

(PHP 4, PHP 5, PHP 7, PHP 8)

chdir — Change directory

### Description

chdir(string `$directory`): bool

Changes PHP's current directory to `directory`.

### Parameters

`directory`

  The new current directory

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws an error of level `E_WARNING` on failure.

### Examples

Example #1 chdir() example

`<?php
// current directory
echo getcwd() . "\n";
chdir('public_html');
// current directory
echo getcwd() . "\n";
?>`

The above example will output something similar to:

    /home/vincent
    /home/vincent/public_html

### Notes

Caution

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, any changes to the current directory made through chdir() will be invisible to the operating system. All built-in PHP functions will still respect the change in current directory; but external library functions called using FFI will not. You can tell whether your copy of PHP was built with ZTS enabled using php -i or the built-in constant `PHP_ZTS`.

### See Also

- getcwd() - Gets the current working directory

# chroot

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

chroot — Change the root directory

### Description

chroot(string `$directory`): bool

Changes the root directory of the current process to `directory`, and changes the current working directory to "/".

This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Calling this function does not change the values of the `__DIR__` and `__FILE__` magic constants.

### Parameters

`directory`

  The path to change the root directory to.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 chroot() example

`<?php
chroot("/path/to/your/chroot/");
echo getcwd();
?>`

The above example will output:

    /

### Notes

> Note: This function is not implemented on Windows platforms.

> Note: This function is not available in PHP interpreters built with ZTS (Zend Thread Safety) enabled. To check whether your copy of PHP was built with ZTS enabled, use php -i or test the built-in constant `PHP_ZTS`.

# closedir

(PHP 4, PHP 5, PHP 7, PHP 8)

closedir — Close directory handle

### Description

closedir(?resource `$dir_handle` = `null`): void

Closes the directory stream indicated by `dir_handle`.

### Parameters

`dir_handle`
  A directory handle resource previously opened with opendir(). If `dir_handle` is `null` the last handle opened using opendir() will be used.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.5.0 | Using `null` for `dir_handle` is now deprecated. Instead, the last opened directory handle should be explicitly provided.
8.0.0 | `dir_handle` is now nullable.

### Examples

For a complete example refer to the opendir() documentation.

### See Also

- opendir() - Open directory handle
- readdir() - Read entry from directory handle
- rewinddir() - Rewind directory handle
- dir() - Return an instance of the Directory class
- is_dir() - Tells whether the filename is a directory
- glob() - Find pathnames matching a pattern
- scandir() - List files and directories inside the specified path

# dir

(PHP 4, PHP 5, PHP 7, PHP 8)

dir — Return an instance of the Directory class

### Description

dir(string `$directory`, ?resource `$context` = `null`): Directory|false

A pseudo-object-oriented mechanism for reading a directory. The given `directory` is opened.

### Parameters

`directory`

  Directory to open

`context`

  A context stream resource.

### Return Values

Returns an instance of Directory, or `false` in case of error.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` is now nullable.

### Examples

Example #1 dir() example

Please note the fashion in which Directory::read()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as - see Comparison Operators for more information) `false` since otherwise, any directory entry whose name evaluates to `false` will stop the loop.

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

The above example will output something similar to:

    Handle: Resource id #2
    Path: /etc/php5
    .
    ..
    apache
    cgi
    cli

### Notes

> Note:

> The order in which directory entries are returned by the read method is system-dependent.

# getcwd

(PHP 4, PHP 5, PHP 7, PHP 8)

getcwd — Gets the current working directory

### Description

getcwd(): string|false

Gets the current working directory.

### Parameters

This function has no parameters.

### Return Values

Returns the current working directory on success, or `false` on failure.

On some Unix variants, getcwd() will return `false` if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.

### Examples

Example #1 getcwd() example

`<?php
// current directory
echo getcwd() . "\n";
chdir('cvs');
// current directory
echo getcwd() . "\n";
?>`

The above example will output something similar to:

    /home/didou
    /home/didou/cvs

### Notes

Caution

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, the current working directory returned by getcwd() may be different from that returned by operating system interfaces. External libraries (invoked through FFI) which depend on the current working directory will be affected.

### See Also

- chdir() - Change directory
- chmod() - Changes file mode

# opendir

(PHP 4, PHP 5, PHP 7, PHP 8)

opendir — Open directory handle

### Description

opendir(string `$directory`, ?resource `$context` = `null`): resource|false

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

### Parameters

`directory`
  The directory path to open.
`context`
  For a description of the `context` parameter, refer to the streams section of the manual.

### Return Values

Returns a directory handle on success, or `false` on failure

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

This may happen if `directory` is not a valid directory, the directory can not be opened due to permission restrictions, or due to filesystem errors.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` is now nullable.

### Examples

Example #1 List all entries in a directory, skipping the special `.` and `..` directories

Because file and directory names can be strings that PHP considers "falsy" (e.g. a directory named `"0"`) and readdir() returns `false` when it has read all entries in a directory one needs to use the `===` comparison operator to properly distinguish between a directory entry whose name is "falsy" and having read all entries of the directory.

`<?php
if ($handle = opendir('/path/to/files')) {
echo "Entries:\n";
/* Correctly handling directory entries that may be considered falsy */
while (false !== ($entry = readdir($handle))) {
if ($entry === '.' || $entry === '..') {
continue;
}
echo "$entry\n";
}
closedir($handle);
}
?>`

The above example will output something similar to:

    Entries:
    base
    en
    fr
    output.md
    test.php

### See Also

- readdir() - Read entry from directory handle
- rewinddir() - Rewind directory handle
- closedir() - Close directory handle
- dir() - Return an instance of the Directory class
- is_dir() - Tells whether the filename is a directory
- glob() - Find pathnames matching a pattern
- scandir() - List files and directories inside the specified path

# readdir

(PHP 4, PHP 5, PHP 7, PHP 8)

readdir — Read entry from directory handle

### Description

readdir(?resource `$dir_handle` = `null`): string|false

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

### Parameters

`dir_handle`
  A directory handle resource previously opened with opendir(). If `dir_handle` is `null` the last handle opened using opendir() will be used.

### Return Values

Returns the entry name on success, or `false` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.5.0 | Using `null` for `dir_handle` is now deprecated. Instead, the last opened directory handle should be explicitly provided.
8.0.0 | `dir_handle` is now nullable.

### Examples

For a complete example refer to the opendir() documentation.

### See Also

- opendir() - Open directory handle
- rewinddir() - Rewind directory handle
- closedir() - Close directory handle
- dir() - Return an instance of the Directory class
- is_dir() - Tells whether the filename is a directory
- glob() - Find pathnames matching a pattern
- scandir() - List files and directories inside the specified path

# rewinddir

(PHP 4, PHP 5, PHP 7, PHP 8)

rewinddir — Rewind directory handle

### Description

rewinddir(?resource `$dir_handle` = `null`): void

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

### Parameters

`dir_handle`
  A directory handle resource previously opened with opendir(). If `dir_handle` is `null` the last handle opened using opendir() will be used.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.5.0 | Using `null` for `dir_handle` is now deprecated. Instead, the last opened directory handle should be explicitly provided.
8.0.0 | `dir_handle` is now nullable.

### Examples

For a complete example refer to the opendir() documentation.

### See Also

- opendir() - Open directory handle
- readdir() - Read entry from directory handle
- closedir() - Close directory handle
- dir() - Return an instance of the Directory class
- is_dir() - Tells whether the filename is a directory
- glob() - Find pathnames matching a pattern
- scandir() - List files and directories inside the specified path

# scandir

(PHP 5, PHP 7, PHP 8)

scandir — List files and directories inside the specified path

### Description

scandir(string `$directory`, int `$sorting_order` = `SCANDIR_SORT_ASCENDING`, ?resource `$context` = `null`): array|false

Returns an array of files and directories from the `directory`.

### Parameters

`directory`

  The directory that will be scanned.

`sorting_order`

  By default, the sorted order is alphabetical in ascending order. If the optional `sorting_order` is set to `SCANDIR_SORT_DESCENDING`, then the sort order is alphabetical in descending order. If it is set to `SCANDIR_SORT_NONE` then the result is unsorted.

`context`

  For a description of the `context` parameter, refer to the streams section of the manual.

### Return Values

Returns an array of filenames on success, or `false` on failure. If `directory` is not a directory, then boolean `false` is returned, and an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | `context` is now nullable.

### Examples

Example #1 A simple scandir() example

`<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, SCANDIR_SORT_DESCENDING);
print_r($files1);
print_r($files2);
?>`

The above example will output something similar to:

    Array
    (
        [0] => .
        [1] => ..
        [2] => bar.php
        [3] => foo.txt
        [4] => somedir
    )
    Array
    (
        [0] => somedir
        [1] => foo.txt
        [2] => bar.php
        [3] => ..
        [4] => .
    )

### Notes

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### See Also

- opendir() - Open directory handle
- readdir() - Read entry from directory handle
- glob() - Find pathnames matching a pattern
- is_dir() - Tells whether the filename is a directory
- sort() - Sort an array in ascending order

## Table of Contents

- chdir — Change directory
- chroot — Change the root directory
- closedir — Close directory handle
- dir — Return an instance of the Directory class
- getcwd — Gets the current working directory
- opendir — Open directory handle
- readdir — Read entry from directory handle
- rewinddir — Rewind directory handle
- scandir — List files and directories inside the specified path

- Predefined Constants
- Directory — The Directory class
  - Directory::close — Close directory handle
  - Directory::read — Read entry from directory handle
  - Directory::rewind — Rewind directory handle
- Directory Functions
  - chdir — Change directory
  - chroot — Change the root directory
  - closedir — Close directory handle
  - dir — Return an instance of the Directory class
  - getcwd — Gets the current working directory
  - opendir — Open directory handle
  - readdir — Read entry from directory handle
  - rewinddir — Rewind directory handle
  - scandir — List files and directories inside the specified path

# File Information

# Introduction

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

# Installing/Configuring

## Table of Contents

- Installation
- Resource Types

## Installation

This extension is enabled by default.

Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.

The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.

## Resource Types

Prior to PHP 8.1.0, there was one resource used in the Fileinfo extension: a magic database descriptor returned by finfo_open().

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

`FILEINFO_NONE` (int)
  No special handling.
`FILEINFO_SYMLINK` (int)
  Follow symlinks.
`FILEINFO_MIME_TYPE` (int)
  Return the mime type.
`FILEINFO_MIME_ENCODING` (int)
  Return the mime encoding of the file.
`FILEINFO_MIME` (int)
  Return the mime type and mime encoding as defined by RFC 2045.
`FILEINFO_COMPRESS` (int)
  Decompress compressed files. Disabled due to thread safety issues.
`FILEINFO_DEVICES` (int)
  Look at the contents of blocks or character special devices.
`FILEINFO_CONTINUE` (int)
  Return all matches, not just the first.
`FILEINFO_PRESERVE_ATIME` (int)
  If possible preserve the original access time.
`FILEINFO_RAW` (int)
  Don't translate unprintable characters to a `\ooo` octal representation.
`FILEINFO_EXTENSION` (int)
  Returns the file extension appropriate for the MIME type detected in the file. For types that commonly have multiple file extensions, such as `JPEG` images, then the return value is multiple extensions separated by a forward slash e.g.: `"jpeg/jpg/jpe/jfif"`. For unknown types not available in the magic.mime database, then return value is `"???"`. Available since PHP 7.2.0.
`FILEINFO_APPLE` (int)
  Return the Apple creator and type.

# Fileinfo Functions

# finfo_buffer

# finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — Return information about a string buffer

### Description

Procedural style

finfo_buffer(
finfo `$finfo`,
string `$string`,
int `$flags` = `FILEINFO_NONE`,
?resource `$context` = `null`
): string|false

Object-oriented style

public finfo::buffer(string `$string`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false

This function is used to get information about binary data in a string.

### Parameters

`finfo`

  An finfo instance, returned by finfo_open().

`string`
  Content of a file to be checked.
`flags`
  One or disjunction of more Fileinfo constants.
`context`

### Return Values

Returns a textual description of the `string` argument, or `false` if an error occurred.

### Changelog

Version | Description
--- | ---
8.1.0 | The `finfo` parameter expects an finfo instance now; previously, a resource was expected.
8.0.0 | `context` is nullable now.

### Examples

Example #1 A finfo_buffer() example

`<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>`

The above example will output something similar to:

    application/x-sh; charset=us-ascii

### See Also

- finfo_file() - Return information about a file

# finfo_close

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_close — Close finfo instance

Warning

This function has been DEPRECATED as of PHP 8.5.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
finfo_close(finfo `$finfo`): true

This function used to close the instance opened by finfo_open() until PHP 7.4, but it's a no-op since the finfo resource to object conversion done in PHP 8.0, and has been deprecated in PHP 8.5.

### Parameters

`finfo`

  An finfo instance, returned by finfo_open().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.5.0 | This function has been deprecated.
8.5.0 | The return type is `true` now; previously, it was bool.
8.1.0 | This function is a NOP now.
8.1.0 | The `finfo` parameter expects an finfo instance now; previously, a resource was expected.

# finfo_file

# finfo::file

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file

### Description

Procedural style

finfo_file(
finfo `$finfo`,
string `$filename`,
int `$flags` = `FILEINFO_NONE`,
?resource `$context` = `null`
): string|false

Object-oriented style

public finfo::file(string `$filename`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false

This function is used to get information about a file.

### Parameters

`finfo`

  An finfo instance, returned by finfo_open().

`filename`
  Name of a file to be checked.
`flags`
  One or disjunction of more Fileinfo constants.
`context`
  For a description of `contexts`, refer to Stream Functions.

### Return Values

Returns a textual description of the contents of the `filename` argument, or `false` if an error occurred.

### Changelog

Version | Description
--- | ---
8.1.0 | The `finfo` parameter expects an finfo instance now; previously, a resource was expected.
8.0.0 | `context` is nullable now.

### Examples

Example #1 A finfo_file() example

`<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type aka mimetype extension
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>`

The above example will output something similar to:

    text/html
    image/gif
    application/vnd.ms-excel

### See Also

- finfo_buffer() - Return information about a string buffer

# finfo_open

# finfo::__construct

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — Create a new finfo instance

### Description

Procedural style

finfo_open(int `$flags` = `FILEINFO_NONE`, ?string `$magic_database` = `null`): finfo|false

Object-oriented style (constructor):

public finfo::__construct(int `$flags` = `FILEINFO_NONE`, ?string `$magic_database` = `null`)

This function opens a magic database and returns its instance.

### Parameters

`flags`
  One or disjunction of more Fileinfo constants.
`magic_database`
  Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the `MAGIC` environment variable is used. If the environment variable isn't set, then PHP's bundled magic database will be used. Passing `null` or an empty string will be equivalent to the default value.

### Return Values

(Procedural style only) Returns an finfo instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an finfo instance now; previously, a resource was returned.
8.0.3 | `magic_database` is nullable now.

### Examples

Example #1 Object-oriented style

`<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);
?>`

Example #2 Procedural style

`<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension
if (!$finfo) {
echo "Opening fileinfo database failed";
exit();
}
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);
/* close connection */
finfo_close($finfo);
?>`

The above example will output:

    text/plain; charset=us-ascii

### Notes

> Note: Generally, using the bundled magic database (by leaving `magic_database` and the `MAGIC` environment variables unset) is the best course of action unless you specifically need a custom magic database.

### See Also

- finfo_close() - Close finfo instance

# finfo_set_flags

# finfo::set_flags

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flags — Set libmagic configuration options

### Description

Procedural style

finfo_set_flags(finfo `$finfo`, int `$flags`): true

Object-oriented style

public finfo::set_flags(int `$flags`): true

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

### Parameters

`finfo`

  An finfo instance, returned by finfo_open().

`flags`
  One or disjunction of more Fileinfo constants.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `finfo` parameter expects an finfo instance now; previously, a resource was expected.

# mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mime_content_type — Detect MIME Content-type for a file

### Description

mime_content_type(resource|string `$filename`): string|false

Returns the MIME content type for a file as determined by using information from the magic.mime file.

### Parameters

`filename`
  Path to the tested file.

### Return Values

Returns the content type in MIME format, like `text/plain` or `application/octet-stream`, or `false` on failure.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 mime_content_type() Example

`<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>`

The above example will output:

    image/gif
    text/plain

### See Also

- finfo_file() - Return information about a file
- finfo_buffer() - Return information about a string buffer

## Table of Contents

- finfo_buffer — Return information about a string buffer
- finfo_close — Close finfo instance
- finfo_file — Return information about a file
- finfo_open — Create a new finfo instance
- finfo_set_flags — Set libmagic configuration options
- mime_content_type — Detect MIME Content-type for a file

# The finfo class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

## Introduction

This class provides an object-oriented interface into the fileinfo functions.

## Class synopsis

class finfo {
/* Methods */
public __construct(int `$flags` = `FILEINFO_NONE`, ?string `$magic_database` = `null`)
public buffer(string `$string`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false
public file(string `$filename`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false
public set_flags(int `$flags`): true
}

# finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::buffer — Alias of finfo_buffer()

### Description

public finfo::buffer(string `$string`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false

This function is an alias of: finfo_buffer()

# finfo::__construct

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::__construct — Alias of finfo_open()

### Description

public finfo::__construct(int `$flags` = `FILEINFO_NONE`, ?string `$magic_database` = `null`)

This function is an alias of: finfo_open()

### Changelog

Version | Description
--- | ---
8.0.3 | `magic_database` is nullable now.

# finfo::file

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::file — Alias of finfo_file()

### Description

public finfo::file(string `$filename`, int `$flags` = `FILEINFO_NONE`, ?resource `$context` = `null`): string|false

This function is an alias of: finfo_file()

# finfo::set_flags

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::set_flags — Alias of finfo_set_flags()

### Description

public finfo::set_flags(int `$flags`): true

This function is an alias of: finfo_set_flags()

## Table of Contents

- finfo::buffer — Alias of finfo_buffer()
- finfo::__construct — Alias of finfo_open
- finfo::file — Alias of finfo_file()
- finfo::set_flags — Alias of finfo_set_flags()

- Installing/Configuring
  - Installation
  - Resource Types
- Predefined Constants
- Fileinfo Functions
  - finfo_buffer — Return information about a string buffer
  - finfo_close — Close finfo instance
  - finfo_file — Return information about a file
  - finfo_open — Create a new finfo instance
  - finfo_set_flags — Set libmagic configuration options
  - mime_content_type — Detect MIME Content-type for a file
- finfo — The finfo class
  - finfo::buffer — Alias of finfo_buffer()
  - finfo::__construct — Alias of finfo_open
  - finfo::file — Alias of finfo_file()
  - finfo::set_flags — Alias of finfo_set_flags()

# Filesystem

# Introduction

No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: `-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64`.

# Installing/Configuring

## Table of Contents

- Runtime Configuration
- Resource Types

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
allow_url_fopen | "1" | `INI_SYSTEM` |
allow_url_include | "0" | `INI_SYSTEM` | Deprecated as of PHP 7.4.0.
user_agent | NULL | `INI_ALL` |
default_socket_timeout | "60" | `INI_ALL` |
from | "" | `INI_ALL` |
auto_detect_line_endings | "0" | `INI_ALL` | Deprecated as of PHP 8.1.0.
sys_temp_dir | "" | `INI_SYSTEM` |

Here's a short explanation of the configuration directives.

`allow_url_fopen` bool

  This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

`allow_url_include` bool

  This option allows the use of URL-aware fopen wrappers with the following functions: include, include_once, require, require_once.

  > Note:

  > This setting requires allow_url_fopen to be on.

`user_agent` string

  Define the user agent for PHP to send.

`default_socket_timeout` int

  Default timeout (in seconds) for socket based streams. Specifying a negative value means an infinite timeout.

`from` string

  The email address to be used on unauthenticated FTP connections and as the value of From header for HTTP connections, when using the ftp and http wrappers, respectively.

`auto_detect_line_endings` bool

  When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

  This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

`sys_temp_dir` string

## Resource Types

The file system uses `streams` as their resource type. Streams are documented in its own reference chapter, Streams.

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

`SEEK_SET` (int)
`SEEK_CUR` (int)
`SEEK_END` (int)
`LOCK_SH` (int)
`LOCK_EX` (int)
`LOCK_UN` (int)
`LOCK_NB` (int)

Available `flags` for file()
`FILE_USE_INCLUDE_PATH` (int)
  Search for `filename` in include_path.
`FILE_NO_DEFAULT_CONTEXT` (int)
`FILE_APPEND` (int)
  Append content to existing file.
`FILE_IGNORE_NEW_LINES` (int)
  Strip EOL characters.
`FILE_SKIP_EMPTY_LINES` (int)
  Skip empty lines.
`FILE_BINARY` (int)

  Binary mode.

  Warning

  This constant has no effect, and is deprecated as of PHP 8.1.0.

`FILE_TEXT` (int)

  Text mode.

  Warning

  This constant has no effect, and is deprecated as of PHP 8.1.0.

Available `flags` for glob()
`GLOB_AVAILABLE_FLAGS` (int)
  All `GLOB_*` flags combined. Equivalent to `0` | `GLOB_BRACE` | `GLOB_MARK` | `GLOB_NOSORT` | `GLOB_NOCHECK` | `GLOB_NOESCAPE` | `GLOB_ERR` | `GLOB_ONLYDIR`
`GLOB_BRACE` (int)
  Expands {a,b,c} to match 'a', 'b', or 'c'

  > Note: `GLOB_BRACE` is not available on some non GNU systems, like Solaris or Alpine Linux.

`GLOB_ERR` (int)
  Stop on read errors (like unreadable directories), by default errors are ignored.
`GLOB_MARK` (int)
  Adds a slash (a backslash on Windows) to each directory returned
`GLOB_NOCHECK` (int)
  Return the search pattern if no files matching it were found
`GLOB_NOESCAPE` (int)
  Backslashes do not quote metacharacters
`GLOB_NOSORT` (int)
  Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
`GLOB_ONLYDIR` (int)
  Return only directory entries which match the pattern

Available `flags` for pathinfo()
`PATHINFO_ALL` (int)
  All parts of the pathinfo returned as an associative array.
`PATHINFO_DIRNAME` (int)
  The path of the directory or file.
`PATHINFO_BASENAME` (int)
  The name of the directory or the name and extension of the file.
`PATHINFO_EXTENSION` (int)
  The extension of the file.
`PATHINFO_FILENAME` (int)
  The name of the file (without the extension) or directory.

Available `scanner_mode`s for parse_ini_file() and parse_ini_string()
`INI_SCANNER_NORMAL` (int)
  Normal INI scanner mode.
`INI_SCANNER_RAW` (int)
  Raw INI scanner mode.
`INI_SCANNER_TYPED` (int)
  Typed INI scanner mode.

Available `flags` for fnmatch()
`FNM_NOESCAPE` (int)
  Disable backslash escaping.
`FNM_PATHNAME` (int)
  Slash in string only matches slash in the given pattern.
`FNM_PERIOD` (int)
  Leading period in string must be exactly matched by period in the given pattern.
`FNM_CASEFOLD` (int)
  Caseless match. Part of the GNU extension.

PHP File Upload Constants
`UPLOAD_ERR_CANT_WRITE` (int)

  Failed to write file to disk. The value of the constant is `7`.

`UPLOAD_ERR_EXTENSION` (int)

  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. The value of the constant is `8`.

`UPLOAD_ERR_FORM_SIZE` (int)

  The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. The value of the constant is `2`.

`UPLOAD_ERR_INI_SIZE` (int)

  The uploaded file exceeds the upload_max_filesize directive in php.ini. The value of the constant is `1`.

`UPLOAD_ERR_NO_FILE` (int)

  No file was uploaded. The value of the constant is `4`.

`UPLOAD_ERR_NO_TMP_DIR` (int)

  Missing a temporary folder. The value of the constant is `6`.

`UPLOAD_ERR_OK` (int)

  There is no error, the file uploaded with success. The value of the constant is `0`.

`UPLOAD_ERR_PARTIAL` (int)

  The uploaded file was only partially uploaded. The value of the constant is `3`.

# Filesystem Functions

# See Also

For related functions, see also the Directory and Program Execution sections.

For a list and explanation of the various URL wrappers that can be used as remote files, see also Supported Protocols and Wrappers.

# basename

(PHP 4, PHP 5, PHP 7, PHP 8)

basename — Returns trailing name component of path

### Description

basename(string `$path`, string `$suffix` = ""): string

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

> Note:

> basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "`..`".

Caution

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. If `path` contains characters which are invalid for the current locale, the behavior of basename() is undefined.

### Parameters

`path`

  A path.

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

`suffix`

  If the name component ends in `suffix` this will also be cut off.

### Return Values

Returns the base name of the given `path`.

### Examples

Example #1 basename() example

`<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/sudoers.d").PHP_EOL;
echo "3) ".basename("/etc/passwd").PHP_EOL;
echo "4) ".basename("/etc/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
?>`

The above example will output:

    1) sudoers
    2) sudoers.d
    3) passwd
    4) etc
    5) .
    6)

### See Also

- dirname() - Returns a parent directory's path
- pathinfo() - Returns information about a file path

# chgrp

(PHP 4, PHP 5, PHP 7, PHP 8)

chgrp — Changes file group

### Description

chgrp(string `$filename`, string|int `$group`): bool

Attempts to change the group of the file `filename` to `group`.

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

### Parameters

`filename`

  Path to the file.

`group`

  A group name or number.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Changing a file's group

`<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
clearstatcache(); // do not cache filegroup() results
printf($format, $filename, date('r'), filegroup($filename));
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: On Windows, this function fails silently when applied on a regular file.

### See Also

- chown() - Changes file owner
- chmod() - Changes file mode

# chmod

(PHP 4, PHP 5, PHP 7, PHP 8)

chmod — Changes file mode

### Description

chmod(string `$filename`, int `$permissions`): bool

Attempts to change the mode of the specified file to that given in `permissions`.

### Parameters

`filename`

  Path to the file.

`permissions`

  Note that `permissions` is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix `permissions` with a zero (0). Strings such as "g+w" will not work properly.

  `<?php
  chmod("/somedir/somefile", 755); // decimal; probably incorrect
  chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
  chmod("/somedir/somefile", 0755); // octal; correct value of mode
  ?>`

  The `permissions` parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

  `<?php
  // Read and write for owner, nothing for everybody else
  chmod("/somedir/somefile", 0600);
  // Read and write for owner, read for everybody else
  chmod("/somedir/somefile", 0644);
  // Everything for owner, read and execute for others
  chmod("/somedir/somefile", 0755);
  // Everything for owner, read and execute for owner's group
  chmod("/somedir/somefile", 0750);
  ?>`

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Notes

> Note:

> The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

### See Also

- chown() - Changes file owner
- chgrp() - Changes file group
- fileperms() - Gets file permissions
- stat() - Gives information about a file

# chown

(PHP 4, PHP 5, PHP 7, PHP 8)

chown — Changes file owner

### Description

chown(string `$filename`, string|int `$user`): bool

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

### Parameters

`filename`

  Path to the file.

`user`

  A user name or number.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Simple chown() usage

`<?php
// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";
// Set the user
chown($path, $user_name);
// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));
?>`

The above example will output something similar to:

    Array
    (
        [name] => root
        [passwd] => x
        [uid] => 0
        [gid] => 0
        [gecos] => root
        [dir] => /root
        [shell] => /bin/bash
    )

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: On Windows, this function fails silently when applied on a regular file.

### See Also

- chmod() - Changes file mode
- chgrp() - Changes file group

# clearstatcache

(PHP 4, PHP 5, PHP 7, PHP 8)

clearstatcache — Clears file status cache

### Description

clearstatcache(bool `$clear_realpath_cache` = `false`, string `$filename` = ""): void

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return `false` until you create the file. If you create the file, it will return `true` even if you then delete the file. However unlink() clears the cache automatically.

> Note:

> This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

### Parameters

`clear_realpath_cache`

  Whether to also clear the realpath cache.

`filename`

  Clear the realpath cache for a specific filename only; only used if `clear_realpath_cache` is `true`.

### Return Values

No value is returned.

### Examples

Example #1 clearstatcache() example

`<?php
$file = 'output_log.txt';
function get_owner($file)
{
$stat = stat($file);
$user = posix_getpwuid($stat['uid']);
return $user['name'];
}
$format = "UID @ %s: %s\n";
printf($format, date('r'), get_owner($file));
chown($file, 'ross');
printf($format, date('r'), get_owner($file));
clearstatcache();
printf($format, date('r'), get_owner($file));
?>`

The above example will output something similar to:

    UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
    UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
    UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross

# copy

(PHP 4, PHP 5, PHP 7, PHP 8)

copy — Copies file

### Description

copy(string `$from`, string `$to`, ?resource `$context` = `null`): bool

Makes a copy of the file `from` to `to`.

If you wish to move a file, use the rename() function.

### Parameters

`from`

  Path to the source file.

`to`

  The destination path. If `to` is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

  Warning

  If the destination file already exists, it will be overwritten.

`context`

  A valid context resource created with stream_context_create().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 copy() example

`<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>`

### See Also

- move_uploaded_file() - Moves an uploaded file to a new location
- rename() - Renames a file or directory
- The section of the manual about handling file uploads

# delete

delete — See unlink() or unset()

### Description

There is no delete keyword or function in the PHP language. If you arrived at this page seeking to delete a file, try unlink(). To delete a variable from the local scope, check out unset().

### See Also

- unlink() - Deletes a file
- unset() - unset a given variable

# dirname

(PHP 4, PHP 5, PHP 7, PHP 8)

dirname — Returns a parent directory's path

### Description

dirname(string `$path`, int `$levels` = 1): string

Given a string containing the path of a file or directory, this function will return the parent directory's path that is `levels` up from the current directory.

> Note:

> dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "`..`".

Caution

On Windows, dirname() assumes the currently set codepage, so for it to see the correct directory name with multibyte character paths, the matching codepage must be set. If `path` contains characters which are invalid for the current codepage, the behavior of dirname() is undefined.

On other systems, dirname() assumes `path` to be encoded in an ASCII compatible encoding. Otherwise, the behavior of the function is undefined.

### Parameters

`path`

  A path.

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

`levels`

  The number of parent directories to go up.

  This must be an integer greater than 0.

### Return Values

Returns the path of a parent directory. If there are no slashes in `path`, a dot ('`.`') is returned, indicating the current directory. Otherwise, the returned string is `path` with any trailing `/component` removed.

Caution

Be careful when using this function in a loop that can reach the top-level directory as this can result in an infinite loop.

`<?php
dirname('.'); // Will return '.'.
dirname('/'); // Will return `\` on Windows and '/' on *nix systems.
dirname('\\'); // Will return `\` on Windows and '.' on *nix systems.
dirname('C:\\'); // Will return 'C:\' on Windows and '.' on *nix systems.
?>`

### Examples

Example #1 dirname() example

`<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo dirname("/etc/") . PHP_EOL;
echo dirname(".") . PHP_EOL;
echo dirname("C:\\") . PHP_EOL;
echo dirname("/usr/local/lib", 2);`

The above example will output something similar to:

    /etc
    / (or \ on Windows)
    .
    C:\
    /usr

### See Also

- basename() - Returns trailing name component of path
- pathinfo() - Returns information about a file path
- realpath() - Returns canonicalized absolute pathname

# disk_free_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

disk_free_space — Returns available space on filesystem or disk partition

### Description

disk_free_space(string `$directory`): float|false

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

### Parameters

`directory`

  A directory of the filesystem or disk partition.

  > Note:

  > Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.

### Return Values

Returns the number of available bytes as a float or `false` on failure.

### Examples

Example #1 disk_free_space() example

`<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");
// On Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

### See Also

- disk_total_space() - Returns the total size of a filesystem or disk partition

# disk_total_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

disk_total_space — Returns the total size of a filesystem or disk partition

### Description

disk_total_space(string `$directory`): float|false

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

### Parameters

`directory`

  A directory of the filesystem or disk partition.

### Return Values

Returns the total number of bytes as a float or `false` on failure.

### Examples

Example #1 disk_total_space() example

`<?php
// $ds contains the total number of bytes available on "/"
$ds = disk_total_space("/");
// On Windows:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

### See Also

- disk_free_space() - Returns available space on filesystem or disk partition

# diskfreespace

(PHP 4, PHP 5, PHP 7, PHP 8)

diskfreespace — Alias of disk_free_space()

### Description

This function is an alias of: disk_free_space().

# fclose

(PHP 4, PHP 5, PHP 7, PHP 8)

fclose — Closes an open file pointer

### Description

fclose(resource `$stream`): bool

The file pointed to by `stream` is closed.

### Parameters

`stream`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 A simple fclose() example

`<?php
$handle = fopen('somefile.txt', 'r');
fclose($handle);
?>`

### See Also

- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection

# fdatasync

(PHP 8 >= 8.1.0)

fdatasync — Synchronizes data (but not meta-data) to the file

### Description

fdatasync(resource `$stream`): bool

This function synchronizes `stream` contents to storage media, just like fsync() does, but it does not synchronize file meta-data. Note that this function is only effectively different in POSIX systems. In Windows, this function is aliased to fsync().

### Parameters

`stream`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 fdatasync() example

`<?php
$file = 'test.txt';
$stream = fopen($file, 'w');
fwrite($stream, 'test data');
fwrite($stream, "\r\n");
fwrite($stream, 'additional data');
fdatasync($stream);
fclose($stream);
?>`

### See Also

- fflush() - Flushes the output to a file
- fsync() - Synchronizes changes to the file (including meta-data)

# feof

(PHP 4, PHP 5, PHP 7, PHP 8)

feof — Tests for end-of-file on a file pointer

### Description

feof(resource `$stream`): bool

Tests for end-of-file on a file pointer.

### Parameters

`stream`

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

### Return Values

Returns `true` if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns `false`.

### Notes

Warning

If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

`<?php
function safe_feof($fp, &$start = NULL) {
$start = microtime(true);
return feof($fp);
}
/* Assuming $fp is previously opened by fsockopen() */
$start = NULL;
$timeout = ini_get('default_socket_timeout');
while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
/* Handle */
}
?>`
Warning

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return `true`.

Example #2 feof() example with an invalid file pointer

`<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");
// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}
fclose($file);
?>`

# fflush

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

fflush — Flushes the output to a file

### Description

fflush(resource `$stream`): bool

This function forces a write of all buffered output to the resource pointed to by the file `stream`.

### Parameters

`stream`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 File write example using fflush()

`<?php
$filename = 'bar.txt';
$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>`

### See Also

- clearstatcache() - Clears file status cache
- fwrite() - Binary-safe file write

# fgetc

(PHP 4, PHP 5, PHP 7, PHP 8)

fgetc — Gets character from file pointer

### Description

fgetc(resource `$stream`): string|false

Gets a character from the given file pointer.

### Parameters

`stream`

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

### Return Values

Returns a string containing a single character read from the file pointed to by `stream`. Returns `false` on EOF.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Examples

Example #1 A fgetc() example

`<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>`

### Notes

> Note: This function is binary-safe.

### See Also

- fread() - Binary-safe file read
- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fsockopen() - Open Internet or Unix domain socket connection
- fgets() - Gets line from file pointer

# fgetcsv

(PHP 4, PHP 5, PHP 7, PHP 8)

fgetcsv — Gets line from file pointer and parse for CSV fields

### Description

fgetcsv(
resource `$stream`,
?int `$length` = `null`,
string `$separator` = ",",
string `$enclosure` = "\"",
string `$escape` = "\\"
): array|false

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

> Note: The locale settings are taken into account by this function. For example, data encoded in certain one-byte encodings may be parsed incorrectly if `LC_CTYPE` is `en_US.UTF-8`.

### Parameters

`stream`

  A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

`length`

  Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of `length` characters, unless the split would occur inside an enclosure.

  Omitting this parameter (or setting it to 0, or `null` in PHP 8.0.0 or later) the maximum line length is not limited, which is slightly slower.

`separator`

  The `separator` parameter sets the field separator. It must be a single byte character.

`enclosure`

  The `enclosure` parameter sets the field enclosure character. It must be a single byte character.

`escape`

  The `escape` parameter sets the escape character. It must be a single byte character or the empty string. The empty string (`""`) disables the proprietary escape mechanism.

  Warning

  In the input stream, the `enclosure` character can always be escaped by doubling it inside a quoted string, resulting in a single `enclosure` character in the parsed result. The `escape` character works differently: If a sequence of `escape` and `enclosure` characters appear in the input, both characters will be present in the parsed result. So for the default parameters, a CVS line like `"a""b","c\"d"` will have the fields parsed as `a"b` and `c\"d`, respectively.

  Warning

  As of PHP 8.4.0, depending on the default value of `escape` is deprecated. It needs to be provided explicitly either positionally or by the use of named arguments.

Warning

When `escape` is set to anything other than an empty string (`""`) it can result in CSV that is not compliant with » RFC 4180 or unable to survive a roundtrip through the PHP CSV functions. The default for `escape` is `"\\"` so it is recommended to set it to the empty string explicitly. The default value will change in a future version of PHP, no earlier than PHP 9.0.

### Return Values

Returns an indexed array containing the fields read on success, or `false` on failure.

> Note:

> A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

> Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

### Errors/Exceptions

Throws a ValueError if `separator` or `enclosure` is not one byte long.

Throws a ValueError if `escape` is not one byte long or the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Relying on the default value of `escape` is now deprecated.
8.3.0 | An empty string is returned instead of a string with a single null byte for the last field if it contains only an unterminated enclosure.
8.0.0 | `length` is now nullable.
7.4.0 | The `escape` parameter now also accepts an empty string to disable the proprietary escape mechanism.

### Examples

Example #1 Read and print the entire contents of a CSV file

`<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>`

### See Also

- fputcsv() - Format line as CSV and write to file pointer
- str_getcsv() - Parse a CSV string into an array
- SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields
- SplFileObject::fputcsv() - Write a field array as a CSV line
- SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
- SplFileObject::getCsvControl() - Get the delimiter, enclosure and escape character for CSV
- explode() - Split a string by a string
- file() - Reads entire file into an array
- pack() - Pack data into binary string

# fgets

(PHP 4, PHP 5, PHP 7, PHP 8)

fgets — Gets line from file pointer

### Description

fgets(resource `$stream`, ?int `$length` = `null`): string|false

Gets a line from file pointer.

### Parameters

`stream`

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

`length`

  Reading ends when `length` - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

### Return Values

Returns a string of up to `length` - 1 bytes read from the file pointed to by `stream`. If there is no more data to read in the file pointer, then `false` is returned.

If an error occurs, `false` is returned.

### Examples

Example #1 Reading a file line by line

`<?php
$fp = @fopen("/tmp/inputfile.txt", "r");
if ($fp) {
while (($buffer = fgets($fp, 4096)) !== false) {
echo $buffer, PHP_EOL;
}
if (!feof($fp)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($fp);
}
?>`

### Notes

> Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

> Note:

> People used to the 'C' semantics of fgets() should note the difference in how `EOF` is returned.

### See Also

- fgetss() - Gets line from file pointer and strip HTML tags
- fread() - Binary-safe file read
- fgetc() - Gets character from file pointer
- stream_get_line() - Gets line from stream resource up to a given delimiter
- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fsockopen() - Open Internet or Unix domain socket connection
- stream_set_timeout() - Set timeout period on a stream

# fgetss

(PHP 4, PHP 5, PHP 7)

fgetss — Gets line from file pointer and strip HTML tags

Warning

This function has been DEPRECATED as of PHP 7.3.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

fgetss(resource `$handle`, int `$length` = ?, string `$allowable_tags` = ?): string

Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags() on the return value of fgets().

### Parameters

`handle`

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

`length`

  Length of the data to be retrieved.

`allowable_tags`

  You can use the optional third parameter to specify tags which should not be stripped. See strip_tags() for details regarding `allowable_tags`.

### Return Values

Returns a string of up to `length` - 1 bytes read from the file pointed to by `handle`, with all HTML and PHP code stripped.

If an error occurs, returns `false`.

### Examples

Example #1 Reading a PHP file line-by-line

`<?php
$str = <<<EOD
<html><body>
<p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);
$handle = @fopen("sample.php", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>`

The above example will output something similar to:

    Welcome! Today is the  of .

    Text outside of the HTML block.

### Notes

> Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

### See Also

- fgets() - Gets line from file pointer
- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fsockopen() - Open Internet or Unix domain socket connection
- strip_tags() - Strip HTML and PHP tags from a string
- SplFileObject::fgetss() - Gets line from file and strip HTML tags
- The string.strip_tags filter

# file

(PHP 4, PHP 5, PHP 7, PHP 8)

file — Reads entire file into an array

### Description

file(string `$filename`, int `$flags` = 0, ?resource `$context` = `null`): array|false

Reads an entire file into an array.

> Note:

> You can use file_get_contents() to return the contents of a file as a string.

### Parameters

`filename`

  Path to the file.

  Tip

  A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

`flags`

  The optional parameter `flags` can be one, or more, of the following constants:

  `FILE_USE_INCLUDE_PATH`
    Search for the file in the include_path.
  `FILE_IGNORE_NEW_LINES`
    Omit newline at the end of each array element.
  `FILE_SKIP_EMPTY_LINES`
    Skip empty lines.
  `FILE_NO_DEFAULT_CONTEXT`
    Don't use the default context.
`context`

  A context stream resource.

### Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns `false`.

> Note:

> Each line in the resulting array will include the line ending, unless `FILE_IGNORE_NEW_LINES` is used.

> Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

### Errors/Exceptions

As of PHP 8.3.0, throws a ValueError if `flags` includes any invalid values, such as `FILE_APPEND`.

Emits an `E_WARNING` level error if the file does not exist.

### Changelog

Version | Description
--- | ---
8.3.0 | ValueError is thrown for any invalid values of `flags`.

### Examples

Example #1 file() example

`<?php
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// Using the optional flags parameter
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>`

### Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a `close_notify` indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the `https://` wrapper and will suppress the warning. When using fsockopen() to create an `ssl://` socket, the developer is responsible for detecting and suppressing this warning.

### See Also

- file_get_contents() - Reads entire file into a string
- readfile() - Outputs a file
- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection
- popen() - Opens process file pointer
- include - include
- stream_context_create() - Creates a stream context

# file_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

file_exists — Checks whether a file or directory exists

### Description

file_exists(string `$filename`): bool

Checks whether a file or directory exists.

### Parameters

`filename`

  Path to the file or directory.

  On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

### Return Values

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

> Note:

> This function will return `false` for symlinks pointing to non-existing files.

> Note:

> The check is done using the real UID/GID instead of the effective one.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Testing whether a file exists

`<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- is_readable() - Tells whether a file exists and is readable
- is_writable() - Tells whether the filename is writable
- is_file() - Tells whether the filename is a regular file
- file() - Reads entire file into an array
- SplFileInfo

# file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contents — Reads entire file into a string

### Description

file_get_contents(
string `$filename`,
bool `$use_include_path` = `false`,
?resource `$context` = `null`,
int `$offset` = 0,
?int `$length` = `null`
): string|false

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified `offset` up to `length` bytes. On failure, file_get_contents() will return `false`.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

> Note:

> If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

### Parameters

`filename`

  Name of the file to read.

`use_include_path`

  > Note:

  > The `FILE_USE_INCLUDE_PATH` constant can be used to trigger include path search. This is not possible if strict typing is enabled, since `FILE_USE_INCLUDE_PATH` is an int. Use `true` instead.

`context`

  A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by `null`.

`offset`

  The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.

  Seeking (`offset`) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

`length`

  Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

### Return Values

The function returns the read data or `false` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Errors/Exceptions

An `E_WARNING` level error is generated if `filename` cannot be found, `length` is less than zero, or if seeking to the specified `offset` in the stream fails.

When file_get_contents() is called on a directory, an `E_WARNING` level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` is nullable now.
7.1.0 | Support for negative `offset`s has been added.

### Examples

Example #1 Get and output the source of the homepage of a website

`<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>`

Example #2 Searching within the include_path

`<?php
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// Otherwise
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>`

Example #3 Reading a section of a file

`<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>`

The above example will output something similar to:

    string(14) "lle Bjori Ro"

Example #4 Using stream contexts

`<?php
// Create a stream
$opts = [
'http' => [
'method' => "GET",
'header' => "Accept-language: en\r\n" .
"Cookie: foo=bar",
]
];
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>`

### Notes

> Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a `close_notify` indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the `https://` wrapper and will suppress the warning. When using fsockopen() to create an `ssl://` socket, the developer is responsible for detecting and suppressing this warning.

### See Also

- file() - Reads entire file into an array
- fgets() - Gets line from file pointer
- fread() - Binary-safe file read
- readfile() - Outputs a file
- file_put_contents() - Write data to a file
- stream_get_contents() - Reads remainder of a stream into a string
- stream_context_create() - Creates a stream context
- $http_response_header

# file_put_contents

(PHP 5, PHP 7, PHP 8)

file_put_contents — Write data to a file

### Description

file_put_contents(
string `$filename`,
mixed `$data`,
int `$flags` = 0,
?resource `$context` = `null`
): int|false

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If `filename` does not exist, the file is created. Otherwise, the existing file is overwritten, unless the `FILE_APPEND` flag is set.

### Parameters

`filename`

  Path to the file where to write the data.

`data`

  The data to write. Can be either a string, an array or a stream resource.

  If `data` is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

  You can also specify the `data` parameter as a single dimension array. This is equivalent to `file_put_contents($filename, implode('', $array))`.

`flags`

  The value of `flags` can be any combination of the following flags, joined with the binary OR (`|`) operator.

  Available flags
  Flag | Description
  --- | ---
  `FILE_USE_INCLUDE_PATH` | Search for `filename` in the include directory. See include_path for more information.
  `FILE_APPEND` | If file `filename` already exists, append the data to the file instead of overwriting it.
  `LOCK_EX` | Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".

`context`

  A valid context resource created with stream_context_create().

### Return Values

This function returns the number of bytes that were written to the file, or `false` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Examples

Example #1 Simple usage example

`<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>`

Example #2 Using flags

`<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>`

### Notes

> Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### See Also

- fopen() - Opens file or URL
- fwrite() - Binary-safe file write
- file_get_contents() - Reads entire file into a string
- stream_context_create() - Creates a stream context

# fileatime

(PHP 4, PHP 5, PHP 7, PHP 8)

fileatime — Gets last access time of file

### Description

fileatime(string `$filename`): int|false

Gets the last access time of the given file.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the time the file was last accessed, or `false` on failure. The time is returned as a Unix timestamp.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 fileatime() example

`<?php
// outputs e.g. somefile.txt was last accessed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}
?>`

### Notes

> Note:

> The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories.

> Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

> Note:

> Note that time resolution may differ from one file system to another.

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- filemtime() - Gets file modification time
- fileinode() - Gets file inode
- date() - Format a Unix timestamp

# filectime

(PHP 4, PHP 5, PHP 7, PHP 8)

filectime — Gets inode change time of file

### Description

filectime(string `$filename`): int|false

Gets the inode change time of a file.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the time the file was last changed, or `false` on failure. The time is returned as a Unix timestamp.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 A filectime() example

`<?php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}
?>`

### Notes

> Note:

> Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

> Note:

> Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

> Note:

> Note that time resolution may differ from one file system to another.

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- filemtime() - Gets file modification time

# filegroup

(PHP 4, PHP 5, PHP 7, PHP 8)

filegroup — Gets file group

### Description

filegroup(string `$filename`): int|false

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the group ID of the file, or `false` if an error occurs. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, `false` is returned.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Finding the group of a file

`<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- fileowner() - Gets file owner
- posix_getgrgid() - Return info about a group by group id

# fileinode

(PHP 4, PHP 5, PHP 7, PHP 8)

fileinode — Gets file inode

### Description

fileinode(string `$filename`): int|false

Gets the file inode.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the inode number of the file, or `false` on failure.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Comparing the inode of a file with the current file

`<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
echo 'You are checking the current file.';
}
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- getmyinode() - Gets the inode of the current script
- stat() - Gives information about a file

# filemtime

(PHP 4, PHP 5, PHP 7, PHP 8)

filemtime — Gets file modification time

### Description

filemtime(string `$filename`): int|false

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the time the file was last modified, or `false` on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 filemtime() example

`<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>`

### Notes

> Note:

> Note that time resolution may differ from one file system to another.

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- filectime() - Gets inode change time of file
- stat() - Gives information about a file
- touch() - Sets access and modification time of file
- getlastmod() - Gets time of last page modification

# fileowner

(PHP 4, PHP 5, PHP 7, PHP 8)

fileowner — Gets file owner

### Description

fileowner(string `$filename`): int|false

Gets the file owner.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the user ID of the owner of the file, or `false` on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Finding the owner of a file

`<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- filegroup() - Gets file group
- stat() - Gives information about a file
- posix_getpwuid() - Return info about a user by user id

# fileperms

(PHP 4, PHP 5, PHP 7, PHP 8)

fileperms — Gets file permissions

### Description

fileperms(string `$filename`): int|false

Gets permissions for the given file.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod(), however on most platforms the return value will also include information on the type of file given as `filename`. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and macOS.

For local files, the specific return value is that of the `st_mode` member of the structure returned by the C library's stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required.

Returns `false` on failure.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Display permissions as an octal value

`<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>`

The above example will output:

    1777
    0644

Example #2 Display full permissions

`<?php
$perms = fileperms('/etc/passwd');
switch ($perms & 0xF000) {
case 0xC000: // socket
$info = 's';
break;
case 0xA000: // symbolic link
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // block special
$info = 'b';
break;
case 0x4000: // directory
$info = 'd';
break;
case 0x2000: // character special
$info = 'c';
break;
case 0x1000: // FIFO pipe
$info = 'p';
break;
default: // unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));
echo $info;
?>`

The above example will output:

    -rw-r--r--

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- chmod() - Changes file mode
- is_readable() - Tells whether a file exists and is readable
- stat() - Gives information about a file

# filesize

(PHP 4, PHP 5, PHP 7, PHP 8)

filesize — Gets file size

### Description

filesize(string `$filename`): int|false

Gets the size for the given file.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns the size of the file in bytes, or `false` (and generates an error of level `E_WARNING`) in case of an error.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 filesize() example

`<?php
// outputs e.g. somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- file_exists() - Checks whether a file or directory exists

# filetype

(PHP 4, PHP 5, PHP 7, PHP 8)

filetype — Gets file type

### Description

filetype(string `$filename`): string|false

Returns the type of the given file.

### Parameters

`filename`

  Path to the file.

### Return Values

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

Returns `false` if an error occurs. filetype() will also produce an `E_NOTICE` message if the stat call fails or if the file type is unknown.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 filetype() example

`<?php
echo filetype('/etc/passwd');
echo "\n";
echo filetype('/etc/');
?>`

The above example will output:

    file
    dir

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- is_dir() - Tells whether the filename is a directory
- is_file() - Tells whether the filename is a regular file
- is_link() - Tells whether the filename is a symbolic link
- file_exists() - Checks whether a file or directory exists
- mime_content_type() - Detect MIME Content-type for a file
- pathinfo() - Returns information about a file path
- stat() - Gives information about a file

# flock

(PHP 4, PHP 5, PHP 7, PHP 8)

flock — Portable advisory file locking

### Description

flock(resource `$stream`, int `$operation`, int `&$would_block` = `null`): bool

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

The lock is released also by fclose(), or when `stream` is garbage collected.

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled with the `LOCK_NB` option documented below.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

`operation`

  `operation` is one of the following:

  - `LOCK_SH` to acquire a shared lock (reader).
  - `LOCK_EX` to acquire an exclusive lock (writer).
  - `LOCK_UN` to release a lock (shared or exclusive).

  It is also possible to add `LOCK_NB` as a bitmask to one of the above operations, if flock() should not block during the locking attempt.

`would_block`

  The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 flock() example

`<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>`

Example #2 flock() using the `LOCK_NB` option

`<?php
$fp = fopen('/tmp/lock.txt', 'r+');
/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}
/* ... */
fclose($fp);
?>`

### Notes

> Note:

> flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.

> Note:

> Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

> Note:

> May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.

Warning

Assigning another value to `stream` argument in subsequent code will release the lock.

Warning

On some operating systems flock() is implemented at the process level. When using a multithreaded server API you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like `FAT` and its derivates and will therefore always return `false` under these environments.

> Note:

> On Windows, if the locking process opens the file a second time, it cannot access the file through this second handle until it unlocks the file.

# fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

fnmatch — Match filename against a pattern

### Description

fnmatch(string `$pattern`, string `$filename`, int `$flags` = 0): bool

fnmatch() checks if the passed `filename` would match the given shell wildcard `pattern`.

### Parameters

`pattern`

  The `pattern` to match against. Usually, the `pattern` will contain wildcards like `'?'` and `'*'`.

  Wildcards to be used in `pattern` parameter
  Wildcard | Description
  --- | ---
  `?` | Question mark will match any single character. For example, pattern `"file?.txt"` will match `"file1.txt"` and `"fileA.txt"`, but will not match `"file10.txt"`.
  `*` | Asterisk will match zero or more characters. For example, pattern `"foo*.xml"` will match `"foo.xml"` and `"foobar.xml"`.
  `[ ]` | Square brackets are used to create ranges of ASCII codepoints or sets of characters. For example, pattern `"index.php[45]"` will match `"index.php4"` and `"index.php5"`, but will not match `"index.phpt"`. Well known ranges are `[0-9]`, `[a-z]`, and `[A-Z]`. Multiple sets and ranges can be used at the same time, for example `[0-9a-zABC]`.
  `!` | Exclamation mark is used to negate characters within square brackets. For example, `"[!A-Z]*.html"` will match `"demo.html"`, but will not match `"Demo.html"`.
  `\` | Backslash is used to escape special characters. For example, `"Name\?"` will match `"Name?"`, but will not match `"Names"`.

`filename`

  The tested string. This function is especially useful for filenames, but may also be used on regular strings.

  The average user may be used to shell patterns or at least in their simplest form to `'?'` and `'*'` wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users.

`flags`

  The value of `flags` can be any combination of the following flags, joined with the binary OR (|) operator.

  A list of possible flags for fnmatch()
  `Flag` | Description
  --- | ---
  `FNM_NOESCAPE` | Disable backslash escaping.
  `FNM_PATHNAME` | Slash in string only matches slash in the given pattern.
  `FNM_PERIOD` | Leading period in string must be exactly matched by period in the given pattern.
  `FNM_CASEFOLD` | Caseless match. Part of the GNU extension.

### Return Values

Returns `true` if there is a match, `false` otherwise.

### Examples

Example #1 Checking a color name against a shell wildcard pattern

`<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>`

### Notes

Warning

For now, this function is not available on non-POSIX compliant systems except Windows.

### See Also

- glob() - Find pathnames matching a pattern
- preg_match() - Perform a regular expression match
- sscanf() - Parses input from a string according to a format
- printf() - Output a formatted string
- sprintf() - Return a formatted string

# fopen

(PHP 4, PHP 5, PHP 7, PHP 8)

fopen — Opens file or URL

### Description

fopen(
string `$filename`,
string `$mode`,
bool `$use_include_path` = `false`,
?resource `$context` = `null`
): resource|false

fopen() binds a named resource, specified by `filename`, to a stream.

### Parameters

`filename`

  If `filename` is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though `filename` specifies a regular file.

  If PHP has decided that `filename` specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

  If PHP has decided that `filename` specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen() call will fail.

  > Note:

  > The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as `wrappers`) support `context` and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value `user_agent` used by the `http` wrapper).

  On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

  `<?php
  $handle = fopen("c:\\folder\\resource.txt", "r");
  ?>`
`mode`

  The `mode` parameter specifies the type of access you require to the stream. It may be any of the following:

  A list of possible modes for fopen() using `mode`
  `mode` | Description
  --- | ---
  `'r'` | Open for reading only; place the file pointer at the beginning of the file.
  `'r+'` | Open for reading and writing; place the file pointer at the beginning of the file.
  `'w'` | Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  `'w+'` | Open for reading and writing; otherwise it has the same behavior as `'w'`.
  `'a'` | Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
  `'a+'` | Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
  `'x'` | Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning `false` and generating an error of level `E_WARNING`. If the file does not exist, attempt to create it. This is equivalent to specifying `O_EXCL|O_CREAT` flags for the underlying `open(2)` system call.
  `'x+'` | Create and open for reading and writing; otherwise it has the same behavior as `'x'`.
  `'c'` | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to `'w'`), nor the call to this function fails (as is the case with `'x'`). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using `'w'` could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
  `'c+'` | Open the file for reading and writing; otherwise it has the same behavior as `'c'`.
  `'e'` | Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conformant systems.
  `'n'` | Set non-blocking flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conformant systems.

  > Note:

  > Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use `\n` as the line ending character, Windows based systems use `\r\n` as the line ending characters and Macintosh based systems (Mac OS Classic) used `\r` as the line ending character.

  > If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".

  > Windows offers a text-mode translation flag (`'t'`) which will transparently translate `\n` to `\r\n` when working with the file. In contrast, you can also use `'b'` to force binary mode, which will not translate your data. To use these flags, specify either `'b'` or `'t'` as the last character of the `mode` parameter.

  > The default translation mode is `'b'`. You can use the `'t'` mode if you are working with plain-text files and you use `\n` to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the `'b'` in all other cases.

  > If you specify the 't' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with `\r\n` characters.

  > Note:

  > For portability, it is also strongly recommended that you re-write code that uses or relies upon the `'t'` mode so that it uses the correct line endings and `'b'` mode instead.

  > Note: The `mode` is ignored for php://output, php://input, php://stdin, php://stdout, php://stderr and php://fd stream wrappers.

`use_include_path`

  The optional third `use_include_path` parameter can be set to `true` if you want to search for the file in the include_path, too.

`context`

  A context stream resource.

### Return Values

Returns a file pointer resource on success, or `false` on failure

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Changelog

Version | Description
--- | ---
7.0.16, 7.1.2 | The `'e'` option was added.

### Examples

Example #1 fopen() examples

`<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>`

### Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a `close_notify` indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the `https://` wrapper and will suppress the warning. When using fsockopen() to create an `ssl://` socket, the developer is responsible for detecting and suppressing this warning.

> Note:

> If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

> Note:

> This function may also succeed when `filename` is a directory. If you are unsure whether `filename` is a file or a directory, you may need to use the is_dir() function before calling fopen().

### See Also

- Supported Protocols and Wrappers
- fclose() - Closes an open file pointer
- fgets() - Gets line from file pointer
- fread() - Binary-safe file read
- fwrite() - Binary-safe file write
- fsockopen() - Open Internet or Unix domain socket connection
- file() - Reads entire file into an array
- file_exists() - Checks whether a file or directory exists
- is_readable() - Tells whether a file exists and is readable
- stream_set_timeout() - Set timeout period on a stream
- popen() - Opens process file pointer
- stream_context_create() - Creates a stream context
- umask() - Changes the current umask
- SplFileObject

# fpassthru

(PHP 4, PHP 5, PHP 7, PHP 8)

fpassthru — Output all remaining data on a file pointer

### Description

fpassthru(resource `$stream`): int

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.

### Parameters

`stream`

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

### Return Values

Returns the number of characters read from `stream` and passed through to the output.

### Examples

Example #1 Using fpassthru() with binary files

`<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>`

### Notes

> Note:

> When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a `b` to the mode used in the call to fopen().

> You are encouraged to use the `b` flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.

### See Also

- readfile() - Outputs a file
- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fsockopen() - Open Internet or Unix domain socket connection

# fputcsv

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

fputcsv — Format line as CSV and write to file pointer

### Description

fputcsv(
resource `$stream`,
array `$fields`,
string `$separator` = ",",
string `$enclosure` = "\"",
string `$escape` = "\\",
string `$eol` = "\n"
): int|false

fputcsv() formats a line (passed as a `fields` array) as CSV and writes it (terminated by a `eol`) to the specified `stream`.

### Parameters

`stream`

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

`fields`

  An array of strings.

`separator`

  The `separator` parameter sets the field separator. It must be a single byte character.

`enclosure`

  The `enclosure` parameter sets the field enclosure character. It must be a single byte character.

`escape`

  The `escape` parameter sets the escape character. It must be a single byte character or the empty string. The empty string (`""`) disables the proprietary escape mechanism.

  Warning

  In the input stream, the `enclosure` character can always be escaped by doubling it inside a quoted string, resulting in a single `enclosure` character in the parsed result. The `escape` character works differently: If a sequence of `escape` and `enclosure` characters appear in the input, both characters will be present in the parsed result. So for the default parameters, a CVS line like `"a""b","c\"d"` will have the fields parsed as `a"b` and `c\"d`, respectively.

  Warning

  As of PHP 8.4.0, depending on the default value of `escape` is deprecated. It needs to be provided explicitly either positionally or by the use of named arguments.

`eol`

  The optional `eol` parameter sets a custom End of Line sequence.

Warning

When `escape` is set to anything other than an empty string (`""`) it can result in CSV that is not compliant with » RFC 4180 or unable to survive a roundtrip through the PHP CSV functions. The default for `escape` is `"\\"` so it is recommended to set it to the empty string explicitly. The default value will change in a future version of PHP, no earlier than PHP 9.0.

> Note:

> If an `enclosure` character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an `escape`.

### Return Values

Returns the length of the written string or `false` on failure.

### Errors/Exceptions

Throws a ValueError if `separator` or `enclosure` is not one byte long.

Throws a ValueError if `escape` is not one byte long or the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Relying on the default value of `escape` is now deprecated.
8.1.0 | The optional `eol` parameter has been added.
7.4.0 | The `escape` parameter now also accepts an empty string to disable the proprietary escape mechanism.

### Examples

Example #1 fputcsv() example

`<?php
$list = [
['aaa', 'bbb', 'ccc', 'dddd'],
['123', '456', '789'],
['"aaa"', '"bbb"']
];
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields, ',', '"', '');
}
fclose($fp);
?>`

The above example will write the following to `file.csv`:

    aaa,bbb,ccc,dddd
    123,456,789
    """aaa""","""bbb"""

### See Also

- fgetcsv() - Gets line from file pointer and parse for CSV fields
- str_getcsv() - Parse a CSV string into an array
- SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields
- SplFileObject::fputcsv() - Write a field array as a CSV line
- SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
- SplFileObject::getCsvControl() - Get the delimiter, enclosure and escape character for CSV

# fputs

(PHP 4, PHP 5, PHP 7, PHP 8)

fputs — Alias of fwrite()

### Description

This function is an alias of: fwrite().

# fread

(PHP 4, PHP 5, PHP 7, PHP 8)

fread — Binary-safe file read

### Description

fread(resource `$stream`, int `$length`): string|false

fread() reads up to `length` bytes from the file pointer referenced by `stream`. Reading stops as soon as one of the following conditions is met:

- `length` bytes have been read
- EOF (end of file) is reached
- a packet becomes available or the socket timeout occurs (for network streams)
- if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

`length`

  Up to `length` number of bytes read.

### Return Values

Returns the read string or `false` on failure.

### Examples

Example #1 A simple fread() example

`<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>`

Example #2 Binary fread() example

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

`<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>`

Example #3 Remote fread() examples

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

`<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>`
`<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
exit("Failed to open stream to URL");
}
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>`

### Notes

> Note:

> If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

> Note:

> Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

### See Also

- fwrite() - Binary-safe file write
- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection
- popen() - Opens process file pointer
- fgets() - Gets line from file pointer
- fgetss() - Gets line from file pointer and strip HTML tags
- fscanf() - Parses input from a file according to a format
- file() - Reads entire file into an array
- fpassthru() - Output all remaining data on a file pointer
- fseek() - Seeks on a file pointer
- ftell() - Returns the current position of the file read/write pointer
- rewind() - Rewind the position of a file pointer
- unpack() - Unpack data from binary string

# fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

fscanf — Parses input from a file according to a format

### Description

fscanf(resource `$stream`, string `$format`, mixed `&...$vars`): array|int|false|null

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with `stream` and interprets the input according to the specified `format`.

Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab (`\t`) in the format string can match a single space character in the input stream.

Each call to fscanf() reads one line from the file.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

`format`

  The interpreted format for `string`, which is described in the documentation for sprintf() with following differences:

  - Function is not locale-aware.
  - `F`, `g`, `G` and `b` are not supported.
  - `D` stands for decimal number.
  - `i` stands for integer with base detection.
  - `n` stands for number of characters processed so far.
  - `s` stops reading at any whitespace character.
  - `*` instead of `argnum$` suppresses the assignment of this conversion specification.
`vars`

  The optional assigned values.

### Return Values

If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

If there are more substrings expected in the `format` than there are available within `string`, `null` will be returned. On other errors, `false` will be returned.

### Examples

Example #1 fscanf() Example

`<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list ($name, $profession, $countrycode) = $userinfo;
//... do something with the values
}
fclose($handle);
?>`

Example #2 Contents of users.txt

    javier  argonaut        pe
    hiroshi sculptor        jp
    robert  slacker us
    luigi   florist it

### See Also

- fread() - Binary-safe file read
- fgets() - Gets line from file pointer
- fgetss() - Gets line from file pointer and strip HTML tags
- sscanf() - Parses input from a string according to a format
- printf() - Output a formatted string
- sprintf() - Return a formatted string

# fseek

(PHP 4, PHP 5, PHP 7, PHP 8)

fseek — Seeks on a file pointer

### Description

fseek(resource `$stream`, int `$offset`, int `$whence` = `SEEK_SET`): int

Sets the file position indicator for the file referenced by `stream`. The new position, measured in bytes from the beginning of the file, is obtained by adding `offset` to the position specified by `whence`.

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

`offset`

  The offset.

  To move to a position before the end-of-file, a negative value in the `offset` must be passed and the `whence` parameter must be set to `SEEK_END`.

`whence`

  `whence` values are:

  - `SEEK_SET` - Set position equal to `offset` bytes from the start of the file.
  - `SEEK_CUR` - Set position to current location plus `offset` bytes.
  - `SEEK_END` - Set position to end-of-file plus `offset` bytes.

### Return Values

Upon success, returns `0`; otherwise, returns `-1`.

Warning

This function was created to imitate the C language function of the same name. Please pay attention to the return values as they differ from what one would expect in PHP.

### Examples

Example #1 fseek() example

`<?php
$fp = fopen('somefile.txt', 'r');
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);
?>`

### Notes

> Note:

> If you have opened the file in append (`a` or `a+`) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

> Note:

> Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

### See Also

- ftell() - Returns the current position of the file read/write pointer
- rewind() - Rewind the position of a file pointer

# fstat

(PHP 4, PHP 5, PHP 7, PHP 8)

fstat — Gets information about a file using an open file pointer

### Description

fstat(resource `$stream`): array|false

Gathers the statistics of the file opened by the file pointer `stream`. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

### Return Values

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page. Returns `false` on failure.

### Examples

Example #1 fstat() example

`<?php
// open a file
$fp = fopen("/etc/passwd", "r");
// gather statistics
$fstat = fstat($fp);
// close the file
fclose($fp);
// print only the associative part
print_r(array_slice($fstat, 13));
?>`

The above example will output something similar to:

    Array
    (
        [dev] => 771
        [ino] => 488704
        [mode] => 33188
        [nlink] => 1
        [uid] => 0
        [gid] => 0
        [rdev] => 0
        [size] => 1114
        [atime] => 1061067181
        [mtime] => 1056136526
        [ctime] => 1056136526
        [blksize] => 4096
        [blocks] => 8
    )

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

# fsync

(PHP 8 >= 8.1.0)

fsync — Synchronizes changes to the file (including meta-data)

### Description

fsync(resource `$stream`): bool

This function synchronizes changes to the file, including its meta-data. This is similar to fflush(), but it also instructs the operating system to write to the storage media.

### Parameters

`stream`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 fsync() example

`<?php
$file = 'test.txt';
$stream = fopen($file, 'w');
fwrite($stream, 'test data');
fwrite($stream, "\r\n");
fwrite($stream, 'additional data');
fsync($stream);
fclose($stream);
?>`

### See Also

- fdatasync() - Synchronizes data (but not meta-data) to the file
- fflush() - Flushes the output to a file

# ftell

(PHP 4, PHP 5, PHP 7, PHP 8)

ftell — Returns the current position of the file read/write pointer

### Description

ftell(resource `$stream`): int|false

Returns the position of the file pointer referenced by `stream`.

### Parameters

`stream`

  The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

### Return Values

Returns the position of the file pointer referenced by `stream` as an integer; i.e., its offset into the file stream.

If an error occurs, returns `false`.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Examples

Example #1 ftell() example

`<?php
// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);
// where are we ?
echo ftell($fp); // 11
fclose($fp);
?>`

### See Also

- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fseek() - Seeks on a file pointer
- rewind() - Rewind the position of a file pointer

# ftruncate

(PHP 4, PHP 5, PHP 7, PHP 8)

ftruncate — Truncates a file to a given length

### Description

ftruncate(resource `$stream`, int `$size`): bool

Takes the filepointer, `stream`, and truncates the file to length, `size`.

### Parameters

`stream`

  The file pointer.

  > Note:

  > The `stream` must be open for writing.

`size`

  The size to truncate to.

  > Note:

  > If `size` is larger than the file then the file is extended with null bytes.

  > If `size` is smaller than the file then the file is truncated to that size.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 File truncation example

`<?php
$filename = 'lorem_ipsum.txt';
$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>`

### Notes

> Note:

> The file pointer is not changed.

### See Also

- fopen() - Opens file or URL
- fseek() - Seeks on a file pointer

# fwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

fwrite — Binary-safe file write

### Description

fwrite(resource `$stream`, string `$data`, ?int `$length` = `null`): int|false

fwrite() writes the contents of `data` to the file stream pointed to by `stream`.

### Parameters

`stream`

  A file system pointer resource that is typically created using fopen().

`data`

  The string that is to be written.

`length`

  If `length` is an int, writing will stop after `length` bytes have been written or the end of `data` is reached, whichever comes first.

### Return Values

fwrite() returns the number of bytes written, or `false` on failure.

### Errors/Exceptions

fwrite() raises `E_WARNING` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` is nullable now.

### Examples

Example #1 A simple fwrite() example

`<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$fp = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($fp, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($fp);
} else {
echo "The file $filename is not writable";
}
?>`

### Notes

> Note:

> Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

> `<?php
> function fwrite_stream($fp, $string) {
> for ($written = 0; $written < strlen($string); $written += $fwrite) {
> $fwrite = fwrite($fp, substr($string, $written));
> if ($fwrite === false) {
> return $written;
> }
> }
> return $written;
> }
> ?>`

> Note:

> On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

> Note:

> If `stream` was fopen()ed in append mode, fwrite()s are atomic (unless the size of `data` exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

> Note:

> If writing twice to the file pointer, then the data will be appended to the end of the file content:

> `<?php
> $fp = fopen('data.txt', 'w');
> fwrite($fp, '1');
> fwrite($fp, '23');
> fclose($fp);
> // the content of 'data.txt' is now 123 and not 23!
> ?>`

### See Also

- fread() - Binary-safe file read
- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection
- popen() - Opens process file pointer
- file_get_contents() - Reads entire file into a string
- pack() - Pack data into binary string

# glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

glob — Find pathnames matching a pattern

### Description

glob(string `$pattern`, int `$flags` = 0): array|false

The glob() function searches for all the pathnames matching `pattern` according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

The behavior on Unix systems and macOS is determined by the system's implementation of glob(). On Windows, an implementation that conforms to the POSIX 1003.2 definition for glob() is used, and it includes an extension to handle the `[!...]` convention for negating a range.

### Parameters

`pattern`

  The pattern. No tilde expansion or parameter substitution is done.

  Special characters:

  - `*` - Matches zero or more characters.
  - `?` - Matches exactly one character (any character).
  - `[...]` - Matches one character from a group of characters. If the first character is `!`, matches any character not in the group.
  - `{a,b,c}` - Matches one string from a group of strings delimited by a comma when the `GLOB_BRACE` flag is used.
  - `\` - Escapes the following character, except when the `GLOB_NOESCAPE` flag is used.
`flags`

  Any of the `GLOB_*` constants.

### Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or `false` on error. Unless `GLOB_NOSORT` was used, the names will be sorted alphanumerically.

### Examples

Example #1 Convenient way how glob() can replace opendir() and friends.

`<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>`

The above example will output something similar to:

    funclist.txt size 44686
    funcsummary.txt size 267625
    quickref.txt size 137820

Example #2 Example with a more complex pattern

`<?php
foreach (glob("path/*/*.{txt,md}", \GLOB_BRACE) as $filename) {
echo "$filename\n";
}
?>`

The above example will output something similar to:

    path/docs/mailinglist-rules.md
    path/docs/README.md
    path/docs/release-process.md
    path/pear/install-pear.txt
    path/Zend/README.md

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: This function isn't available on some systems (e.g. old Sun OS).

### See Also

- opendir() - Open directory handle
- readdir() - Read entry from directory handle
- closedir() - Close directory handle
- fnmatch() - Match filename against a pattern

# is_dir

(PHP 4, PHP 5, PHP 7, PHP 8)

is_dir — Tells whether the filename is a directory

### Description

is_dir(string `$filename`): bool

Tells whether the given filename is a directory.

### Parameters

`filename`

  Path to the file. If `filename` is a relative filename, it will be checked relative to the current working directory. If `filename` is a symbolic or hard link then the link will be resolved and checked. If you have enabled open_basedir further restrictions may apply.

### Return Values

Returns `true` if the filename exists and is a directory, `false` otherwise.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 is_dir() example

`<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));
var_dump(is_dir('..')); //one dir up
?>`

The above example will output:

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

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- chdir() - Change directory
- dir() - Return an instance of the Directory class
- opendir() - Open directory handle
- is_file() - Tells whether the filename is a regular file
- is_link() - Tells whether the filename is a symbolic link

# is_executable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_executable — Tells whether the filename is executable

### Description

is_executable(string `$filename`): bool

Tells whether the filename is executable.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns `true` if the filename exists and is executable, or `false` on error. On POSIX systems, a file is executable if the executable bit of the file permissions is set. For Windows, see the note below.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 is_executable() example

`<?php
$file = '/home/vincent/somefile.sh';
if (is_executable($file)) {
echo $file.' is executable';
} else {
echo $file.' is not executable';
}
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

> Note: On Windows, a file is considered executable, if it is a properly executable file as reported by the Win API `GetBinaryType()`; for BC reasons, files with a .bat or .cmd extension are also considered executable. Prior to PHP 7.4.0, any non-empty file with a .exe or .com extension was considered executable. Note that PATHEXT is irrelevant for is_executable().

### See Also

- is_file() - Tells whether the filename is a regular file
- is_link() - Tells whether the filename is a symbolic link

# is_file

(PHP 4, PHP 5, PHP 7, PHP 8)

is_file — Tells whether the filename is a regular file

### Description

is_file(string `$filename`): bool

Tells whether the given file is a regular file. If `filename` is a symbolic link, it will resolve the symlink and will give information about the referred file.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns `true` if the filename exists and is a regular file, `false` otherwise.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 is_file() example

`<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>`

The above example will output:

    bool(true)
    bool(false)

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- is_dir() - Tells whether the filename is a directory
- is_link() - Tells whether the filename is a symbolic link
- SplFileInfo

# is_link

(PHP 4, PHP 5, PHP 7, PHP 8)

is_link — Tells whether the filename is a symbolic link

### Description

is_link(string `$filename`): bool

Tells whether the given file is a symbolic link.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns `true` if the filename exists and is a symbolic link, `false` otherwise.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Create and confirm if a file is a symbolic link

`<?php
$link = 'uploads';
if (is_link($link)) {
echo readlink($link);
} else {
symlink('uploads.php', $link);
}
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- is_dir() - Tells whether the filename is a directory
- is_file() - Tells whether the filename is a regular file
- readlink() - Returns the target of a symbolic link
- symlink() - Creates a symbolic link

# is_readable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_readable — Tells whether a file exists and is readable

### Description

is_readable(string `$filename`): bool

Tells whether a file exists and is readable.

### Parameters

`filename`

  Path to the file.

### Return Values

Returns `true` if the file or directory specified by `filename` exists and is readable, `false` otherwise.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 is_readable() example

`<?php
$filename = 'test.txt';
if (is_readable($filename)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}
?>`

### Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody').

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

> Note:

> The check is done using the real UID/GID instead of the effective one.

This function may return `true` for directories. Use is_dir() to distinguish file and directory.

### See Also

- is_writable() - Tells whether the filename is writable
- file_exists() - Checks whether a file or directory exists
- fgets() - Gets line from file pointer

# is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

is_uploaded_file — Tells whether the file was uploaded via HTTP POST

### Description

is_uploaded_file(string `$filename`): bool

Returns `true` if the file named by `filename` was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.

### Parameters

`filename`

  The filename being checked.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 is_uploaded_file() example

`<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['userfile']['tmp_name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}
?>`

### See Also

- move_uploaded_file() - Moves an uploaded file to a new location
- $_FILES
- See Handling file uploads for a simple usage example.

# is_writable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_writable — Tells whether the filename is writable

### Description

is_writable(string `$filename`): bool

Returns `true` if the `filename` exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody').

### Parameters

`filename`

  The filename being checked.

### Return Values

Returns `true` if the `filename` exists and is writable.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 is_writable() example

`<?php
$filename = 'test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
?>`

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- is_readable() - Tells whether a file exists and is readable
- file_exists() - Checks whether a file or directory exists
- fwrite() - Binary-safe file write

# is_writeable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_writeable — Alias of is_writable()

### Description

This function is an alias of: is_writable().

# lchgrp

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

lchgrp — Changes group ownership of symlink

### Description

lchgrp(string `$filename`, string|int `$group`): bool

Attempts to change the group of the symlink `filename` to `group`.

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

### Parameters

`filename`

  Path to the symlink.

`group`

  The group specified by name or number.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Changing the group of a symbolic link

`<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);
lchgrp($link, 8);
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: This function is not implemented on Windows platforms.

### See Also

- chgrp() - Changes file group
- lchown() - Changes user ownership of symlink
- chown() - Changes file owner
- chmod() - Changes file mode

# lchown

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

lchown — Changes user ownership of symlink

### Description

lchown(string `$filename`, string|int `$user`): bool

Attempts to change the owner of the symlink `filename` to user `user`.

Only the superuser may change the owner of a symlink.

### Parameters

`filename`

  Path to the file.

`user`

  User name or number.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Changing the owner of a symbolic link

`<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);
lchown($link, 8);
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: This function is not implemented on Windows platforms.

### See Also

- chown() - Changes file owner
- lchgrp() - Changes group ownership of symlink
- chgrp() - Changes file group
- chmod() - Changes file mode

# link

(PHP 4, PHP 5, PHP 7, PHP 8)

link — Create a hard link

### Description

link(string `$target`, string `$link`): bool

link() creates a hard link.

### Parameters

`target`

  Target of the link.

`link`

  The link name.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

The function fails, and issues `E_WARNING`, if `link` already exists, or if `target` does not exist.

### Examples

Example #1 Creating a simple hard link

`<?php
$target = 'source.ext'; // This is the file that already exists
$link = 'newfile.ext'; // This the filename that you want to link it to
link($target, $link);
?>`

### Notes

> Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

> Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.

### See Also

- symlink() - Creates a symbolic link
- readlink() - Returns the target of a symbolic link
- linkinfo() - Gets information about a link
- unlink() - Deletes a file

# linkinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

linkinfo — Gets information about a link

### Description

linkinfo(string `$path`): int|false

Gets information about a link.

This function is used to verify if a link (pointed to by `path`) really exists (using the same method as the S_ISLNK macro defined in stat.h).

### Parameters

`path`

  Path to the link.

### Return Values

linkinfo() returns the `st_dev` field of the Unix C stat structure returned by the `lstat` system call. Returns a non-negative integer on success, -1 in case the link was not found, or `false` if an open.base_dir violation occurs.

### Examples

Example #1 linkinfo() example

`<?php
echo linkinfo('/vmlinuz'); // 835
?>`

### See Also

- symlink() - Creates a symbolic link
- link() - Create a hard link
- readlink() - Returns the target of a symbolic link

# lstat

(PHP 4, PHP 5, PHP 7, PHP 8)

lstat — Gives information about a file or symbolic link

### Description

lstat(string `$filename`): array|false

Gathers the statistics of the file or symbolic link named by `filename`.

### Parameters

`filename`

  Path to a file or a symbolic link.

### Return Values

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the `filename` parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

On failure, `false` is returned.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Comparison of stat() and lstat()

`<?php
symlink('uploads.php', 'uploads');
// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>`

The above example will output something similar to:

Information that differs between the two files.

    Array
    (
        [ino] => 97236376
        [mode] => 33188
        [size] => 34
        [atime] => 1223580003
        [mtime] => 1223581848
        [ctime] => 1223581848
        [blocks] => 8
    )

### Notes

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- stat() - Gives information about a file

# mkdir

(PHP 4, PHP 5, PHP 7, PHP 8)

mkdir — Makes directory

### Description

mkdir(
string `$directory`,
int `$permissions` = 0777,
bool `$recursive` = `false`,
?resource `$context` = `null`
): bool

Attempts to create the directory specified by `directory`.

### Parameters

`directory`

  The directory path.

  Tip

  A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

`permissions`

  The permissions are 0777 by default, which means the widest possible access. For more information on permissions, read the details on the chmod() page.

  > Note:

  > `permissions` is ignored on Windows.

  Note that you probably want to specify the `permissions` as an octal number, which means it should have a leading zero. The `permissions` is also modified by the current umask, which you can change using umask().

`recursive`

  If `true`, then any parent directories to the `directory` specified will also be created, with the same permissions.

`context`

  A context stream resource.

### Return Values

Returns `true` on success or `false` on failure.

> Note:

> If the directory to be created already exists, that is considered an error and `false` will still be returned. Use is_dir() or file_exists() to check if the directory already exists before trying to create it.

### Errors/Exceptions

Emits an `E_WARNING` level error if the directory already exists.

Emits an `E_WARNING` level error if the relevant permissions prevent creating the directory.

### Examples

Example #1 mkdir() example

`<?php
mkdir("/path/to/my/dir", 0700);
?>`

Example #2 mkdir() using the `recursive` parameter

`<?php
// Desired directory structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create directories...');
}
// ...
?>`

### See Also

- is_dir() - Tells whether the filename is a directory
- rmdir() - Removes directory
- umask() - Changes the current umask

# move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

move_uploaded_file — Moves an uploaded file to a new location

### Description

move_uploaded_file(string `$from`, string `$to`): bool

This function checks to ensure that the file designated by `from` is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by `to`.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

### Parameters

`from`

  The filename of the uploaded file.

`to`

  The destination of the moved file.

### Return Values

Returns `true` on success.

If `from` is not a valid upload file, then no action will occur, and move_uploaded_file() will return `false`.

If `from` is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return `false`. Additionally, a warning will be issued.

### Examples

Example #1 Uploading multiple files

`<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>`

### Notes

> Note:

> move_uploaded_file() is open_basedir aware. However, restrictions are placed only on the `to` path as to allow the moving of uploaded files in which `from` may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Warning

If the destination file already exists, it will be overwritten.

### See Also

- is_uploaded_file() - Tells whether the file was uploaded via HTTP POST
- rename() - Renames a file or directory
- See Handling file uploads for a simple usage example

# parse_ini_file

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_ini_file — Parse a configuration file

### Description

parse_ini_file(string `$filename`, bool `$process_sections` = `false`, int `$scanner_mode` = `INI_SCANNER_NORMAL`): array|false

parse_ini_file() loads in the ini file specified in `filename`, and returns the settings in it in an associative array.

The structure of the ini file is the same as the php.ini's.

Warning

This function must not be used with untrusted inputs, unless `scanner_mode` is `INI_SCANNER_RAW` since the parsed output might contain the values of sensitive constants, such as constants holding a database password.

### Parameters

`filename`

  The filename of the ini file being parsed. If a relative path is used, it is evaluated relative to the current working directory, then the include_path.

`process_sections`

  By setting the `process_sections` parameter to `true`, you get a multidimensional array, with the section names and settings included. The default for `process_sections` is `false`

`scanner_mode`

  Can either be `INI_SCANNER_NORMAL` (default) or `INI_SCANNER_RAW`. If `INI_SCANNER_RAW` is supplied, then option values will not be parsed.

  As of PHP 5.6.1 can also be specified as `INI_SCANNER_TYPED`. In this mode boolean, null and integer types are preserved when possible. String values `"true"`, `"on"` and `"yes"` are converted to `true`. `"false"`, `"off"`, `"no"` and `"none"` are considered `false`. `"null"` is converted to `null` in typed mode. Also, all numeric strings are converted to integer type if it is possible.

### Return Values

The settings are returned as an associative array on success, and `false` on failure.

### Examples

Example #1 Contents of sample.ini

    ; This is a sample configuration file
    ; Comments start with ';', as in php.ini

    [first_section]
    one = 1
    five = 5
    animal = BIRD

    [second_section]
    path = "/usr/local/bin"
    URL = "http://www.example.com/~username"

    [third_section]
    phpversion[] = "5.0"
    phpversion[] = "5.1"
    phpversion[] = "5.2"
    phpversion[] = "5.3"

    urls[svn] = "http://svn.php.net"
    urls[git] = "http://git.php.net"

Example #2 parse_ini_file() example

Constants (but not "magic constants" like `__FILE__`) may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated, and the value must be just the constant. For example:

`<?php
define('BIRD', 'Dodo bird');
// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);
// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
?>`

The above example will output something similar to:

    Array
    (
        [one] => 1
        [five] => 5
        [animal] => Dodo bird
        [path] => /usr/local/bin
        [URL] => http://www.example.com/~username
        [phpversion] => Array
            (
                [0] => 5.0
                [1] => 5.1
                [2] => 5.2
                [3] => 5.3
            )

        [urls] => Array
            (
                [svn] => http://svn.php.net
                [git] => http://git.php.net
            )

    )
    Array
    (
        [first_section] => Array
            (
                [one] => 1
                [five] => 5
                [animal] => Dodo bird
            )

        [second_section] => Array
            (
                [path] => /usr/local/bin
                [URL] => http://www.example.com/~username
            )

        [third_section] => Array
            (
                [phpversion] => Array
                    (
                        [0] => 5.0
                        [1] => 5.1
                        [2] => 5.2
                        [3] => 5.3
                    )

                [urls] => Array
                    (
                        [svn] => http://svn.php.net
                        [git] => http://git.php.net
                    )

            )

    )

Example #3 parse_ini_file() parsing a php.ini file

`<?php
// A simple function used for comparing the results below
function yesno($expression)
{
return($expression ? 'Yes' : 'No');
}
// Get the path to php.ini using the php_ini_loaded_file() function
$ini_path = php_ini_loaded_file();
// Parse php.ini
$ini = parse_ini_file($ini_path);
// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>`

The above example will output something similar to:

    (parsed) magic_quotes_gpc = Yes
    (loaded) magic_quotes_gpc = Yes

Example #4 Value Interpolation

In addition to evaluating constants, certain characters have special meaning in an ini value. Additionally, environment variables and previously defined configuration options (see get_cfg_var()) may be read using `${}` syntax.

    ; | is used for bitwise OR
    three = 2|3

    ; & is used for bitwise AND
    four = 6&5

    ; ^ is used for bitwise XOR
    five = 3^6

    ; ~ is used for bitwise negate
    negative_two = ~1

    ; () is used for grouping
    seven = (8|7)&(6|5)

    ; Interpolate the PATH environment variable
    path = ${PATH}

    ; Interpolate the configuration option 'memory_limit'
    configured_memory_limit = ${memory_limit}

Example #5 Escaping Characters

Some characters have special meaning in double-quoted strings and must be escaped by the backslash prefix. First of all, these are the double quote `"` as the boundary marker, and the backslash `\` itself (if followed by one of the special characters):

    quoted = "She said \"Exactly my point\"." ; Results in a string with quote marks in it.
    hint = "Use \\\" to escape double quote" ; Results in: Use \" to escape double quote

There is an exception made for Windows-like paths: it's possible to not escape trailing backslash if the quoted string is directly followed by a linebreak:

    save_path = "C:\Temp\"

If one does need to escape double quote followed by linebreak in a multiline value, it's possible to use value concatenation in the following way (there is one double-quoted string directly followed by another one):

    long_text = "Lorem \"ipsum\"""
     dolor" ; Results in: Lorem "ipsum"\n dolor

Another character with special meaning is `$` (the dollar sign). It must be escaped if followed by the open curly brace:

    code = "\${test}"

Escaping characters is not supported in the `INI_SCANNER_RAW` mode (in this mode all characters are processed "as is").

Note that the ini parser doesn't support standard escape sequences (`\n`, `\t`, etc.). If necessary, post-process the result of parse_ini_file() with stripcslashes() function.

### Notes

> Note:

> This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files.

> Note:

> If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

> Note: There are reserved words which must not be used as keys for ini files. These include: `null`, `yes`, `no`, `true`, `false`, `on`, `off`, `none`. Values `null`, `off`, `no` and `false` result in `""`, and values `on`, `yes` and `true` result in `"1"`, unless `INI_SCANNER_TYPED` mode is used. Characters `?{}|&~!()^"` must not be used anywhere in the key and have a special meaning in the value.

> Note:

> Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored.

> Note:

> ini files are generally treated as plain text by web servers and thus served to browsers if requested. That means for security you must either keep your ini files outside of your docroot or reconfigure your web server to not serve them. Failure to do either of those may introduce a security risk.

### See Also

- parse_ini_string() - Parse a configuration string

# parse_ini_string

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

parse_ini_string — Parse a configuration string

### Description

parse_ini_string(string `$ini_string`, bool `$process_sections` = `false`, int `$scanner_mode` = `INI_SCANNER_NORMAL`): array|false

parse_ini_string() returns the settings in string `ini_string` in an associative array.

The structure of the ini string is the same as the php.ini's.

Warning

This function must not be used with untrusted inputs, unless `scanner_mode` is `INI_SCANNER_RAW` since the parsed output might contain the values of sensitive constants, such as constants holding a database password.

### Parameters

`ini_string`

  The contents of the ini file being parsed.

`process_sections`

  By setting the `process_sections` parameter to `true`, you get a multidimensional array, with the section names and settings included. The default for `process_sections` is `false`

`scanner_mode`

  Can either be `INI_SCANNER_NORMAL` (default) or `INI_SCANNER_RAW`. If `INI_SCANNER_RAW` is supplied, then option values will not be parsed.

  As of PHP 5.6.1 can also be specified as `INI_SCANNER_TYPED`. In this mode boolean, null and integer types are preserved when possible. String values `"true"`, `"on"` and `"yes"` are converted to `true`. `"false"`, `"off"`, `"no"` and `"none"` are considered `false`. `"null"` is converted to `null` in typed mode. Also, all numeric strings are converted to integer type if it is possible.

### Return Values

The settings are returned as an associative array on success, and `false` on failure.

### Notes

> Note: There are reserved words which must not be used as keys for ini files. These include: `null`, `yes`, `no`, `true`, `false`, `on`, `off`, `none`. Values `null`, `off`, `no` and `false` result in `""`, and values `on`, `yes` and `true` result in `"1"`, unless `INI_SCANNER_TYPED` mode is used. Characters `?{}|&~![()^"` must not be used anywhere in the key and have a special meaning in the value.

### See Also

- parse_ini_file() - Parse a configuration file

# pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pathinfo — Returns information about a file path

### Description

pathinfo(string `$path`, int `$flags` = `PATHINFO_ALL`): array|string

pathinfo() returns information about `path`: either an associative array or a string, depending on `flags`.

> Note:

> For information on retrieving the current path info, read the section on predefined reserved variables.

> Note:

> pathinfo() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "`..`".

> Note:

> On Windows systems only, the `\` character will be interpreted as a directory separator. On other systems it will be treated like any other character.

Caution

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

### Parameters

`path`

  The path to be parsed.

`flags`

  If present, specifies a specific element to be returned; one of `PATHINFO_DIRNAME`, `PATHINFO_BASENAME`, `PATHINFO_EXTENSION` or `PATHINFO_FILENAME`.

  If `flags` is not specified, returns all available elements.

### Return Values

If the `flags` parameter is not passed, an associative array containing the following elements is returned: `dirname`, `basename`, `extension` (if any), and `filename`.

> Note:

> If the `path` has more than one extension, `PATHINFO_EXTENSION` returns only the last one and `PATHINFO_FILENAME` only strips the last one. (see first example below).

> Note:

> If the `path` does not have an extension, no `extension` element will be returned (see second example below).

> Note:

> If the `basename` of the `path` starts with a dot, the following characters are interpreted as `extension`, and the `filename` is empty (see third example below).

If `flags` is present, returns a string containing the requested element.

### Examples

Example #1 pathinfo() Example

`<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
?>`

The above example will output:

    /www/htdocs/inc
    lib.inc.php
    php
    lib.inc

Example #2 pathinfo() example showing difference between null and no extension

`<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);
$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>`

The above example will output something similar to:

    string(0) ""

    Notice: Undefined index: extension in test.php on line 6
    NULL

Example #3 pathinfo() example for a dot-file

`<?php
print_r(pathinfo('/some/path/.test'));
?>`

The above example will output something similar to:

    Array
    (
        [dirname] => /some/path
        [basename] => .test
        [extension] => test
        [filename] =>
    )

Example #4 pathinfo() example with array dereferencing

The `flags` parameter is not a bitmask. Only a single value may be provided. To select only a limited set of parsed values, use array destructuring like so:

`<?php
['basename' => $basename, 'dirname' => $dirname] = pathinfo('/www/htdocs/inc/lib.inc.php');
var_dump($basename, $dirname);
?>`

The above example will output something similar to:

    string(11) "lib.inc.php"
    string(15) "/www/htdocs/inc"

### See Also

- dirname() - Returns a parent directory's path
- basename() - Returns trailing name component of path
- parse_url() - Parse a URL and return its components
- realpath() - Returns canonicalized absolute pathname

# pclose

(PHP 4, PHP 5, PHP 7, PHP 8)

pclose — Closes process file pointer

### Description

pclose(resource `$handle`): int

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

### Parameters

`handle`

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

### Return Values

Returns the termination status of the process that was run. In case of an error then `-1` is returned.

> Note:

> If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.

### Examples

Example #1 pclose() example

`<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>`

### Notes

> Note: Unix Only:

> pclose() is internally implemented using the `waitpid(3)` system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

### See Also

- popen() - Opens process file pointer

# popen

(PHP 4, PHP 5, PHP 7, PHP 8)

popen — Opens process file pointer

### Description

popen(string `$command`, string `$mode`): resource|false

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

### Parameters

`command`

  The command

`mode`

  The mode. Either `'r'` for reading, or `'w'` for writing.

  On Windows, popen() defaults to text mode, i.e. any `\n` characters written to or read from the pipe will be translated to `\r\n`. If this is not desired, binary mode can be enforced by setting `mode` to `'rb'` and `'wb'`, respectively.

### Return Values

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

If an error occurs, returns `false`.

### Examples

Example #1 popen() example

`<?php
$handle = popen("/bin/ls", "r");
?>`

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #2 popen() example

`<?php
error_reporting(E_ALL);
/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>`

### Notes

> Note:

> If you're looking for bi-directional support (two-way), use proc_open().

### See Also

- pclose() - Closes process file pointer
- fopen() - Opens file or URL
- proc_open() - Execute a command and open file pointers for input/output

# readfile

(PHP 4, PHP 5, PHP 7, PHP 8)

readfile — Outputs a file

### Description

readfile(string `$filename`, bool `$use_include_path` = `false`, ?resource `$context` = `null`): int|false

Reads a file and writes it to the output buffer.

### Parameters

`filename`

  The filename being read.

`use_include_path`

  You can use the optional second parameter and set it to `true`, if you want to search for the file in the include_path, too.

`context`

  A context stream resource.

### Return Values

Returns the number of bytes read from the file on success, or `false` on failure

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Examples

Example #1 Forcing a download using readfile()

`<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>`

The above example will output something similar to:

### Notes

> Note:

> readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### See Also

- fpassthru() - Output all remaining data on a file pointer
- file() - Reads entire file into an array
- fopen() - Opens file or URL
- include - include
- require - require
- virtual() - Perform an Apache sub-request
- file_get_contents() - Reads entire file into a string
- Supported Protocols and Wrappers

# readlink

(PHP 4, PHP 5, PHP 7, PHP 8)

readlink — Returns the target of a symbolic link

### Description

readlink(string `$path`): string|false

readlink() does the same as the readlink C function.

### Parameters

`path`

  The symbolic link path.

### Return Values

Returns the contents of the symbolic link path or `false` on error.

> Note: The function fails if `path` is not a symlink, except on Windows, where the normalized path will be returned.

### Examples

Example #1 readlink() example

`<?php
// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');
?>`

### See Also

- is_link() - Tells whether the filename is a symbolic link
- symlink() - Creates a symbolic link
- linkinfo() - Gets information about a link

# realpath

(PHP 4, PHP 5, PHP 7, PHP 8)

realpath — Returns canonicalized absolute pathname

### Description

realpath(string `$path`): string|false

realpath() expands all symbolic links and resolves references to `/./`, `/../` and extra `/` characters in the input `path` and returns the canonicalized absolute pathname.

### Parameters

`path`

  The path being checked.

  > Note:

  > Whilst a path must be supplied, the value can be an empty string. In this case, the value is interpreted as the current directory.

### Return Values

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, `/./` or `/../` components. Trailing delimiters, such as `\` and `/`, are also removed.

realpath() returns `false` on failure, e.g. if the file does not exist.

> Note:

> The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return `false`.

> Note:

> For case-insensitive filesystems realpath() may or may not normalize the character case.

> Note:

> The function realpath() will not work for a file which is inside a Phar as such path would be a virtual path, not a real one.

> Note:

> On Windows, junctions and symbolic links to directories are only expanded by one level.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Examples

Example #1 realpath() example

`<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd') . PHP_EOL;
echo realpath('/tmp/') . PHP_EOL;
?>`

The above example will output:

    /etc/passwd
    /tmp

Example #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

`<?php
echo realpath('/windows/system32'), PHP_EOL;
echo realpath('C:\Program Files\\'), PHP_EOL;
?>`

The above example will output:

    C:\WINDOWS\System32
    C:\Program Files

### See Also

- basename() - Returns trailing name component of path
- dirname() - Returns a parent directory's path
- pathinfo() - Returns information about a file path

# realpath_cache_get

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

realpath_cache_get — Get realpath cache entries

### Description

realpath_cache_get(): array

Get the contents of the realpath cache.

### Parameters

This function has no parameters.

### Return Values

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

### Examples

Example #1 realpath_cache_get() example

`<?php
var_dump(realpath_cache_get());
?>`

The above example will output something similar to:

    array(2) {
      ["/test"]=>
      array(4) {
        ["key"]=>
        int(123456789)
        ["is_dir"]=>
        bool(true)
        ["realpath"]=>
        string(5) "/test"
        ["expires"]=>
        int(1260318939)
      }
      ["/test/test.php"]=>
      array(4) {
        ["key"]=>
        int(987654321)
        ["is_dir"]=>
        bool(false)
        ["realpath"]=>
        string(12) "/root/test.php"
        ["expires"]=>
        int(1260318939)
      }
    }

### See Also

- realpath_cache_size() - Get realpath cache size

# realpath_cache_size

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

realpath_cache_size — Get realpath cache size

### Description

realpath_cache_size(): int

Get the amount of memory used by the realpath cache.

### Parameters

This function has no parameters.

### Return Values

Returns how much memory realpath cache is using.

### Examples

Example #1 realpath_cache_size() example

`<?php
var_dump(realpath_cache_size());
?>`

The above example will output something similar to:

    int(412)

### See Also

- realpath_cache_get() - Get realpath cache entries
- The realpath_cache_size configuration option

# rename

(PHP 4, PHP 5, PHP 7, PHP 8)

rename — Renames a file or directory

### Description

rename(string `$from`, string `$to`, ?resource `$context` = `null`): bool

Attempts to rename `from` to `to`, moving it between directories if necessary. If renaming a file and `to` exists, it will be overwritten. If renaming a directory and `to` exists, this function will emit a warning.

### Parameters

`from`

  The old name.

  > Note:

  > The wrapper used in `from` must match the wrapper used in `to`.

`to`

  The new name.

  > Note: On Windows, if `to` already exists, it must be writable. Otherwise rename() fails and issues `E_WARNING`.

`context`

  A context stream resource.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Example with rename()

`<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>`

### See Also

- copy() - Copies file
- unlink() - Deletes a file
- move_uploaded_file() - Moves an uploaded file to a new location

# rewind

(PHP 4, PHP 5, PHP 7, PHP 8)

rewind — Rewind the position of a file pointer

### Description

rewind(resource `$stream`): bool

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

> Note:

> If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file pointer position.

### Parameters

`stream`

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

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 rewind() overwriting example

`<?php
$handle = fopen('output.txt', 'r+');
fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output.txt'));
fclose($handle);
?>`

The above example will output something similar to:

    Foolly long sentence.

### See Also

- fread() - Binary-safe file read
- fseek() - Seeks on a file pointer
- ftell() - Returns the current position of the file read/write pointer
- fwrite() - Binary-safe file write

# rmdir

(PHP 4, PHP 5, PHP 7, PHP 8)

rmdir — Removes directory

### Description

rmdir(string `$directory`, ?resource `$context` = `null`): bool

Attempts to remove the directory named by `directory`. The directory must be empty, and the relevant permissions must permit this. A `E_WARNING` level error will be generated on failure.

### Parameters

`directory`

  Path to the directory.

`context`

  A context stream resource.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 rmdir() example

`<?php
if (!is_dir('examples')) {
mkdir('examples');
}
rmdir('examples');
?>`

### See Also

- is_dir() - Tells whether the filename is a directory
- mkdir() - Makes directory
- unlink() - Deletes a file

# set_file_buffer

(PHP 4, PHP 5, PHP 7, PHP 8)

set_file_buffer — Alias of stream_set_write_buffer()

### Description

This function is an alias of: stream_set_write_buffer().

# stat

(PHP 4, PHP 5, PHP 7, PHP 8)

stat — Gives information about a file

### Description

stat(string `$filename`): array|false

Gathers the statistics of the file named by `filename`. If `filename` is a symbolic link, statistics are from the file itself, not the symlink. Prior to PHP 7.4.0, on Windows NTS builds the `size`, `atime`, `mtime` and `ctime` statistics have been from the symlink, in this case.

lstat() is identical to stat() except it would instead be based off the symlinks status.

### Parameters

`filename`

  Path to the file.

### Return Values

stat() and fstat() result format
Numeric | Associative | Description
--- | --- | ---
0 | dev | device number ***
1 | ino | inode number ****
2 | mode | inode protection mode *****
3 | nlink | number of links
4 | uid | userid of owner *
5 | gid | groupid of owner *
6 | rdev | device type, if inode device
7 | size | size in bytes
8 | atime | time of last access (Unix timestamp)
9 | mtime | time of last modification (Unix timestamp)
10 | ctime | time of last inode change (Unix timestamp)
11 | blksize | blocksize of filesystem IO **
12 | blocks | number of 512-byte blocks allocated **

* On Windows this will always be `0`.

** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return `-1`.

*** On Windows, as of PHP 7.4.0, this is the serial number of the volume that contains the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was the numeric representation of the drive letter (e.g. `2` for `C:`) for stat(), and `0` for lstat().

**** On Windows, as of PHP 7.4.0, this is the identifier associated with the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was always `0`.

***** On Windows, the writable permission bit is set according to the read-only file attribute, and the same value is reported for all users, group and owner. The ACL is not taken into account, contrary to is_writable().

The value of `mode` contains information read by several functions. When written in octal, starting from the right, the first three digits are returned by chmod(). The next digit is ignored by PHP. The next two digits indicate the file type:

`mode` file types
`mode` in octal | Meaning
--- | ---
`0140000` | socket
`0120000` | link
`0100000` | regular file
`0060000` | block device
`0040000` | directory
`0020000` | character device
`0010000` | fifo

So for example a regular file could be `0100644` and a directory could be `0040755`.

In case of error, stat() returns `false`.

> Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

### Errors/Exceptions

Upon failure, an `E_WARNING` is emitted.

### Changelog

Version | Description
--- | ---
7.4.0 | On Windows, the device number is now the serial number of the volume that contains the file, and the inode number is the identifier associated with the file.
7.4.0 | The `size`, `atime`, `mtime` and `ctime` statistics of symlinks are always those of the target. This was previously not the case for NTS builds on Windows.

### Examples

Example #1 stat() example

`<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');
/*
* Print file access time, this is the same
* as calling fileatime()
*/
echo 'Access time: ' . $stat['atime'];
/*
* Print file modification time, this is the
* same as calling filemtime()
*/
echo 'Modification time: ' . $stat['mtime'];
/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>`

Example #2 Using stat() information together with touch()

`<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');
/* Did we failed to get stat information? */
if (!$stat) {
echo 'stat() call failed...';
} else {
/*
* We want the access time to be 1 week
* after the current access time.
*/
$atime = $stat['atime'] + 604800;
/* Touch the file */
if (!touch('some_file.txt', time(), $atime)) {
echo 'Failed to touch file...';
} else {
echo 'touch() returned success...';
}
}
?>`

### Notes

> Note:

> Note that time resolution may differ from one file system to another.

> Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

### See Also

- lstat() - Gives information about a file or symbolic link
- fstat() - Gets information about a file using an open file pointer
- filemtime() - Gets file modification time
- filegroup() - Gets file group
- SplFileInfo

# symlink

(PHP 4, PHP 5, PHP 7, PHP 8)

symlink — Creates a symbolic link

### Description

symlink(string `$target`, string `$link`): bool

symlink() creates a symbolic link to the existing `target` with the specified name `link`.

### Parameters

`target`

  Target of the link.

`link`

  The link name.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

The function fails, and issues `E_WARNING`, if `link` already exists. On Windows, the function also fails, and issues `E_WARNING`, if `target` does not exist.

### Examples

Example #1 Create a symbolic link

`<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);
echo readlink($link);
?>`

### See Also

- is_link() - Tells whether the filename is a symbolic link
- link() - Create a hard link
- readlink() - Returns the target of a symbolic link
- linkinfo() - Gets information about a link
- unlink() - Deletes a file

# tempnam

(PHP 4, PHP 5, PHP 7, PHP 8)

tempnam — Create file with unique file name

### Description

tempnam(string `$directory`, string `$prefix`): string|false

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.

### Parameters

`directory`

  The directory where the temporary filename will be created.

`prefix`

  The prefix of the generated temporary filename.

  > Note: Only the first 63 characters of the prefix are used, the rest are ignored. Windows uses only the first three characters of the prefix.

### Return Values

Returns the new temporary filename (with path), or `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.0 | tempnam() now emits a notice when falling back to the temp directory of the system.

### Examples

Example #1 tempnam() example

`<?php
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);
// do something here
unlink($tmpfname);
?>`

### Notes

> Note: If PHP cannot create a file in the specified `directory` parameter, it falls back on the system default. On NTFS this also happens if the specified `directory` contains more than 65534 files.

### See Also

- tmpfile() - Creates a temporary file
- sys_get_temp_dir() - Returns directory path used for temporary files
- unlink() - Deletes a file

# tmpfile

(PHP 4, PHP 5, PHP 7, PHP 8)

tmpfile — Creates a temporary file

### Description

tmpfile(): resource|false

Creates a temporary file with a unique name in read-write-binary (w+b) mode and returns a file handle.

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.

Caution

If the script terminates unexpectedly, the temporary file may not be deleted.

### Parameters

This function has no parameters.

### Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or `false` on failure.

### Examples

Example #1 tmpfile() example

`<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>`

The above example will output:

    writing to tempfile

### See Also

- tempnam() - Create file with unique file name
- sys_get_temp_dir() - Returns directory path used for temporary files

# touch

(PHP 4, PHP 5, PHP 7, PHP 8)

touch — Sets access and modification time of file

### Description

touch(string `$filename`, ?int `$mtime` = `null`, ?int `$atime` = `null`): bool

Attempts to set the access and modification times of the file named in the `filename` parameter to the value given in `mtime`. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

### Parameters

`filename`

  The name of the file being touched.

`mtime`

  The touch time. If `mtime` is `null`, the current system time() is used.

`atime`

  If not `null`, the access time of the given filename is set to the value of `atime`. Otherwise, it is set to the value passed to the `mtime` parameter. If both are `null`, the current system time is used.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `mtime` and `atime` are now nullable.

### Examples

Example #1 touch() example

`<?php
if (touch($filename)) {
echo $filename . ' modification time has been changed to present time';
} else {
echo 'Sorry, could not change modification time of ' . $filename;
}
?>`

Example #2 touch() using the `mtime` parameter

`<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;
// Touch the file
if (!touch('some_file.txt', $time)) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}
?>`

### Notes

> Note:

> Note that time resolution may differ from one file system to another.

# umask

(PHP 4, PHP 5, PHP 7, PHP 8)

umask — Changes the current umask

### Description

umask(?int `$mask` = `null`): int

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

### Parameters

`mask`

  The new umask.

### Return Values

If `mask` is `null`, umask() simply returns the current umask otherwise the old umask is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `mask` is nullable now.

### Examples

Example #1 umask() example

`<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);
// Checking
if ($old != umask()) {
die('An error occurred while changing back the umask');
}
?>`

### Notes

> Note:

> Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.

# unlink

(PHP 4, PHP 5, PHP 7, PHP 8)

unlink — Deletes a file

### Description

unlink(string `$filename`, ?resource `$context` = `null`): bool

Deletes `filename`. Similar to the Unix C unlink() function. An `E_WARNING` level error will be generated on failure.

### Parameters

`filename`

  Path to the file.

  If the file is a symlink, the symlink will be deleted. On Windows, to delete a symlink to a directory, rmdir() has to be used instead.

`context`

  A context stream resource.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
7.3.0 | On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed.

### Examples

Example #1 Basic unlink() usage

`<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);
unlink('test.html');
?>`

### See Also

- rmdir() - Removes directory

## Table of Contents

- basename — Returns trailing name component of path
- chgrp — Changes file group
- chmod — Changes file mode
- chown — Changes file owner
- clearstatcache — Clears file status cache
- copy — Copies file
- delete — See unlink or unset
- dirname — Returns a parent directory's path
- disk_free_space — Returns available space on filesystem or disk partition
- disk_total_space — Returns the total size of a filesystem or disk partition
- diskfreespace — Alias of disk_free_space
- fclose — Closes an open file pointer
- fdatasync — Synchronizes data (but not meta-data) to the file
- feof — Tests for end-of-file on a file pointer
- fflush — Flushes the output to a file
- fgetc — Gets character from file pointer
- fgetcsv — Gets line from file pointer and parse for CSV fields
- fgets — Gets line from file pointer
- fgetss — Gets line from file pointer and strip HTML tags
- file — Reads entire file into an array
- file_exists — Checks whether a file or directory exists
- file_get_contents — Reads entire file into a string
- file_put_contents — Write data to a file
- fileatime — Gets last access time of file
- filectime — Gets inode change time of file
- filegroup — Gets file group
- fileinode — Gets file inode
- filemtime — Gets file modification time
- fileowner — Gets file owner
- fileperms — Gets file permissions
- filesize — Gets file size
- filetype — Gets file type
- flock — Portable advisory file locking
- fnmatch — Match filename against a pattern
- fopen — Opens file or URL
- fpassthru — Output all remaining data on a file pointer
- fputcsv — Format line as CSV and write to file pointer
- fputs — Alias of fwrite
- fread — Binary-safe file read
- fscanf — Parses input from a file according to a format
- fseek — Seeks on a file pointer
- fstat — Gets information about a file using an open file pointer
- fsync — Synchronizes changes to the file (including meta-data)
- ftell — Returns the current position of the file read/write pointer
- ftruncate — Truncates a file to a given length
- fwrite — Binary-safe file write
- glob — Find pathnames matching a pattern
- is_dir — Tells whether the filename is a directory
- is_executable — Tells whether the filename is executable
- is_file — Tells whether the filename is a regular file
- is_link — Tells whether the filename is a symbolic link
- is_readable — Tells whether a file exists and is readable
- is_uploaded_file — Tells whether the file was uploaded via HTTP POST
- is_writable — Tells whether the filename is writable
- is_writeable — Alias of is_writable
- lchgrp — Changes group ownership of symlink
- lchown — Changes user ownership of symlink
- link — Create a hard link
- linkinfo — Gets information about a link
- lstat — Gives information about a file or symbolic link
- mkdir — Makes directory
- move_uploaded_file — Moves an uploaded file to a new location
- parse_ini_file — Parse a configuration file
- parse_ini_string — Parse a configuration string
- pathinfo — Returns information about a file path
- pclose — Closes process file pointer
- popen — Opens process file pointer
- readfile — Outputs a file
- readlink — Returns the target of a symbolic link
- realpath — Returns canonicalized absolute pathname
- realpath_cache_get — Get realpath cache entries
- realpath_cache_size — Get realpath cache size
- rename — Renames a file or directory
- rewind — Rewind the position of a file pointer
- rmdir — Removes directory
- set_file_buffer — Alias of stream_set_write_buffer
- stat — Gives information about a file
- symlink — Creates a symbolic link
- tempnam — Create file with unique file name
- tmpfile — Creates a temporary file
- touch — Sets access and modification time of file
- umask — Changes the current umask
- unlink — Deletes a file

- Installing/Configuring
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Filesystem Functions
  - basename — Returns trailing name component of path
  - chgrp — Changes file group
  - chmod — Changes file mode
  - chown — Changes file owner
  - clearstatcache — Clears file status cache
  - copy — Copies file
  - delete — See unlink or unset
  - dirname — Returns a parent directory's path
  - disk_free_space — Returns available space on filesystem or disk partition
  - disk_total_space — Returns the total size of a filesystem or disk partition
  - diskfreespace — Alias of disk_free_space
  - fclose — Closes an open file pointer
  - fdatasync — Synchronizes data (but not meta-data) to the file
  - feof — Tests for end-of-file on a file pointer
  - fflush — Flushes the output to a file
  - fgetc — Gets character from file pointer
  - fgetcsv — Gets line from file pointer and parse for CSV fields
  - fgets — Gets line from file pointer
  - fgetss — Gets line from file pointer and strip HTML tags
  - file — Reads entire file into an array
  - file_exists — Checks whether a file or directory exists
  - file_get_contents — Reads entire file into a string
  - file_put_contents — Write data to a file
  - fileatime — Gets last access time of file
  - filectime — Gets inode change time of file
  - filegroup — Gets file group
  - fileinode — Gets file inode
  - filemtime — Gets file modification time
  - fileowner — Gets file owner
  - fileperms — Gets file permissions
  - filesize — Gets file size
  - filetype — Gets file type
  - flock — Portable advisory file locking
  - fnmatch — Match filename against a pattern
  - fopen — Opens file or URL
  - fpassthru — Output all remaining data on a file pointer
  - fputcsv — Format line as CSV and write to file pointer
  - fputs — Alias of fwrite
  - fread — Binary-safe file read
  - fscanf — Parses input from a file according to a format
  - fseek — Seeks on a file pointer
  - fstat — Gets information about a file using an open file pointer
  - fsync — Synchronizes changes to the file (including meta-data)
  - ftell — Returns the current position of the file read/write pointer
  - ftruncate — Truncates a file to a given length
  - fwrite — Binary-safe file write
  - glob — Find pathnames matching a pattern
  - is_dir — Tells whether the filename is a directory
  - is_executable — Tells whether the filename is executable
  - is_file — Tells whether the filename is a regular file
  - is_link — Tells whether the filename is a symbolic link
  - is_readable — Tells whether a file exists and is readable
  - is_uploaded_file — Tells whether the file was uploaded via HTTP POST
  - is_writable — Tells whether the filename is writable
  - is_writeable — Alias of is_writable
  - lchgrp — Changes group ownership of symlink
  - lchown — Changes user ownership of symlink
  - link — Create a hard link
  - linkinfo — Gets information about a link
  - lstat — Gives information about a file or symbolic link
  - mkdir — Makes directory
  - move_uploaded_file — Moves an uploaded file to a new location
  - parse_ini_file — Parse a configuration file
  - parse_ini_string — Parse a configuration string
  - pathinfo — Returns information about a file path
  - pclose — Closes process file pointer
  - popen — Opens process file pointer
  - readfile — Outputs a file
  - readlink — Returns the target of a symbolic link
  - realpath — Returns canonicalized absolute pathname
  - realpath_cache_get — Get realpath cache entries
  - realpath_cache_size — Get realpath cache size
  - rename — Renames a file or directory
  - rewind — Rewind the position of a file pointer
  - rmdir — Removes directory
  - set_file_buffer — Alias of stream_set_write_buffer
  - stat — Gives information about a file
  - symlink — Creates a symbolic link
  - tempnam — Create file with unique file name
  - tmpfile — Creates a temporary file
  - touch — Sets access and modification time of file
  - umask — Changes the current umask
  - unlink — Deletes a file

# Inotify

# Introduction

The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().

As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.

# Installing/Configuring

## Table of Contents

- Installing/Configuring
- Resource Types

## Installing/Configuring

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: » https://pecl.php.net/package/inotify.

## Resource Types

This extension defines a stream resource returned by inotify_init().

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

Inotify constants usable with inotify_add_watch() and/or returned by inotify_read()
`IN_ACCESS` (int)
  File was accessed (read) (*)
`IN_MODIFY` (int)
  File was modified (*)
`IN_ATTRIB` (int)
  Metadata changed (e.g. permissions, mtime, etc.) (*)
`IN_CLOSE_WRITE` (int)
  File opened for writing was closed (*)
`IN_CLOSE_NOWRITE` (int)
  File not opened for writing was closed (*)
`IN_OPEN` (int)
  File was opened (*)
`IN_MOVED_TO` (int)
  File moved into watched directory (*)
`IN_MOVED_FROM` (int)
  File moved out of watched directory (*)
`IN_CREATE` (int)
  File or directory created in watched directory (*)
`IN_DELETE` (int)
  File or directory deleted in watched directory (*)
`IN_DELETE_SELF` (int)
  Watched file or directory was deleted
`IN_MOVE_SELF` (int)
  Watch file or directory was moved
`IN_CLOSE` (int)
  Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
`IN_MOVE` (int)
  Equals to IN_MOVED_FROM | IN_MOVED_TO
`IN_ALL_EVENTS` (int)
  Bitmask of all the above constants
`IN_UNMOUNT` (int)
  File system containing watched object was unmounted
`IN_Q_OVERFLOW` (int)
  Event queue overflowed (wd is -1 for this event)
`IN_IGNORED` (int)
  Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
`IN_ISDIR` (int)
  Subject of this event is a directory
`IN_ONLYDIR` (int)
  Only watch pathname if it is a directory (Since Linux 2.6.15)
`IN_DONT_FOLLOW` (int)
  Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
`IN_MASK_ADD` (int)
  Add events to watch mask for this pathname if it already exists (instead of replacing mask).
`IN_ONESHOT` (int)
  Monitor pathname for one event, then remove from watch list.

> Note: The events marked with an asterisk (*) above can occur for files in watched directories.

# Inotify Functions

# inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — Add a watch to an initialized inotify instance

### Description

inotify_add_watch(resource `$inotify_instance`, string `$pathname`, int `$mask`): int|false

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in `pathname`.

Using inotify_add_watch() on a watched object replaces the existing watch. Using the `IN_MASK_ADD` constant adds (OR) events to the existing watch.

### Parameters

`inotify_instance`
  Resource returned by inotify_init()
`pathname`
  File or directory to watch
`mask`
  Events to watch for. See Predefined Constants.

### Return Values

The return value is a unique (inotify instance wide) watch descriptor, or `false` on failure.

### See Also

- inotify_init() - Initialize an inotify instance

# inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

### Description

inotify_init(): resource|false

Initialize an inotify instance for use with inotify_add_watch()

### Parameters

This function has no parameters.

### Return Values

A stream resource or `false` on error.

### Examples

Example #1 Example usage of inotify

`<?php
// Open an inotify instance
$fd = inotify_init();
// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);
// generate an event
touch(__FILE__);
// Read events
$events = inotify_read($fd);
print_r($events);
// The following methods allows to use inotify functions without blocking on inotify_read():
// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);
// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending
// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block
// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);
// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);
?>`

The above example will output something similar to:

    array(
      array(
        'wd' => 1,     // Equals $watch_descriptor
        'mask' => 4,   // IN_ATTRIB bit is set
        'cookie' => 0, // unique id to connect related events (e.g.
                       // IN_MOVE_FROM and IN_MOVE_TO events)
        'name' => '',  // the name of a file (e.g. if we monitored changes
                       // in a directory)
      ),
    );

### See Also

- inotify_add_watch() - Add a watch to an initialized inotify instance
- inotify_rm_watch() - Remove an existing watch from an inotify instance
- inotify_queue_len() - Return a number upper than zero if there are pending events
- inotify_read() - Read events from an inotify instance
- fclose() - Closes an open file pointer

# inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — Return a number upper than zero if there are pending events

### Description

inotify_queue_len(resource `$inotify_instance`): int

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

### Parameters

`inotify_instance`
  Resource returned by inotify_init()

### Return Values

Returns a number upper than zero if there are pending events.

### See Also

- inotify_init() - Initialize an inotify instance
- stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
- stream_set_blocking() - Set blocking/non-blocking mode on a stream

# inotify_read

(PECL inotify >= 0.1.2)

inotify_read — Read events from an inotify instance

### Description

inotify_read(resource `$inotify_instance`): array

Read inotify events from an inotify instance.

### Parameters

`inotify_instance`
  Resource returned by inotify_init()

### Return Values

An array of inotify events or `false` if no events was pending and `inotify_instance` is non-blocking. Each event is an array with the following keys:

- wd is a watch descriptor returned by inotify_add_watch()
- mask is a bit mask of events
- cookie is a unique id to connect related events (e.g. `IN_MOVE_FROM` and `IN_MOVE_TO`)
- name is the name of a file (e.g. if a file was modified in a watched directory)

### See Also

- inotify_init() - Initialize an inotify instance
- stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
- stream_set_blocking() - Set blocking/non-blocking mode on a stream
- inotify_queue_len() - Return a number upper than zero if there are pending events

# inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — Remove an existing watch from an inotify instance

### Description

inotify_rm_watch(resource `$inotify_instance`, int `$watch_descriptor`): bool

inotify_rm_watch() removes the watch `watch_descriptor` from the inotify instance `inotify_instance`.

### Parameters

`inotify_instance`
  Resource returned by inotify_init()
`watch_descriptor`
  Watch to remove from the instance

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- inotify_init() - Initialize an inotify instance

## Table of Contents

- inotify_add_watch — Add a watch to an initialized inotify instance
- inotify_init — Initialize an inotify instance
- inotify_queue_len — Return a number upper than zero if there are pending events
- inotify_read — Read events from an inotify instance
- inotify_rm_watch — Remove an existing watch from an inotify instance

- Installing/Configuring
  - Installing/Configuring
  - Resource Types
- Predefined Constants
- Inotify Functions
  - inotify_add_watch — Add a watch to an initialized inotify instance
  - inotify_init — Initialize an inotify instance
  - inotify_queue_len — Return a number upper than zero if there are pending events
  - inotify_read — Read events from an inotify instance
  - inotify_rm_watch — Remove an existing watch from an inotify instance

# xattr

# Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

To use xattr, you will need libattr installed. It is available at » http://savannah.nongnu.org/projects/attr/.

> Note:

> These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are `ext2`, `ext3`, `reiserfs`, `jfs`, and `xfs`.

## Installation

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: » https://pecl.php.net/package/xattr.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

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

`XATTR_ROOT` (int)
  Set attribute in root (trusted) namespace. Requires root privileges.
`XATTR_DONTFOLLOW` (int)
  Do not follow the symbolic link but operate on symbolic link itself.
`XATTR_CREATE` (int)
  Function will fail if extended attribute already exists.
`XATTR_REPLACE` (int)
  Function will fail if extended attribute doesn't exist.

# xattr Functions

# xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

### Description

xattr_get(string `$filename`, string `$name`, int `$flags` = 0): string|false

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter.

### Parameters

`filename`

  The file from which we get the attribute.

`name`

  The name of the attribute.

`flags`

  Supported xattr flags
  `XATTR_DONTFOLLOW` | Do not follow the symbolic link but operate on symbolic link itself.
  `XATTR_ROOT` | Set attribute in root (trusted) namespace. Requires root privileges.

### Return Values

Returns a string containing the value or `false` if the attribute doesn't exist.

### Examples

Example #1 Checks if system administrator has signed the file

`<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);
/* ... check if $signature is valid ... */
?>`

### See Also

- xattr_list() - Get a list of extended attributes
- xattr_set() - Set an extended attribute
- xattr_remove() - Remove an extended attribute

# xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

### Description

xattr_list(string `$filename`, int `$flags` = 0): array

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter.

### Parameters

`filename`

  The path of the file.

`flags`

  Supported xattr flags
  `XATTR_DONTFOLLOW` | Do not follow the symbolic link but operate on symbolic link itself.
  `XATTR_ROOT` | Set attribute in root (trusted) namespace. Requires root privileges.

### Return Values

This function returns an array with names of extended attributes.

### Examples

Example #1 Prints names of all extended attributes of file

`<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);
echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
printf("%s\n", $attr_name);
}
echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
printf("%s\n", $attr_name);
}
?>`

### See Also

- xattr_get() - Get an extended attribute

# xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

### Description

xattr_remove(string `$filename`, string `$name`, int `$flags` = 0): bool

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter.

### Parameters

`filename`

  The file from which we remove the attribute.

`name`

  The name of the attribute to remove.

`flags`

  Supported xattr flags
  `XATTR_DONTFOLLOW` | Do not follow the symbolic link but operate on symbolic link itself.
  `XATTR_ROOT` | Set attribute in root (trusted) namespace. Requires root privileges.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Removes all extended attributes of a file

`<?php
$file = 'some_file';
$attributes = xattr_list($file);
foreach ($attributes as $attr_name) {
xattr_remove($file, $attr_name);
}
?>`

### See Also

- xattr_list() - Get a list of extended attributes
- xattr_set() - Set an extended attribute
- xattr_get() - Get an extended attribute

# xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

### Description

xattr_set(
string `$filename`,
string `$name`,
string `$value`,
int `$flags` = 0
): bool

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter.

### Parameters

`filename`

  The file in which we set the attribute.

`name`

  The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the `flags` parameter.

`value`

  The value of the attribute.

`flags`

  Supported xattr flags
  `XATTR_CREATE` | Function will fail if extended attribute already exists.
  `XATTR_REPLACE` | Function will fail if extended attribute doesn't exist.
  `XATTR_DONTFOLLOW` | Do not follow the symbolic link but operate on symbolic link itself.
  `XATTR_ROOT` | Set attribute in root (trusted) namespace. Requires root privileges.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Sets extended attributes on .wav file

`<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');
/* ... other code ... */
printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?>`

### See Also

- xattr_get() - Get an extended attribute
- xattr_remove() - Remove an extended attribute

# xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

### Description

xattr_supported(string `$filename`, int `$flags` = 0): bool

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

### Parameters

`filename`

  The path of the tested file.

`flags`

  Supported xattr flags
  `XATTR_DONTFOLLOW` | Do not follow the symbolic link but operate on symbolic link itself.

### Return Values

This function returns `true` if filesystem supports extended attributes, `false` if it doesn't and `null` if it can't be determined (for example wrong path or lack of permissions to file).

### Examples

Example #1 xattr_supported() example

The following code checks if we can use extended attributes.

`<?php
$file = 'some_file';
if (xattr_supported($file)) {
/* ... make use of some xattr_* functions ... */
}
?>`

### See Also

- xattr_get() - Get an extended attribute
- xattr_list() - Get a list of extended attributes

## Table of Contents

- xattr_get — Get an extended attribute
- xattr_list — Get a list of extended attributes
- xattr_remove — Remove an extended attribute
- xattr_set — Set an extended attribute
- xattr_supported — Check if filesystem supports extended attributes

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- xattr Functions
  - xattr_get — Get an extended attribute
  - xattr_list — Get a list of extended attributes
  - xattr_remove — Remove an extended attribute
  - xattr_set — Set an extended attribute
  - xattr_supported — Check if filesystem supports extended attributes

# xdiff

# Introduction

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

> Note:

> You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

## Installation

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: » https://pecl.php.net/package/xdiff.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

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

`XDIFF_PATCH_NORMAL` (int)
  This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
`XDIFF_PATCH_REVERSE` (int)
  This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.

# xdiff Functions

# xdiff_file_bdiff

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff — Make binary diff of two files

### Description

xdiff_file_bdiff(string `$old_file`, string `$new_file`, string `$dest`): bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

### Parameters

`old_file`

  Path to the first file. This file acts as "old" file.

`new_file`

  Path to the second file. This file acts as "new" file.

`dest`

  Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

`<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>`

### Notes

> Note:

> Both files will be loaded into memory so ensure that your memory_limit is set high enough.

### See Also

- xdiff_file_bpatch() - Patch a file with a binary diff

# xdiff_file_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

### Description

xdiff_file_bdiff_size(string `$file`): int

Returns a size of a result file that would be created after applying binary patch from file `file` to the original file.

### Parameters

`file`

  The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

### Return Values

Returns the size of file that would be created.

### Examples

Example #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

`<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>`

### See Also

- xdiff_file_bdiff() - Make binary diff of two files
- xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
- xdiff_file_bpatch() - Patch a file with a binary diff

# xdiff_file_bpatch

(PECL xdiff >= 1.5.0)

xdiff_file_bpatch — Patch a file with a binary diff

### Description

xdiff_file_bpatch(string `$file`, string `$patch`, string `$dest`): bool

Patches a `file` with a binary `patch` and stores the result in a file `dest`. This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

### Parameters

`file`

  The original file.

`patch`

  The binary patch file.

`dest`

  Path of the resulting file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

`<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';
$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}
?>`

### Notes

> Note:

> Both files (`file` and `patch`) will be loaded into memory so ensure that your memory_limit is set high enough.

### See Also

- xdiff_file_bdiff() - Make binary diff of two files
- xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

# xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

### Description

xdiff_file_diff(
string `$old_file`,
string `$new_file`,
string `$dest`,
int `$context` = 3,
bool `$minimal` = `false`
): bool

Makes an unified diff containing differences between `old_file` and `new_file` and stores it in `dest` file. The resulting file is human-readable. An optional `context` parameter specifies how many lines of context should be added around each change. Setting `minimal` parameter to true will result in outputting the shortest patch file possible (can take a long time).

### Parameters

`old_file`

  Path to the first file. This file acts as "old" file.

`new_file`

  Path to the second file. This file acts as "new" file.

`dest`

  Path of the resulting patch file.

`context`

  Indicates how many lines of context you want to include in diff result.

`minimal`

  Set this parameter to `true` if you want to minimalize size of the result (can take a long time).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

`<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';
xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>`

### Notes

> Note:

> This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

### See Also

- xdiff_file_patch() - Patch a file with an unified diff

# xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — Alias of xdiff_file_bdiff()

### Description

xdiff_file_diff_binary(string `$old_file`, string `$new_file`, string `$dest`): bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

### Parameters

`old_file`

  Path to the first file. This file acts as "old" file.

`new_file`

  Path to the second file. This file acts as "new" file.

`dest`

  Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

`<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>`

### Notes

> Note:

> Both files will be loaded into memory so ensure that your memory_limit is set high enough.

### See Also

- xdiff_file_bdiff() - Make binary diff of two files
- xdiff_file_bpatch() - Patch a file with a binary diff

# xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

### Description

xdiff_file_merge3(
string `$old_file`,
string `$new_file1`,
string `$new_file2`,
string `$dest`
): mixed

Merges three files into one and stores the result in a file `dest`. The `old_file` is an original version while `new_file1` and `new_file2` are modified versions of an original.

### Parameters

`old_file`

  Path to the first file. It acts as "old" file.

`new_file1`

  Path to the second file. It acts as modified version of `old_file`.

`new_file2`

  Path to the third file. It acts as modified version of `old_file`.

`dest`

  Path of the resulting file, containing merged changed from both `new_file1` and `new_file2`.

### Return Values

Returns `true` if merge was successful, string with rejected chunks if it was not or `false` if an internal error happened.

### Examples

Example #1 xdiff_file_merge3() example

The following code merges three files into one.

`<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';
$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>`

### See Also

- xdiff_string_merge3() - Merge 3 strings into one

# xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

### Description

xdiff_file_patch(
string `$file`,
string `$patch`,
string `$dest`,
int `$flags` = DIFF_PATCH_NORMAL
): mixed

Patches a `file` with a `patch` and stores the result in a file. `patch` has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional `flags` parameter specifies mode of operation.

### Parameters

`file`

  The original file.

`patch`

  The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

`dest`

  Path of the resulting file.

`flags`

  Can be either `XDIFF_PATCH_NORMAL` (default mode, normal patch) or `XDIFF_PATCH_REVERSE` (reversed patch).

  Starting from version 1.5.0, you can also use binary OR to enable `XDIFF_PATCH_IGNORESPACE` flag.

### Return Values

Returns `false` if an internal error happened, string with rejected chunks if patch couldn't be applied or `true` if patch has been successfully applied.

### Examples

Example #1 xdiff_file_patch() example

The following code applies unified diff to a file.

`<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';
$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>`

Example #2 Patch reversing example

The following code reverses a patch.

`<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';
$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>`

### See Also

- xdiff_file_diff() - Make unified diff of two files

# xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — Alias of xdiff_file_bpatch()

### Description

xdiff_file_patch_binary(string `$file`, string `$patch`, string `$dest`): bool

Patches a `file` with a binary `patch` and stores the result in a file `dest`. This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

### Parameters

`file`

  The original file.

`patch`

  The binary patch file.

`dest`

  Path of the resulting file.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

`<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';
$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}
?>`

### Notes

> Note:

> Both files (`file` and `patch`) will be loaded into memory so ensure that your memory_limit is set high enough.

### See Also

- xdiff_string_patch_binary() - Alias of xdiff_string_bpatch

# xdiff_file_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

### Description

xdiff_file_rabdiff(string `$old_file`, string `$new_file`, string `$dest`): bool

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

### Parameters

`old_file`

  Path to the first file. This file acts as "old" file.

`new_file`

  Path to the second file. This file acts as "new" file.

`dest`

  Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

`<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>`

### Notes

> Note:

> Both files will be loaded into memory so ensure that your memory_limit is set high enough.

### See Also

- xdiff_file_bpatch() - Patch a file with a binary diff

# xdiff_string_bdiff

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff — Make binary diff of two strings

### Description

xdiff_string_bdiff(string `$old_data`, string `$new_data`): string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

### Parameters

`old_data`

  First string with binary data. It acts as "old" data.

`new_data`

  Second string with binary data. It acts as "new" data.

### Return Values

Returns string with binary diff containing differences between "old" and "new" data or `false` if an internal error occurred.

### See Also

- xdiff_string_bpatch() - Patch a string with a binary diff

# xdiff_string_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

### Description

xdiff_string_bdiff_size(string `$patch`): int

Returns a size of a result file that would be created after applying binary `patch` to the original file.

### Parameters

`patch`

  The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

### Return Values

Returns the size of file that would be created.

### Examples

Example #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

`<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>`

### See Also

- xdiff_string_bdiff() - Make binary diff of two strings
- xdiff_string_rabdiff() - Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
- xdiff_string_bpatch() - Patch a string with a binary diff

# xdiff_string_bpatch

(PECL xdiff >= 1.5.0)

xdiff_string_bpatch — Patch a string with a binary diff

### Description

xdiff_string_bpatch(string `$str`, string `$patch`): string

Patches a string `str` with a binary `patch`. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

### Parameters

`str`

  The original binary string.

`patch`

  The binary patch string.

### Return Values

Returns the patched string, or `false` on error.

### See Also

- xdiff_string_bdiff() - Make binary diff of two strings
- xdiff_string_rabdiff() - Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

# xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

### Description

xdiff_string_diff(
string `$old_data`,
string `$new_data`,
int `$context` = 3,
bool `$minimal` = `false`
): string

Makes an unified diff containing differences between `old_data` string and `new_data` string and returns it. The resulting diff is human-readable. An optional `context` parameter specifies how many lines of context should be added around each change. Setting `minimal` parameter to true will result in outputting the shortest patch file possible (can take a long time).

### Parameters

`old_data`

  First string with data. It acts as "old" data.

`new_data`

  Second string with data. It acts as "new" data.

`context`

  Indicates how many lines of context you want to include in the diff result.

`minimal`

  Set this parameter to `true` if you want to minimalize the size of the result (can take a long time).

### Return Values

Returns string with resulting diff or `false` if an internal error happened.

### Examples

Example #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

`<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */
$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
echo "Differences between two articles:\n";
echo $diff;
}
?>`

### Notes

> Note:

> This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

### See Also

- xdiff_string_patch() - Patch a string with an unified diff

# xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — Alias of xdiff_string_bdiff()

### Description

xdiff_string_bdiff(string `$old_data`, string `$new_data`): string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

### Parameters

`old_data`

  First string with binary data. It acts as "old" data.

`new_data`

  Second string with binary data. It acts as "new" data.

### Return Values

Returns string with result or `false` if an internal error happened.

### See Also

- xdiff_string_bdiff() - Make binary diff of two strings
- xdiff_string_bpatch() - Patch a string with a binary diff

# xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

### Description

xdiff_string_merge3(
string `$old_data`,
string `$new_data1`,
string `$new_data2`,
string `&$error` = ?
): mixed

Merges three strings into one and returns the result. The `old_data` is an original version of data while `new_data1` and `new_data2` are modified versions of an original. An optional `error` is used to pass any rejected parts during merging process.

### Parameters

`old_data`

  First string with data. It acts as "old" data.

`new_data1`

  Second string with data. It acts as modified version of `old_data`.

`new_data2`

  Third string with data. It acts as modified version of `old_data`.

`error`

  If provided then rejected parts are stored inside this variable.

### Return Values

Returns the merged string, `false` if an internal error happened, or `true` if merged string is empty.

### See Also

- xdiff_file_merge3() - Merge 3 files into one

# xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

### Description

xdiff_string_patch(
string `$str`,
string `$patch`,
int `$flags` = ?,
string `&$error` = ?
): string

Patches a `str` string with an unified patch in `patch` parameter and returns the result. `patch` has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional `flags` parameter specifies mode of operation. Any rejected parts of the patch will be stored inside `error` variable if it is provided.

### Parameters

`str`

  The original string.

`patch`

  The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

`flags`

  `flags` can be either `XDIFF_PATCH_NORMAL` (default mode, normal patch) or `XDIFF_PATCH_REVERSE` (reversed patch).

  Starting from version 1.5.0, you can also use binary OR to enable `XDIFF_PATCH_IGNORESPACE` flag.

`error`

  If provided then rejected parts are stored inside this variable.

### Return Values

Returns the patched string, or `false` on error.

### Examples

Example #1 xdiff_string_patch() example

The following code applies changes to some article.

`<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */
$errors = '';
$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
echo "New article:\n";
echo $new_article;
}
if (strlen($errors)) {
echo "Rejects: \n";
echo $errors;
}
?>`

### See Also

- xdiff_string_diff() - Make unified diff of two strings

# xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — Alias of xdiff_string_bpatch()

### Description

xdiff_string_patch_binary(string `$str`, string `$patch`): string

Patches a string `str` with a binary `patch`. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

### Parameters

`str`

  The original binary string.

`patch`

  The binary patch string.

### Return Values

Returns the patched string, or `false` on error.

### See Also

- xdiff_string_bpatch() - Patch a string with a binary diff
- xdiff_string_bdiff() - Make binary diff of two strings
- xdiff_string_rabdiff() - Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

# xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiff — Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

### Description

xdiff_string_rabdiff(string `$old_data`, string `$new_data`): string|false

Makes a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm implemented by » libxdiff. Compared to xdiff_string_bdiff(), this algorithm generally produces smaller diffs and operates faster, while remaining fully compatible with xdiff_string_bpatch() and xdiff_file_bpatch() for applying patches.

This function can be used with both text and binary data. The resulting diff data can later be applied to recreate the new version from the old one.

For further information about the algorithm, see the » libxdiff documentation.

### Parameters

`old_data`

  The first string containing the "old" binary data.

`new_data`

  The second string containing the "new" binary data.

### Return Values

Returns a binary diff string containing the differences between the old and new data, or `false` on failure.

### Examples

Example #1 Creation of a binary diff between two strings

`<?php
$old = file_get_contents('file_v1.txt');
$new = file_get_contents('file_v2.txt');
$diff = xdiff_string_rabdiff($old, $new);
file_put_contents('patch.rdiff', $diff);
?>`

### See Also

- xdiff_string_bdiff() - Make binary diff of two strings
- xdiff_string_bpatch() - Patch a string with a binary diff
- xdiff_file_bpatch() - Patch a file with a binary diff

## Table of Contents

- xdiff_file_bdiff — Make binary diff of two files
- xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
- xdiff_file_bpatch — Patch a file with a binary diff
- xdiff_file_diff — Make unified diff of two files
- xdiff_file_diff_binary — Alias of xdiff_file_bdiff
- xdiff_file_merge3 — Merge 3 files into one
- xdiff_file_patch — Patch a file with an unified diff
- xdiff_file_patch_binary — Alias of xdiff_file_bpatch
- xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
- xdiff_string_bdiff — Make binary diff of two strings
- xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
- xdiff_string_bpatch — Patch a string with a binary diff
- xdiff_string_diff — Make unified diff of two strings
- xdiff_string_diff_binary — Alias of xdiff_string_bdiff
- xdiff_string_merge3 — Merge 3 strings into one
- xdiff_string_patch — Patch a string with an unified diff
- xdiff_string_patch_binary — Alias of xdiff_string_bpatch
- xdiff_string_rabdiff — Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- xdiff Functions
  - xdiff_file_bdiff — Make binary diff of two files
  - xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  - xdiff_file_bpatch — Patch a file with a binary diff
  - xdiff_file_diff — Make unified diff of two files
  - xdiff_file_diff_binary — Alias of xdiff_file_bdiff
  - xdiff_file_merge3 — Merge 3 files into one
  - xdiff_file_patch — Patch a file with an unified diff
  - xdiff_file_patch_binary — Alias of xdiff_file_bpatch
  - xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  - xdiff_string_bdiff — Make binary diff of two strings
  - xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  - xdiff_string_bpatch — Patch a string with a binary diff
  - xdiff_string_diff — Make unified diff of two strings
  - xdiff_string_diff_binary — Alias of xdiff_string_bdiff
  - xdiff_string_merge3 — Merge 3 strings into one
  - xdiff_string_patch — Patch a string with an unified diff
  - xdiff_string_patch_binary — Alias of xdiff_string_bpatch
  - xdiff_string_rabdiff — Make a binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

- Direct IO
  - Installing/Configuring
  - Predefined Constants
  - Direct IO Functions
- Directories
  - Predefined Constants
  - Directory — The Directory class
  - Directory Functions
- Fileinfo — File Information
  - Installing/Configuring
  - Predefined Constants
  - Fileinfo Functions
  - finfo — The finfo class
- Filesystem
  - Installing/Configuring
  - Predefined Constants
  - Filesystem Functions
- Inotify
  - Installing/Configuring
  - Predefined Constants
  - Inotify Functions
- xattr
  - Installing/Configuring
  - Predefined Constants
  - xattr Functions
- xdiff
  - Installing/Configuring
  - Predefined Constants
  - xdiff Functions

# Human Language and Character Encoding Support

# Enchant spelling library

# Introduction

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchant supports the following backends:

- `Aspell/Pspell (intends to replace Ispell)`
- `Ispell (old as sin, could be interpreted as a defacto standard)`
- `MySpell/Hunspell (an OOo projects, also used by Mozilla)`
- `Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")`
- `Hspell (Hebrew)`
- `AppleSpell (Mac OSX)`

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later. Enchant 2.0.0 or later is only supported as of PHP 8.0.0.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.

## Installation

Provided the required libraries are installed, users may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.

Windows users must enable php_enchant.dll in order to use this extension.

> Note: Additional setup on Windows
> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libenchant.dll, glib-2.dll, gmodule-2.dll. Furthermore, it is necessary to copy at least one of the shipped providers in lib\enchant to \usr\local\lib\enchant-2 (which is an absolute path from the root of the current drive). Prior to PHP 8.0.0, i.e. using Enchant v1, the providers had to be copied to C:\enchant_plugins instead, where this path could be customized by creating the registry value `HKEY_CURRENT_USER\SOFTWARE\Enchant\Config\Module_Dir` and setting it to the desired path.

## Resource Types

Prior to PHP 8.0.0, there are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.

# Predefined Constants

`LIBENCHANT_VERSION` (string)
  The version of libenchant. Available as of PHP 8.0.0.
`ENCHANT_MYSPELL` (int)
  Dictionary type for MySpell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path(). Deprecated as of PHP 8.0.0.
`ENCHANT_ISPELL` (int)
  Dictionary type for Ispell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path(). Deprecated as of PHP 8.0.0.

# Examples

Example #1 Enchant Usage Example

`<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
$dprovides = enchant_dict_describe($d);
echo "dictionary $tag provides:\n";
$wordcorrect = enchant_dict_check($d, "soong");
print_r($dprovides);
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>`

# Enchant Functions

# enchant_broker_describe

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

### Description

enchant_broker_describe(EnchantBroker `$broker`): array

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

### Return Values

Returns an array of available Enchant providers with their details.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned `false` on failure.

### Examples

Example #1 List the backends provided by the given broker

`<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);
?>`

The above example will output something similar to:

    Current broker provides the following backend(s):
    Array
    (
        [0] => Array
            (
                [name] => aspell
                [desc] => Aspell Provider
                [file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [1] => Array
            (
                [name] => hspell
                [desc] => Hspell Provider
                [file] => /usr/lib/enchant/libenchant_hspell.so
            )

        [2] => Array
            (
                [name] => ispell
                [desc] => Ispell Provider
                [file] => /usr/lib/enchant/libenchant_ispell.so
            )

        [3] => Array
            (
                [name] => myspell
                [desc] => Myspell Provider
                [file] => /usr/lib/enchant/libenchant_myspell.so
            )

    )

# enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

### Description

enchant_broker_dict_exists(EnchantBroker `$broker`, string `$tag`): bool

Tells if a dictionary exists or not, using a non-empty tags

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`tag`
  non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

### Return Values

Returns `true` when the tag exist or `false` when not.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

### Examples

Example #1 A enchant_broker_dict_exists() example

`<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
echo $tag . " dictionary found.\n";
}
?>`

### See Also

- enchant_broker_describe() - Enumerates the Enchant providers

# enchant_broker_free

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionaries

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
enchant_broker_free(EnchantBroker `$broker`): bool

Free a broker with all its dictionaries. As of PHP 8.0.0, it is recommended to unset the object instead of calling this function.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function has been deprecated in favor of unsetting the object.
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

### See Also

- enchant_broker_init() - Create a new broker object capable of requesting

# enchant_broker_free_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
enchant_broker_free_dict(EnchantDictionary `$dictionary`): bool

Free a dictionary. As of PHP 8.0.0, it is recommended to unset the object instead of calling this function.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function has been deprecated in favor of unsetting the object.
8.0.0 | `dictionary` expects a EnchantDictionary now; previoulsy, a resource was expected.

### See Also

- enchant_broker_request_dict() - Create a new dictionary using a tag
- enchant_broker_request_pwl_dict() - Creates a dictionary using a PWL file

# enchant_broker_get_dict_path

(PHP 5 >= 5.3.1, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_get_dict_path — Get the directory path for a given backend

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
enchant_broker_get_dict_path(EnchantBroker `$broker`, int `$type`): string|false

Get the directory path for a given backend.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`type`
  The type of the dictionaries, i.e. `ENCHANT_MYSPELL` or `ENCHANT_ISPELL`.

### Return Values

Returns the path of the dictionary directory on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function has been deprecated.
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

### Notes

> Note: This function is only available if the extension has been compiled with Enchant v1.

### See Also

- enchant_broker_set_dict_path() - Set the directory path for a given backend

# enchant_broker_get_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

### Description

enchant_broker_get_error(EnchantBroker `$broker`): string|false

Returns the last error which occurred in this broker.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

### Return Values

Return the msg string if an error was found or `false`

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

# enchant_broker_init

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_init — Create a new broker object capable of requesting

### Description

enchant_broker_init(): EnchantBroker|false

### Parameters

### Return Values

Returns a broker resource on success or `false`.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns an EnchantBroker instance now; previously, a resource was returned.

### See Also

- enchant_broker_free() - Free the broker resource and its dictionaries

# enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

### Description

enchant_broker_list_dicts(EnchantBroker `$broker`): array

Returns a list of available dictionaries with their details.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

### Return Values

Returns an array of available dictionaries with their details.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned `false` on failure.

### Examples

Example #1 List all available dictionaries for one broker

`<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>`

The above example will output something similar to:

    Array
    (
        [0] => Array
            (
                [lang_tag] => de
                [provider_name] => aspell
                [provider_desc] => Aspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [1] => Array
            (
                [lang_tag] => de_DE
                [provider_name] => aspell
                [provider_desc] => Aspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [3] => Array
            (
                [lang_tag] => en
                [provider_name] => aspell
                [provider_desc] => Aspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [4] => Array
            (
                [lang_tag] => en_GB
                [provider_name] => aspell
                [provider_desc] => Aspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [5] => Array
            (
                [lang_tag] => en_US
                [provider_name] => aspell
                [provider_desc] => Aspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_aspell.so
            )

        [6] => Array
            (
                [lang_tag] => hi_IN
                [provider_name] => myspell
                [provider_desc] => Myspell Provider
                [provider_file] => /usr/lib/enchant/libenchant_myspell.so
            )

    )

### See Also

- enchant_broker_describe() - Enumerates the Enchant providers

# enchant_broker_request_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — Create a new dictionary using a tag

### Description

enchant_broker_request_dict(EnchantBroker `$broker`, string `$tag`): EnchantDictionary|false

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`tag`
  A tag describing the locale, for example en_US, de_DE

### Return Values

Returns a dictionary resource on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | On success, this function returns an EnchantDictionary instance now; previously, a resource was returned.

### Examples

Example #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

`<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
$dict = enchant_broker_request_dict($broker, $tag);
var_dump($dict);
}
?>`

### See Also

- enchant_dict_describe() - Describes an individual dictionary
- enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
- enchant_broker_free_dict() - Free a dictionary resource

# enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file

### Description

enchant_broker_request_pwl_dict(EnchantBroker `$broker`, string `$filename`): EnchantDictionary|false

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`filename`
  Path to the PWL file. If there is no such file, a new one will be created if possible.

### Return Values

Returns a dictionary resource on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | On success, this function returns an EnchantDictionary instance now; previoulsy, a resource was retured.

### See Also

- enchant_dict_describe() - Describes an individual dictionary
- enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
- enchant_broker_free_dict() - Free a dictionary resource

# enchant_broker_set_dict_path

(PHP 5 >= 5.3.1, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_set_dict_path — Set the directory path for a given backend

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
enchant_broker_set_dict_path(EnchantBroker `$broker`, int `$type`, string `$path`): bool

Set the directory path for a given backend.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`type`
  The type of the dictionaries, i.e. `ENCHANT_MYSPELL` or `ENCHANT_ISPELL`.
`path`
  The path of the dictionary directory.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | This function has been deprecated.
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

### Notes

> Note: This function is only available if the extension has been compiled with Enchant v1.

### See Also

- enchant_broker_get_dict_path() - Get the directory path for a given backend

# enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

### Description

enchant_broker_set_ordering(EnchantBroker `$broker`, string `$tag`, string `$ordering`): bool

Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

### Parameters

`broker`

  An Enchant broker returned by enchant_broker_init().

`tag`
  Language tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.
`ordering`
  Comma delimited list of provider names

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `broker` expects an EnchantBroker instance now; previoulsy, a resource was expected.

# enchant_dict_add

(PHP 8)

enchant_dict_add — Add a word to personal word list

### Description

enchant_dict_add(EnchantDictionary `$dictionary`, string `$word`): void

Add a word to personal word list of the given dictionary.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  The word to add

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

### Examples

Example #1 Adding a word to a PWL

`<?php
$filename = './my_word_list.pwl';
$word = 'Supercalifragilisticexpialidocious';
$broker = enchant_broker_init();
$dict = enchant_broker_request_pwl_dict($broker, $filename);
enchant_dict_add($dict, $word);
?>`

### See Also

- enchant_broker_request_pwl_dict() - Creates a dictionary using a PWL file
- enchant_broker_request_dict() - Create a new dictionary using a tag

# enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — Alias of enchant_dict_add()

Warning

This alias is DEPRECATED as of PHP 8.0.0.

### Description

This function is an alias of: enchant_dict_add().

# enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — Add 'word' to this spell-checking session

### Description

enchant_dict_add_to_session(EnchantDictionary `$dictionary`, string `$word`): void

Add a word to the given dictionary. It will be added only for the active spell-checking session.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  The word to add

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

### See Also

- enchant_broker_request_dict() - Create a new dictionary using a tag

# enchant_dict_check

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

### Description

enchant_dict_check(EnchantDictionary `$dictionary`, string `$word`): bool

If the word is correctly spelled return `true`, otherwise return `false`

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  The word to check

### Return Values

Returns `true` if the word is spelled correctly, `false` if not.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

# enchant_dict_describe

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

### Description

enchant_dict_describe(EnchantDictionary `$dictionary`): array

Returns the details of the dictionary.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned `false` on failure.

### Examples

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

`<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker, $tag)) {
$dict = enchant_broker_request_dict($broker, $tag);
$dict_details = enchant_dict_describe($dict);
print_r($dict_details);
}
?>`

The above example will output something similar to:

    Array
    (
        [lang] => en_US
        [name] => aspell
        [desc] => Aspell Provider
        [file] => /usr/lib/enchant/libenchant_aspell.so
    )

# enchant_dict_get_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

### Description

enchant_dict_get_error(EnchantDictionary `$dictionary`): string|false

Returns the last error of the current spelling-session

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

### Return Values

Returns the error message as string or `false` if no error occurred.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

# enchant_dict_is_added

(PHP 8)

enchant_dict_is_added — Whether or not 'word' exists in this spelling-session

### Description

enchant_dict_is_added(EnchantDictionary `$dictionary`, string `$word`): bool

Tells whether or not a word already exists in the current session.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  The word to lookup

### Return Values

Returns `true` if the word exists or `false`

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

### See Also

- enchant_dict_add_to_session() - Add 'word' to this spell-checking session

# enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — Alias of enchant_dict_is_added()

Warning

This alias is DEPRECATED as of PHP 8.0.0.

### Description

This function is an alias of: enchant_dict_is_added().

# enchant_dict_quick_check

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

### Description

enchant_dict_quick_check(EnchantDictionary `$dictionary`, string `$word`, array `&$suggestions` = `null`): bool

If the word is correctly spelled return `true`, otherwise return `false`, if suggestions variable is provided, fill it with spelling alternatives.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  The word to check
`suggestions`
  If the word is not correctly spelled, this variable will contain an array of suggestions.

### Return Values

Returns `true` if the word is correctly spelled or `false`

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

### Examples

Example #1 A enchant_dict_quick_check() example

`<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
enchant_dict_quick_check($d, 'soong', $suggs);
print_r($suggs);
}
?>`

The above example will output something similar to:

    Array
    (
        [0] => song
        [1] => snog
        [2] => soon
        [3] => Sang
        [4] => Sung
        [5] => sang
        [6] => sung
        [7] => sponge
        [8] => spongy
        [9] => snag
        [10] => snug
        [11] => sonic
        [12] => sing
        [13] => songs
        [14] => Son
        [15] => Sonja
        [16] => Synge
        [17] => son
        [18] => Sejong
        [19] => sarong
        [20] => sooner
        [21] => Sony
        [22] => sown
        [23] => scone
        [24] => song's
    )

### See Also

- enchant_dict_check() - Check whether a word is correctly spelled or not
- enchant_dict_suggest() - Will return a list of values if any of those pre-conditions are not met

# enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

### Description

enchant_dict_store_replacement(EnchantDictionary `$dictionary`, string `$misspelled`, string `$correct`): void

Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`misspelled`
  The work to fix
`correct`
  The correct word

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

# enchant_dict_suggest

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

### Description

enchant_dict_suggest(EnchantDictionary `$dictionary`, string `$word`): array

### Parameters

`dictionary`

  An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

`word`
  Word to use for the suggestions.

### Return Values

Will returns an array of suggestions if the word is bad spelled.

### Changelog

Version | Description
--- | ---
8.0.0 | `dictionary` expects an EnchantDictionary instance now; previoulsy, a resource was expected.

### Examples

Example #1 A enchant_dict_suggest() example

`<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
$wordcorrect = enchant_dict_check($d, "soong");
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
}
?>`

### See Also

- enchant_dict_check() - Check whether a word is correctly spelled or not
- enchant_dict_quick_check() - Check the word is correctly spelled and provide suggestions

## Table of Contents

- enchant_broker_describe — Enumerates the Enchant providers
- enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
- enchant_broker_free — Free the broker resource and its dictionaries
- enchant_broker_free_dict — Free a dictionary resource
- enchant_broker_get_dict_path — Get the directory path for a given backend
- enchant_broker_get_error — Returns the last error of the broker
- enchant_broker_init — Create a new broker object capable of requesting
- enchant_broker_list_dicts — Returns a list of available dictionaries
- enchant_broker_request_dict — Create a new dictionary using a tag
- enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file
- enchant_broker_set_dict_path — Set the directory path for a given backend
- enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
- enchant_dict_add — Add a word to personal word list
- enchant_dict_add_to_personal — Alias of enchant_dict_add
- enchant_dict_add_to_session — Add 'word' to this spell-checking session
- enchant_dict_check — Check whether a word is correctly spelled or not
- enchant_dict_describe — Describes an individual dictionary
- enchant_dict_get_error — Returns the last error of the current spelling-session
- enchant_dict_is_added — Whether or not 'word' exists in this spelling-session
- enchant_dict_is_in_session — Alias of enchant_dict_is_added
- enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
- enchant_dict_store_replacement — Add a correction for a word
- enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

# The EnchantBroker class

(PHP 8)

## Introduction

A fully opaque class which replaces `enchant_broker` resources as of PHP 8.0.0.

## Class synopsis

final class EnchantBroker {
}

# The EnchantDictionary class

(PHP 8)

## Introduction

A fully opaque class which replaces `enchant_dict` resources as of PHP 8.0.0.

## Class synopsis

final class EnchantDictionary {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- Examples
- Enchant Functions
  - enchant_broker_describe — Enumerates the Enchant providers
  - enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
  - enchant_broker_free — Free the broker resource and its dictionaries
  - enchant_broker_free_dict — Free a dictionary resource
  - enchant_broker_get_dict_path — Get the directory path for a given backend
  - enchant_broker_get_error — Returns the last error of the broker
  - enchant_broker_init — Create a new broker object capable of requesting
  - enchant_broker_list_dicts — Returns a list of available dictionaries
  - enchant_broker_request_dict — Create a new dictionary using a tag
  - enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file
  - enchant_broker_set_dict_path — Set the directory path for a given backend
  - enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
  - enchant_dict_add — Add a word to personal word list
  - enchant_dict_add_to_personal — Alias of enchant_dict_add
  - enchant_dict_add_to_session — Add 'word' to this spell-checking session
  - enchant_dict_check — Check whether a word is correctly spelled or not
  - enchant_dict_describe — Describes an individual dictionary
  - enchant_dict_get_error — Returns the last error of the current spelling-session
  - enchant_dict_is_added — Whether or not 'word' exists in this spelling-session
  - enchant_dict_is_in_session — Alias of enchant_dict_is_added
  - enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
  - enchant_dict_store_replacement — Add a correction for a word
  - enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
- EnchantBroker — The EnchantBroker class
- EnchantDictionary — The EnchantDictionary class

# Determine gender of firstnames

# Introduction

Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.

# Installing/Configuring

## Table of Contents

- Installation

## Installation

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: » https://pecl.php.net/package/gender.

# Examples

## Table of Contents

- Usage example.

## Usage example.

Gender class usage example.

Example #1 Usage example.

`<?php
namespace Gender;
$gender = new Gender;
$name = "Milene";
$country = Gender::FRANCE;
$result = $gender->get($name, $country);
$data = $gender->country($country);
switch($result) {
case Gender::IS_FEMALE:
printf("The name %s is female in %s\n", $name, $data['country']);
break;
case Gender::IS_MOSTLY_FEMALE:
printf("The name %s is mostly female in %s\n", $name, $data['country']);
break;
case Gender::IS_MALE:
printf("The name %s is male in %s\n", $name, $data['country']);
break;
case Gender::IS_MOSTLY_MALE:
printf("The name %s is mostly male in %s\n", $name, $data['country']);
break;
case Gender::IS_UNISEX_NAME:
printf("The name %s is unisex in %s\n", $name, $data['country']);
break;
case Gender::IS_A_COUPLE:
printf("The name %s is both male and female in %s\n", $name, $data['country']);
break;
case Gender::NAME_NOT_FOUND:
printf("The name %s was not found for %s\n", $name, $data['country']);
break;
case Gender::ERROR_IN_NAME:
echo "There is an error in the given name!\n";
break;
default:
echo "An error occurred!\n";
break;
}`

# The Gender\Gender class

(PECL gender >= 0.6.0)

## Introduction

## Class synopsis

class Gender\Gender {
/* Constants */
const int IS_FEMALE = 70;
const int IS_MOSTLY_FEMALE = 102;
const int IS_MALE = 77;
const int IS_MOSTLY_MALE = 109;
const int IS_UNISEX_NAME = 63;
const int IS_A_COUPLE = 67;
const int NAME_NOT_FOUND = 32;
const int ERROR_IN_NAME = 69;
const int ANY_COUNTRY = 0;
const int BRITAIN = 1;
const int IRELAND = 2;
const int USA = 3;
const int SPAIN = 4;
const int PORTUGAL = 5;
const int ITALY = 6;
const int MALTA = 7;
const int FRANCE = 8;
const int BELGIUM = 9;
const int LUXEMBOURG = 10;
const int NETHERLANDS = 11;
const int GERMANY = 12;
const int EAST_FRISIA = 13;
const int AUSTRIA = 14;
const int SWISS = 15;
const int ICELAND = 16;
const int DENMARK = 17;
const int NORWAY = 18;
const int SWEDEN = 19;
const int FINLAND = 20;
const int ESTONIA = 21;
const int LATVIA = 22;
const int LITHUANIA = 23;
const int POLAND = 24;
const int CZECH_REP = 25;
const int SLOVAKIA = 26;
const int HUNGARY = 27;
const int ROMANIA = 28;
const int BULGARIA = 29;
const int BOSNIA = 30;
const int CROATIA = 31;
const int KOSOVO = 32;
const int MACEDONIA = 33;
const int MONTENEGRO = 34;
const int SERBIA = 35;
const int SLOVENIA = 36;
const int ALBANIA = 37;
const int GREECE = 38;
const int RUSSIA = 39;
const int BELARUS = 40;
const int MOLDOVA = 41;
const int UKRAINE = 42;
const int ARMENIA = 43;
const int AZERBAIJAN = 44;
const int GEORGIA = 45;
const int KAZAKH_UZBEK = 46;
const int TURKEY = 47;
const int ARABIA = 48;
const int ISRAEL = 49;
const int CHINA = 50;
const int INDIA = 51;
const int JAPAN = 52;
const int KOREA = 53;
/* Methods */
public __construct(string `$dsn` = ?)
public connect(string `$dsn`): bool
public country(int `$country`): array|false
public get(string `$name`, int `$country` = ?): int
public isNick(string `$name0`, string `$name1`, int `$country` = ?): array
public similarNames(string `$name`, int `$country` = ?): array
}

## Predefined Constants

`Gender\Gender::IS_FEMALE`
`Gender\Gender::IS_MOSTLY_FEMALE`
`Gender\Gender::IS_MALE`
`Gender\Gender::IS_MOSTLY_MALE`
`Gender\Gender::IS_UNISEX_NAME`
`Gender\Gender::IS_A_COUPLE`
`Gender\Gender::NAME_NOT_FOUND`
`Gender\Gender::ERROR_IN_NAME`
`Gender\Gender::ANY_COUNTRY`
`Gender\Gender::BRITAIN`
`Gender\Gender::IRELAND`
`Gender\Gender::USA`
`Gender\Gender::SPAIN`
`Gender\Gender::PORTUGAL`
`Gender\Gender::ITALY`
`Gender\Gender::MALTA`
`Gender\Gender::FRANCE`
`Gender\Gender::BELGIUM`
`Gender\Gender::LUXEMBOURG`
`Gender\Gender::NETHERLANDS`
`Gender\Gender::GERMANY`
`Gender\Gender::EAST_FRISIA`
`Gender\Gender::AUSTRIA`
`Gender\Gender::SWISS`
`Gender\Gender::ICELAND`
`Gender\Gender::DENMARK`
`Gender\Gender::NORWAY`
`Gender\Gender::SWEDEN`
`Gender\Gender::FINLAND`
`Gender\Gender::ESTONIA`
`Gender\Gender::LATVIA`
`Gender\Gender::LITHUANIA`
`Gender\Gender::POLAND`
`Gender\Gender::CZECH_REP`
`Gender\Gender::SLOVAKIA`
`Gender\Gender::HUNGARY`
`Gender\Gender::ROMANIA`
`Gender\Gender::BULGARIA`
`Gender\Gender::BOSNIA`
`Gender\Gender::CROATIA`
`Gender\Gender::KOSOVO`
`Gender\Gender::MACEDONIA`
`Gender\Gender::MONTENEGRO`
`Gender\Gender::SERBIA`
`Gender\Gender::SLOVENIA`
`Gender\Gender::ALBANIA`
`Gender\Gender::GREECE`
`Gender\Gender::RUSSIA`
`Gender\Gender::BELARUS`
`Gender\Gender::MOLDOVA`
`Gender\Gender::UKRAINE`
`Gender\Gender::ARMENIA`
`Gender\Gender::AZERBAIJAN`
`Gender\Gender::GEORGIA`
`Gender\Gender::KAZAKH_UZBEK`
`Gender\Gender::TURKEY`
`Gender\Gender::ARABIA`
`Gender\Gender::ISRAEL`
`Gender\Gender::CHINA`
`Gender\Gender::INDIA`
`Gender\Gender::JAPAN`
`Gender\Gender::KOREA`

# Gender\Gender::connect

(PECL gender >= 0.6.0)

Gender\Gender::connect — Connect to an external name dictionary

### Description

public Gender\Gender::connect(string `$dsn`): bool

Connect to an external name dictionary. Currently only streams are supported.

### Parameters

`dsn`
  DSN to open.

### Return Values

Boolean as success of failure.

# Gender\Gender::__construct

(PECL gender >= 0.6.0)

Gender\Gender::__construct — Construct the Gender object

### Description

public Gender\Gender::__construct(string `$dsn` = ?)

Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.

### Parameters

`dsn`
  DSN to open.

# Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::country — Get textual country representation

### Description

public Gender\Gender::country(int `$country`): array|false

Returns the textual representation of a country from a Gender class constant.

### Parameters

`country`
  A country ID specified by a Gender\Gender class constant.

### Return Values

Returns an array with the short and full names of the country on success or `false` on failure.

### Examples

Example #1 Using Gender\Gender::country()

`$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));`

The above example will output:

    array(2) {
      'country_short' =>
      string(2) "UK"
      'country' =>
      string(13) "Great Britain"
    }

# Gender\Gender::get

(PECL gender >= 0.6.0)

Gender\Gender::get — Get gender of a name

### Description

public Gender\Gender::get(string `$name`, int `$country` = ?): int

Get the gender of the name in a particular country.

### Parameters

`name`
  Name to check.
`country`
  Country id identified by Gender class constant.

### Return Values

Returns gender of the name.

# Gender\Gender::isNick

(PECL gender >= 0.9.0)

Gender\Gender::isNick — Check if the name0 is an alias of the name1

### Description

public Gender\Gender::isNick(string `$name0`, string `$name1`, int `$country` = ?): array

Check whether the name0 is a nick of the name1.

### Parameters

`name0`
  Name to check.
`name1`
  Name to check.
`country`
  Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

### Return Values

Returns `true` on success or `false` on failure.

# Gender\Gender::similarNames

(PECL gender >= 0.9.0)

Gender\Gender::similarNames — Get similar names

### Description

public Gender\Gender::similarNames(string `$name`, int `$country` = ?): array

Get similar names for the given name and country.

### Parameters

`name`
  Name to check.
`country`
  Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

### Return Values

Returns an array with the similar names found.

## Table of Contents

- Gender\Gender::connect — Connect to an external name dictionary
- Gender\Gender::__construct — Construct the Gender object
- Gender\Gender::country — Get textual country representation
- Gender\Gender::get — Get gender of a name
- Gender\Gender::isNick — Check if the name0 is an alias of the name1
- Gender\Gender::similarNames — Get similar names

- Installing/Configuring
  - Installation
- Examples
  - Usage example.
- Gender\Gender — The Gender\Gender class
  - Gender\Gender::connect — Connect to an external name dictionary
  - Gender\Gender::__construct — Construct the Gender object
  - Gender\Gender::country — Get textual country representation
  - Gender\Gender::get — Get gender of a name
  - Gender\Gender::isNick — Check if the name0 is an alias of the name1
  - Gender\Gender::similarNames — Get similar names

# Gettext

# Introduction

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at » http://www.gnu.org/software/gettext/manual/gettext.html.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html

## Installation

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.

# Gettext Functions

# _

(PHP 4, PHP 5, PHP 7, PHP 8)

_ — Alias of gettext()

### Description

This function is an alias of: gettext().

# bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned

### Description

bind_textdomain_codeset(string `$domain`, ?string `$codeset` = `null`): string|false

bind_textdomain_codeset() allows to set or get the encoding in which messages from `domain` will be returned by gettext() and similar functions.

### Parameters

`domain`

  The domain.

`codeset`

  The code set. If `null`, the currently set encoding is returned.

### Return Values

A string on success.

### Errors/Exceptions

Throws a ValueError if `domain` is the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `domain` is the empty string.
8.4.0 | `codeset` is optional now. Previously, the parameter always had to be specified.
8.0.3 | `codeset` is nullable now. Previously, it was not possible to retrieve the currently set encoding.

### Notes

> Note:

> The bind_textdomain_codeset() information is maintained per process, not per thread.

# bindtextdomain

(PHP 4, PHP 5, PHP 7, PHP 8)

bindtextdomain — Sets or gets the path for a domain

### Description

bindtextdomain(string `$domain`, ?string `$directory` = `null`): string|false

The bindtextdomain() function sets or gets the path for a domain.

### Parameters

`domain`

  The domain.

`directory`

  The directory path. An empty string means the current directory. If `null`, the currently set directory is returned.

### Return Values

The full pathname for the `domain` currently being set, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.4.0 | `directory` is optional now. Previously, the parameter always had to be specified.
8.0.3 | `directory` is nullable now. Previously, it was not possible to retrieve the currently set directory.

### Examples

Example #1 bindtextdomain() example

`<?php
$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');
?>`

The above example will output:

    /usr/share/myapp/locale

### Notes

> Note:

> The bindtextdomain() information is maintained per process, not per thread.

# dcgettext

(PHP 4, PHP 5, PHP 7, PHP 8)

dcgettext — Overrides the domain for a single lookup

### Description

dcgettext(string `$domain`, string `$message`, int `$category`): string

This function allows you to override the current domain for a single message lookup.

### Parameters

`domain`

  The domain

`message`

  The message

`category`

  The category

### Return Values

A string on success.

### See Also

- gettext() - Lookup a message in the current domain

# dcngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

dcngettext — Plural version of dcgettext

### Description

dcngettext(
string `$domain`,
string `$singular`,
string `$plural`,
int `$count`,
int `$category`
): string

This function allows you to override the current domain for a single plural message lookup.

### Parameters

`domain`

  The domain

`singular`

`plural`

`count`

`category`

### Return Values

A string on success.

### See Also

- ngettext() - Plural version of gettext

# dgettext

(PHP 4, PHP 5, PHP 7, PHP 8)

dgettext — Override the current domain

### Description

dgettext(string `$domain`, string `$message`): string

The dgettext() function allows you to override the current `domain` for a single message lookup.

### Parameters

`domain`

  The domain

`message`

  The message

### Return Values

A string on success.

### Errors/Exceptions

Throws a ValueError if `domain` is the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `domain` is the empty string.

### See Also

- gettext() - Lookup a message in the current domain

# dngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

dngettext — Plural version of dgettext

### Description

dngettext(
string `$domain`,
string `$singular`,
string `$plural`,
int `$count`
): string

The dngettext() function allows you to override the current `domain` for a single plural message lookup.

### Parameters

`domain`

  The domain

`singular`

`plural`

`count`

### Return Values

A string on success.

### Errors/Exceptions

Throws a ValueError if `domain` is the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `domain` is the empty string.

### See Also

- ngettext() - Plural version of gettext

# gettext

(PHP 4, PHP 5, PHP 7, PHP 8)

gettext — Lookup a message in the current domain

### Description

gettext(string `$message`): string

Looks up a message in the current domain.

### Parameters

`message`

  The message being translated.

### Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

### Examples

Example #1 gettext()-check

`<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');
// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");
// Choose domain
textdomain("myPHPApp");
// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now
// Print a test message
echo gettext("Welcome to My PHP Application");
// Or use the alias _() for gettext()
echo _("Have a nice day");
?>`

### Notes

> Note:

> You may use the underscore character '_' as an alias to this function.

> Note:

> Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

### See Also

- _() - Alias of gettext
- setlocale() - Set locale information

# ngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ngettext — Plural version of gettext

### Description

ngettext(string `$singular`, string `$plural`, int `$count`): string

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

### Parameters

`singular`

  The singular message ID.

`plural`

  The plural message ID.

`count`

  The number (e.g. item count) to determine the translation for the respective grammatical number.

### Return Values

Returns correct plural form of message identified by `singular` and `plural` for count `count`.

### Examples

Example #1 ngettext() example

`<?php
setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken
?>`

# textdomain

(PHP 4, PHP 5, PHP 7, PHP 8)

textdomain — Sets the default domain

### Description

textdomain(?string `$domain` = `null`): string

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

### Parameters

`domain`

  The new message domain, or `null` to get the current setting without changing it

### Return Values

If successful, this function returns the current message domain, after possibly changing it.

### Errors/Exceptions

Throws a ValueError if `domain` is the empty string.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `domain` is the empty string.
8.4.0 | `domain` is optional now. Previously, the parameter always had to be specified.

### Notes

> Note:

> The textdomain() information is maintained per process, not per thread.

## Table of Contents

- _ — Alias of gettext
- bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
- bindtextdomain — Sets or gets the path for a domain
- dcgettext — Overrides the domain for a single lookup
- dcngettext — Plural version of dcgettext
- dgettext — Override the current domain
- dngettext — Plural version of dgettext
- gettext — Lookup a message in the current domain
- ngettext — Plural version of gettext
- textdomain — Sets the default domain

- Installing/Configuring
  - Requirements
  - Installation
- Gettext Functions
  - _ — Alias of gettext
  - bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
  - bindtextdomain — Sets or gets the path for a domain
  - dcgettext — Overrides the domain for a single lookup
  - dcngettext — Plural version of dcgettext
  - dgettext — Override the current domain
  - dngettext — Plural version of dgettext
  - gettext — Lookup a message in the current domain
  - ngettext — Plural version of gettext
  - textdomain — Sets the default domain

# iconv

# Introduction

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the » GNU libiconv library. It will most likely end up with more consistent results.

This extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the » libiconv library installed in your system.

## Installation

This extension is enabled by default, although it may be disabled by compiling with --without-iconv.

The optional --with-iconv[=DIR] directive is used to specify the location of iconv on the system that PHP is being compiled on, otherwise only the default locations are scanned.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Iconv Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
iconv.input_encoding | "" | `INI_ALL` | Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | `INI_ALL` | Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | `INI_ALL` | Deprecated in PHP 5.6.0.

Here's a short explanation of the configuration directives.

Warning

Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.

`iconv.input_encoding` string
  Warning

  This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

  PHP 5.6 and later users should leave this empty and set input_encoding instead.

`iconv.output_encoding` string
  Warning

  This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

  PHP 5.6 and later users should leave this empty and set output_encoding instead.

`iconv.internal_encoding` string
  Warning

  This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

  PHP 5.6 and later users should leave this empty and set `default_charset` instead.

# Predefined Constants

It is possible to identify at runtime which `iconv` implementation is adopted by this extension.

`iconv` implementation constants
Name | Type | Description
--- | --- | ---
`ICONV_IMPL` (string) | string | The implementation name
`ICONV_VERSION` (string) | string | The implementation version

> Note:

> Writing implementation-dependent scripts with these constants is strongly discouraged.

The following constants are also available:

Other `iconv` constants
Name | Type | Description
--- | --- | ---
`ICONV_MIME_DECODE_STRICT` (int) | int | A bitmask used for iconv_mime_decode()
`ICONV_MIME_DECODE_CONTINUE_ON_ERROR` (int) | int | A bitmask used for iconv_mime_decode()

# iconv Functions

# See Also

See also GNU Recode functions.

# iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv — Convert a string from one character encoding to another

### Description

iconv(string `$from_encoding`, string `$to_encoding`, string `$string`): string|false

Converts `string` from `from_encoding` to `to_encoding`.

### Parameters

`from_encoding`

  The current encoding used to interpret `string`.

`to_encoding`

  The desired encoding of the result.

  If the string `//TRANSLIT` is appended to `to_encoding`, then transliteration is activated. This means that when a character can't be represented in the target charset, it may be approximated through one or several similarly looking characters. If the string `//IGNORE` is appended, characters that cannot be represented in the target charset are silently discarded. Otherwise, `E_NOTICE` is generated and the function will return `false`.

  Caution

  If and how `//TRANSLIT` works exactly depends on the system's iconv() implementation (cf. `ICONV_IMPL`). Some implementations are known to ignore `//TRANSLIT`, so the conversion is likely to fail for characters which are illegal for the `to_encoding`.

`string`

  The string to be converted.

### Return Values

Returns the converted string, or `false` on failure.

### Examples

Example #1 iconv() example

`<?php
$text = "This is the Euro symbol '€'.";
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
?>`

The above example will output something similar to:

    Original : This is the Euro symbol '€'.
    TRANSLIT : This is the Euro symbol 'EUR'.
    IGNORE   : This is the Euro symbol ''.
    Plain    :
    Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7

### Notes

> Note:

> The character encodings and options available depend on the installed implementation of iconv. If the argument to `from_encoding` or `to_encoding` is not supported on the current system, `false` will be returned.

### See Also

- mb_convert_encoding() - Convert a string from one character encoding to another
- UConverter::transcode() - Convert a string from one character encoding to another

# iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv_get_encoding — Retrieve internal configuration variables of iconv extension

### Description

iconv_get_encoding(string `$type` = "all"): array|string|false

Retrieve internal configuration variables of iconv extension.

### Parameters

`type`

  The value of the optional `type` can be:

  - all
  - input_encoding
  - output_encoding
  - internal_encoding

### Return Values

Returns the current value of the internal configuration variable if successful or `false` on failure.

If `type` is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

### Examples

Example #1 iconv_get_encoding() example

`<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>`

The above example will output:

    Array
    (
        [input_encoding] => ISO-8859-1
        [output_encoding] => ISO-8859-1
        [internal_encoding] => UTF-8
    )

### See Also

- iconv_set_encoding() - Set current setting for character encoding conversion
- ob_iconv_handler() - Convert character encoding as output buffer handler

# iconv_mime_decode

(PHP 5, PHP 7, PHP 8)

iconv_mime_decode — Decodes a `MIME` header field

### Description

iconv_mime_decode(string `$string`, int `$mode` = 0, ?string `$encoding` = `null`): string|false

Decodes a `MIME` header field.

### Parameters

`string`

  The encoded header, as a string.

`mode`

  `mode` determines the behaviour in the event iconv_mime_decode() encounters a malformed `MIME` header field. You can specify any combination of the following bitmasks.

  Bitmasks acceptable to iconv_mime_decode()
  Value | Constant | Description
  --- | --- | ---
  1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct `MIME` headers.
  2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

`encoding`

  The optional `encoding` parameter specifies the character set to represent the result by. If omitted or `null`, iconv.internal_encoding will be used.

### Return Values

Returns a decoded `MIME` field on success, or `false` if an error occurs during the decoding.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 iconv_mime_decode() example

`<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
0, "ISO-8859-1");
?>`

### See Also

- iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
- mb_decode_mimeheader() - Decode string in MIME header field
- imap_mime_header_decode() - Decode MIME header elements
- imap_base64() - Decode BASE64 encoded text
- imap_qprint() - Convert a quoted-printable string to an 8 bit string

# iconv_mime_decode_headers

(PHP 5, PHP 7, PHP 8)

iconv_mime_decode_headers — Decodes multiple `MIME` header fields at once

### Description

iconv_mime_decode_headers(string `$headers`, int `$mode` = 0, ?string `$encoding` = `null`): array|false

Decodes multiple `MIME` header fields at once.

### Parameters

`headers`

  The encoded headers, as a string.

`mode`

  `mode` determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed `MIME` header field. You can specify any combination of the following bitmasks.

  Bitmasks acceptable to iconv_mime_decode_headers()
  Value | Constant | Description
  --- | --- | ---
  1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct `MIME` headers.
  2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

`encoding`

  The optional `encoding` parameter specifies the character set to represent the result by. If omitted or `null`, iconv.internal_encoding will be used.

### Return Values

Returns an associative array that holds a whole set of `MIME` header fields specified by `headers` on success, or `false` if an error occurs during the decoding.

Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence. Note that header names are not case-insensitive.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 iconv_mime_decode_headers() example

`<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
with SMTP id example for <example@example.com>;
Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
(envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
EOF;
$headers = iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>`

The above example will output:

    Array
    (
        [Subject] => Prüfung Prüfung
        [To] => example@example.com
        [Date] => Thu, 1 Jan 1970 00:00:00 +0000
        [Message-Id] => <example@example.com>
        [Received] => Array
            (
                [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
                [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
            )

    )

### See Also

- iconv_mime_decode() - Decodes a MIME header field
- mb_decode_mimeheader() - Decode string in MIME header field
- imap_mime_header_decode() - Decode MIME header elements
- imap_base64() - Decode BASE64 encoded text
- imap_qprint() - Convert a quoted-printable string to an 8 bit string

# iconv_mime_encode

(PHP 5, PHP 7, PHP 8)

iconv_mime_encode — Composes a `MIME` header field

### Description

iconv_mime_encode(string `$field_name`, string `$field_value`, array `$options` = []): string|false

Composes and returns a string that represents a valid `MIME` header field, which looks like the following:

    Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile

In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

### Parameters

`field_name`

  The field name.

`field_value`

  The field value.

`options`

  You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter `options`. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.

  Configuration items supported by iconv_mime_encode()
  Item | Type | Description | Default value | Example
  --- | --- | --- | --- | ---
  scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for `base64` encoding scheme and "Q" stands for `quoted-printable` encoding scheme. | B | B
  input-charset | string | Specifies the character set in which the first parameter `field_name` and the second parameter `field_value` are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. | iconv.internal_encoding | ISO-8859-1
  output-charset | string | Specifies the character set to use to compose the `MIME` header. | iconv.internal_encoding | UTF-8
  line-length | int | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996
  line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (`CR` `LF`). Note that this parameter is always treated as an ASCII string regardless of the value of `input-charset`. | \r\n | \n

### Return Values

Returns an encoded `MIME` field on success, or `false` if an error occurs during the encoding.

### Examples

Example #1 iconv_mime_encode() example

`<?php
$preferences = array(
"input-charset" => "ISO-8859-1",
"output-charset" => "UTF-8",
"line-length" => 76,
"line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>`

### See Also

- imap_binary() - Convert an 8bit string to a base64 string
- mb_encode_mimeheader() - Encode string for MIME header
- imap_8bit() - Convert an 8bit string to a quoted-printable string
- quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

# iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv_set_encoding — Set current setting for character encoding conversion

### Description

iconv_set_encoding(string `$type`, string `$encoding`): bool

Changes the value of the internal configuration variable specified by `type` to `encoding`.

### Parameters

`type`

  The value of `type` can be any one of these:

  - input_encoding
  - output_encoding
  - internal_encoding
`encoding`

  The character set.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 iconv_set_encoding() example

`<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>`

### See Also

- iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
- ob_iconv_handler() - Convert character encoding as output buffer handler

# iconv_strlen

(PHP 5, PHP 7, PHP 8)

iconv_strlen — Returns the character count of string

### Description

iconv_strlen(string `$string`, ?string `$encoding` = `null`): int|false

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence `string` on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in bytes.

### Parameters

`string`

  The string.

`encoding`

  If `encoding` parameter is omitted or `null`, `string` is assumed to be encoded in iconv.internal_encoding.

### Return Values

Returns the character count of `string`, as an integer, or `false` if an error occurs during the encoding.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- grapheme_strlen() - Get string length in grapheme units
- mb_strlen() - Get string length
- strlen() - Get string length

# iconv_strpos

(PHP 5, PHP 7, PHP 8)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

### Description

iconv_strpos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
?string `$encoding` = `null`
): int|false

Finds position of first occurrence of a `needle` within a `haystack`.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set `encoding`.

### Parameters

`haystack`

  The entire string.

`needle`

  The searched substring.

`offset`

  The optional `offset` parameter specifies the position from which the search should be performed. If the offset is negative, it is counted from the end of the string.

`encoding`

  If `encoding` parameter is omitted or `null`, `string` are assumed to be encoded in iconv.internal_encoding.

If `haystack` or `needle` is not a string, it is converted to a string and applied as the ordinal value of a character.

### Return Values

Returns the numeric position of the first occurrence of `needle` in `haystack`.

If `needle` is not found, iconv_strpos() will return `false`.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.
7.1.0 | Support for negative `offset`s has been added.

### See Also

- strpos() - Find the position of the first occurrence of a substring in a string
- iconv_strrpos() - Finds the last occurrence of a needle within a haystack
- mb_strpos() - Find position of first occurrence of string in a string

# iconv_strrpos

(PHP 5, PHP 7, PHP 8)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

### Description

iconv_strrpos(string `$haystack`, string `$needle`, ?string `$encoding` = `null`): int|false

Finds the last occurrence of a `needle` within a `haystack`.

In contrast to strrpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set `encoding`.

### Parameters

`haystack`

  The entire string.

`needle`

  The searched substring.

`encoding`

  If `encoding` parameter is omitted or `null`, `string` are assumed to be encoded in iconv.internal_encoding.

If `haystack` or `needle` is not a string, it is converted to a string and applied as the ordinal value of a character.

### Return Values

Returns the numeric position of the last occurrence of `needle` in `haystack`.

If `needle` is not found, iconv_strrpos() will return `false`.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- strrpos() - Find the position of the last occurrence of a substring in a string
- iconv_strpos() - Finds position of first occurrence of a needle within a haystack
- mb_strrpos() - Find position of last occurrence of a string in a string

# iconv_substr

(PHP 5, PHP 7, PHP 8)

iconv_substr — Cut out part of a string

### Description

iconv_substr(
string `$string`,
int `$offset`,
?int `$length` = `null`,
?string `$encoding` = `null`
): string|false

Cuts a portion of `string` specified by the `offset` and `length` parameters.

### Parameters

`string`

  The original string.

`offset`

  If `offset` is non-negative, iconv_substr() cuts the portion out of `string` beginning at `offset`'th character, counting from zero.

  If `offset` is negative, iconv_substr() cuts out the portion beginning at the position, `offset` characters away from the end of `string`.

`length`

  If `length` is given and is positive, the return value will contain at most `length` characters of the portion that begins at `offset` (depending on the length of `string`).

  If negative `length` is passed, iconv_substr() cuts the portion out of `string` from the `offset`'th character up to the character that is `length` characters away from the end of the string. In case `offset` is also negative, the start position is calculated beforehand according to the rule explained above.

`encoding`

  If `encoding` parameter is omitted or `null`, `string` are assumed to be encoded in iconv.internal_encoding.

  Note that `offset` and `length` parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by `encoding`, whilst the counterpart substr() always takes these for byte offsets.

### Return Values

Returns the portion of `string` specified by the `offset` and `length` parameters.

If `string` is shorter than `offset` characters long, `false` will be returned. If `string` is exactly `offset` characters long, an empty string will be returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `length` and `encoding` are nullable now.
7.0.11 | If `string` is equal to `offset` characters long, an empty string will be returned. Prior to this version, `false` was returned in this case.

### See Also

- substr() - Return part of a string
- mb_substr() - Get part of string
- mb_strcut() - Get part of string

# ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ob_iconv_handler — Convert character encoding as output buffer handler

### Description

ob_iconv_handler(string `$contents`, int `$status`): string

Converts the string encoded in `internal_encoding` to `output_encoding`.

`internal_encoding` and `output_encoding` should be defined in the php.ini file or in iconv_set_encoding().

### Parameters

See ob_start() for information about this handler parameters.

### Return Values

See ob_start() for information about this handler return values.

### Examples

Example #1 ob_iconv_handler() example:

`<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>`

### See Also

- iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
- iconv_set_encoding() - Set current setting for character encoding conversion
- output-control functions

## Table of Contents

- iconv — Convert a string from one character encoding to another
- iconv_get_encoding — Retrieve internal configuration variables of iconv extension
- iconv_mime_decode — Decodes a MIME header field
- iconv_mime_decode_headers — Decodes multiple MIME header fields at once
- iconv_mime_encode — Composes a MIME header field
- iconv_set_encoding — Set current setting for character encoding conversion
- iconv_strlen — Returns the character count of string
- iconv_strpos — Finds position of first occurrence of a needle within a haystack
- iconv_strrpos — Finds the last occurrence of a needle within a haystack
- iconv_substr — Cut out part of a string
- ob_iconv_handler — Convert character encoding as output buffer handler

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- iconv Functions
  - iconv — Convert a string from one character encoding to another
  - iconv_get_encoding — Retrieve internal configuration variables of iconv extension
  - iconv_mime_decode — Decodes a MIME header field
  - iconv_mime_decode_headers — Decodes multiple MIME header fields at once
  - iconv_mime_encode — Composes a MIME header field
  - iconv_set_encoding — Set current setting for character encoding conversion
  - iconv_strlen — Returns the character count of string
  - iconv_strpos — Finds position of first occurrence of a needle within a haystack
  - iconv_strrpos — Finds the last occurrence of a needle within a haystack
  - iconv_substr — Cut out part of a string
  - ob_iconv_handler — Convert character encoding as output buffer handler

# Internationalization Functions

# Introduction

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform various locale-aware operations including but not limited to formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes.

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

- Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
- Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
- Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them. It can handle plurals, locale-aware numbers, currencies, conditions and much more.
- Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
- Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.
- Calendar: provides a class which could be used for locale-aware calendar operations and getting various information such as timezone for locale chosen, first day of week or if it's daylight saving time now.
- Timezone: provides a wrapper around the » "Olson" database which has information about all the timezones around the world.
- Date formatter: allows to display date and time according to the localized format or given pattern or set of rules, and to parse strings into date and time.
- Transliterator: allows getting latin representation of strings in various languages.

## Links

- » Miscellaneous ICU docs

- » ICU User Guide

- » Unicode Collation Algorithm

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

To build the extension you need to install the » ICU library, version 4.0.0 or newer is required. As of PHP 7.4.0 ICU 50.1 or newer is required.

## Installation

--enable-intl will enable the extension while compiling PHP.

If your ICU is installed to a non-standard directory then you might want to specify its location in `LD_LIBRARY_PATH` environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to configure are not needed.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Intl Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
intl.default_locale |  | `INI_ALL` |
intl.error_level | 0 | `INI_ALL` |
intl.use_exceptions | 0 | `INI_ALL` | Available since PECL 3.0.0a1

Here's a short explanation of the configuration directives.

`intl.default_locale` string

  The locale that will be used in intl functions when none is specified (either by omitting the corresponding argument or by passing `NULL`). These are ICU locales, not system locales. The built-in ICU locales and their data can be explored at » https://unicode-org.github.io/icu/userguide/locale/.

  The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.

`intl.error_level` int

  The type of the error messages generated when an error occurs in ICU functions. This is a PHP error level, such as `E_WARNING`. It can be set to `0` in order to inhibit the messages. This does not affect the return values indicating error or the values returned by intl_get_error_code() or by the class specific methods for retrieving error codes and messages.

  The default value is `0`.

`intl.use_exceptions` int

  If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.

  The default value is `false`.

# Predefined Constants

`INTL_ICU_DATA_VERSION` (string)
  Data version in ICU4C.
`INTL_ICU_VERSION` (string)
  The current ICU library version as a dotted-decimal string.
`INTL_MAX_LOCALE_LEN` (int)
  Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
`IDNA_DEFAULT` (int)
  Prohibit processing of unassigned codepoints in the input for IDN functions and do not check if the input conforms to domain name ASCII rules.
`IDNA_ALLOW_UNASSIGNED` (int)
  Allow processing of unassigned codepoints in the input for IDN functions.
`IDNA_USE_STD3_RULES` (int)
  Check if the input for IDN functions conforms to domain name ASCII rules.
`IDNA_CHECK_BIDI` (int)
  Check whether the input conforms to the BiDi rules. Ignored by the IDNA2003 implementation, which always performs this check.
`IDNA_CHECK_CONTEXTJ` (int)
  Check whether the input conforms to the CONTEXTJ rules. Ignored by the IDNA2003 implementation, as this check is new in IDNA2008.
`IDNA_NONTRANSITIONAL_TO_ASCII` (int)
  Option for nontransitional processing in idn_to_ascii(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
`IDNA_NONTRANSITIONAL_TO_UNICODE` (int)
  Option for nontransitional processing in idn_to_utf8(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
`INTL_IDNA_VARIANT_2003` (int)
  Use IDNA 2003 algorithm in idn_to_utf8() and idn_to_ascii(). This is the default. This constant and using the default has been deprecated as of PHP 7.2.0.
`INTL_IDNA_VARIANT_UTS46` (int)
  Use UTS #46 algorithm in idn_to_utf8() and idn_to_ascii(). Available as of ICU 4.6.
`GRAPHEME_EXTR_COUNT` (int)
  The number of default grapheme clusters to extract.
`GRAPHEME_EXTR_MAXBYTES` (int)
  The maximum number of bytes returned.
`GRAPHEME_EXTR_MAXCHARS` (int)
  The maximum number of UTF-8 characters returned.

The following errors are part of a bitmask returned by the UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().

`IDNA_ERROR_EMPTY_LABEL` (int)
`IDNA_ERROR_LABEL_TOO_LONG` (int)
`IDNA_ERROR_DOMAIN_NAME_TOO_LONG` (int)
`IDNA_ERROR_LEADING_HYPHEN` (int)
`IDNA_ERROR_TRAILING_HYPHEN` (int)
`IDNA_ERROR_HYPHEN_3_4` (int)
`IDNA_ERROR_LEADING_COMBINING_MARK` (int)
`IDNA_ERROR_DISALLOWED` (int)
`IDNA_ERROR_PUNYCODE` (int)
`IDNA_ERROR_LABEL_HAS_DOT` (int)
`IDNA_ERROR_INVALID_ACE_LABEL` (int)
`IDNA_ERROR_BIDI` (int)
`IDNA_ERROR_CONTEXTJ` (int)
`ULOC_ACTUAL_LOCALE` (int)
  The locale the data actually comes from.
`ULOC_VALID_LOCALE` (int)
  The most specific locale supported by ICU.
`U_AMBIGUOUS_ALIAS_WARNING` (int)
  This converter alias can go to different converter implementations.
`U_BAD_VARIABLE_DEFINITION` (int)
  Missing `'$'` or duplicate variable name.
`U_BRK_ASSIGN_ERROR` (int)
  Syntax error in RBBI rule assignment statement.
`U_BRK_ERROR_LIMIT` (int)
  This must always be the last value to indicate the limit for Break Iterator failures.
`U_BRK_ERROR_START` (int)
  Start of codes indicating Break Iterator failures.
`U_BRK_HEX_DIGITS_EXPECTED` (int)
  Hex digits expected as part of a escaped char in a rule.
`U_BRK_INIT_ERROR` (int)
  Initialization failure. Probable missing ICU Data.
`U_BRK_INTERNAL_ERROR` (int)
  An internal error (bug) was detected.
`U_BRK_MALFORMED_RULE_TAG` (int)
  The `{nnn}` tag on a rule is mal formed.
`U_BRK_MISMATCHED_PAREN` (int)
  Mis-matched parentheses in an RBBI rule.
`U_BRK_NEW_LINE_IN_QUOTED_STRING` (int)
  Missing closing quote in an RBBI rule.
`U_BRK_RULE_EMPTY_SET` (int)
  Rule contains an empty Unicode Set.
`U_BRK_RULE_SYNTAX` (int)
  Syntax error in RBBI rule.
`U_BRK_SEMICOLON_EXPECTED` (int)
  Missing `';'` at the end of a RBBI rule.
`U_BRK_UNCLOSED_SET` (int)
  UnicodeSet writing an RBBI rule missing a closing `']'`.
`U_BRK_UNDEFINED_VARIABLE` (int)
  Use of an undefined `$Variable` in an RBBI rule.
`U_BRK_UNRECOGNIZED_OPTION` (int)
  Option in RBBI rules not recognized.
`U_BRK_VARIABLE_REDFINITION` (int)
  RBBI rule variable redefined.
`U_BUFFER_OVERFLOW_ERROR` (int)
  A result would not fit in the supplied buffer.
`U_CE_NOT_FOUND_ERROR` (int)
  Currently used only while setting variable top, but can be used generally.
`U_COLLATOR_VERSION_MISMATCH` (int)
  Collator version is not compatible with the base version.
`U_DIFFERENT_UCA_VERSION` (int)
  ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function.
`U_ENUM_OUT_OF_SYNC_ERROR` (int)
  `UEnumeration` out of sync with underlying collection.
`U_ERROR_LIMIT` (int)
  Alias of `U_PLUGIN_ERROR_LIMIT`.
`U_ERROR_WARNING_LIMIT` (int)
  This must always be the last warning value to indicate the limit for UErrorCode warnings (last warning code +1).
`U_ERROR_WARNING_START` (int)
  Start of information results (semantically successful).
`U_FILE_ACCESS_ERROR` (int)
  The requested file cannot be found.
`U_FMT_PARSE_ERROR_LIMIT` (int)
  The limit for format library errors.
`U_FMT_PARSE_ERROR_START` (int)
  Start of format library errors.
`U_IDNA_ACE_PREFIX_ERROR` (int)
`U_IDNA_CHECK_BIDI_ERROR` (int)
`U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR` (int)
`U_IDNA_ERROR_LIMIT` (int)
`U_IDNA_ERROR_START` (int)
`U_IDNA_LABEL_TOO_LONG_ERROR` (int)
`U_IDNA_PROHIBITED_ERROR` (int)
`U_IDNA_STD3_ASCII_RULES_ERROR` (int)
`U_IDNA_UNASSIGNED_ERROR` (int)
`U_IDNA_VERIFICATION_ERROR` (int)
`U_IDNA_ZERO_LENGTH_LABEL_ERROR` (int)
`U_ILLEGAL_ARGUMENT_ERROR` (int)
  Indicates an incorrect argument value.
`U_ILLEGAL_CHAR_FOUND` (int)
  Character conversion: Illegal input sequence.
`U_ILLEGAL_CHAR_IN_SEGMENT` (int)
  Unused as of ICU 2.4.
`U_ILLEGAL_CHARACTER` (int)
  A special character is outside its allowed context.
`U_ILLEGAL_ESCAPE_SEQUENCE` (int)
  ISO-2022 illlegal escape sequence.
`U_ILLEGAL_PAD_POSITION` (int)
  Pad symbol misplaced in number pattern.
`U_INDEX_OUTOFBOUNDS_ERROR` (int)
  Trying to access the index that is out of bounds.
`U_INTERNAL_PROGRAM_ERROR` (int)
  Indicates a bug in the library code.
`U_INTERNAL_TRANSLITERATOR_ERROR` (int)
  Internal transliterator system error.
`U_INVALID_CHAR_FOUND` (int)
  Character conversion: Unmappable input sequence. In other APIs: Invalid character.
`U_INVALID_FORMAT_ERROR` (int)
  Data format is not what is expected.
`U_INVALID_FUNCTION` (int)
  A `'&fn()'` rule specifies an unknown transliterator.
`U_INVALID_ID` (int)
  A `'::id'` rule specifies an unknown transliterator.
`U_INVALID_PROPERTY_PATTERN` (int)
  Unused as of ICU 2.4.
`U_INVALID_RBT_SYNTAX` (int)
  A `'::id'` rule was passed to the RuleBasedTransliterator parser.
`U_INVALID_STATE_ERROR` (int)
  Requested operation can not be completed with ICU in its current state.
`U_INVALID_TABLE_FILE` (int)
  Conversion table file not found.
`U_INVALID_TABLE_FORMAT` (int)
  Conversion table file found, but corrupted.
`U_INVARIANT_CONVERSION_ERROR` (int)
  Unable to convert a `UChar*` string to `char*` with the invariant converter.
`U_MALFORMED_EXPONENTIAL_PATTERN` (int)
  Grouping symbol in exponent pattern.
`U_MALFORMED_PRAGMA` (int)
  A `'use'` pragma is invalid.
`U_MALFORMED_RULE` (int)
  Elements of a rule are misplaced.
`U_MALFORMED_SET` (int)
  A `UnicodeSet` pattern is invalid.
`U_MALFORMED_SYMBOL_REFERENCE` (int)
  Unused as of ICU 2.4.
`U_MALFORMED_UNICODE_ESCAPE` (int)
  A Unicode escape pattern is invalid.
`U_MALFORMED_VARIABLE_DEFINITION` (int)
  A variable definition is invalid.
`U_MALFORMED_VARIABLE_REFERENCE` (int)
  A variable reference is invalid.
`U_MEMORY_ALLOCATION_ERROR` (int)
  Memory allocation error.
`U_MESSAGE_PARSE_ERROR` (int)
  Unable to parse a message (message format).
`U_MISMATCHED_SEGMENT_DELIMITERS` (int)
  Unused as of ICU 2.4.
`U_MISPLACED_ANCHOR_START` (int)
  A start anchor appears at an illegal position.
`U_MISPLACED_COMPOUND_FILTER` (int)
  A compound filter is in an invalid location.
`U_MISPLACED_CURSOR_OFFSET` (int)
  A cursor offset occurs at an illegal position.
`U_MISPLACED_QUANTIFIER` (int)
  A quantifier appears after a segment close delimiter.
`U_MISSING_OPERATOR` (int)
  A rule contains no operator.
`U_MISSING_RESOURCE_ERROR` (int)
  The requested resource cannot be found.
`U_MISSING_SEGMENT_CLOSE` (int)
  Unused as of ICU 2.4.
`U_MULTIPLE_ANTE_CONTEXTS` (int)
  More than one ante context.
`U_MULTIPLE_COMPOUND_FILTERS` (int)
  More than one compound filter.
`U_MULTIPLE_CURSORS` (int)
  More than one cursor.
`U_MULTIPLE_DECIMAL_SEPARATORS` (int)
  More than one decimal separator in number pattern.
`U_MULTIPLE_DECIMAL_SEPERATORS` (int)
  Alias of `U_MULTIPLE_DECIMAL_SEPARATORS`.
`U_MULTIPLE_EXPONENTIAL_SYMBOLS` (int)
  More than one exponent symbol in number pattern.
`U_MULTIPLE_PAD_SPECIFIERS` (int)
  More than one pad symbol in number pattern.
`U_MULTIPLE_PERCENT_SYMBOLS` (int)
  More than one percent symbol in number pattern.
`U_MULTIPLE_PERMILL_SYMBOLS` (int)
  More than one permill symbol in number pattern.
`U_MULTIPLE_POST_CONTEXTS` (int)
  More than one post context.
`U_NO_SPACE_AVAILABLE` (int)
  No space available for in-buffer expansion for Arabic shaping.
`U_NO_WRITE_PERMISSION` (int)
  Attempt to modify read-only or constant data.
`U_PARSE_ERROR` (int)
  Equivalent to Java `ParseException`.
`U_PARSE_ERROR_LIMIT` (int)
  The limit for Transliterator errors.
`U_PARSE_ERROR_START` (int)
  Start of Transliterator errors.
`U_PATTERN_SYNTAX_ERROR` (int)
  Syntax error in format pattern.
`U_PRIMARY_TOO_LONG_ERROR` (int)
  User tried to set variable top to a primary that is longer than two bytes.
`U_REGEX_BAD_ESCAPE_SEQUENCE` (int)
  Unrecognized backslash escape sequence in pattern.
`U_REGEX_BAD_INTERVAL` (int)
  Error in `{min,max}` interval.
`U_REGEX_ERROR_LIMIT` (int)
  This must always be the last value to indicate the limit for regexp errors.
`U_REGEX_ERROR_START` (int)
  Start of codes indicating Regexp failures.
`U_REGEX_INTERNAL_ERROR` (int)
  An internal error (bug) was detected.
`U_REGEX_INVALID_BACK_REF` (int)
  Back-reference to a non-existent capture group.
`U_REGEX_INVALID_FLAG` (int)
  Invalid value for match mode flags.
`U_REGEX_INVALID_STATE` (int)
  `RegexMatcher` in invalid state for requested operation.
`U_REGEX_LOOK_BEHIND_LIMIT` (int)
  Look-Behind pattern matches must have a bounded maximum length.
`U_REGEX_MAX_LT_MIN` (int)
  In `{min,max}`, max is less than min.
`U_REGEX_MISMATCHED_PAREN` (int)
  Incorrectly nested parentheses in regexp pattern.
`U_REGEX_NUMBER_TOO_BIG` (int)
  Decimal number is too large.
`U_REGEX_PROPERTY_SYNTAX` (int)
  Incorrect Unicode property.
`U_REGEX_RULE_SYNTAX` (int)
  Syntax error in regexp pattern.
`U_REGEX_SET_CONTAINS_STRING` (int)
  Regexps cannot have `UnicodeSet`s containing strings.
`U_REGEX_UNIMPLEMENTED` (int)
  Use of regexp feature that is not yet implemented.
`U_RESOURCE_TYPE_MISMATCH` (int)
  An operation is requested over a resource that does not support it.
`U_RULE_MASK_ERROR` (int)
  A rule is hidden by an earlier more general rule.
`U_SAFECLONE_ALLOCATED_WARNING` (int)
  A `SafeClone` operation required allocating memory (informational only).
`U_SORT_KEY_TOO_SHORT_WARNING` (int)
  Number of levels requested in `getBound` is higher than the number of levels in the sort key.
`U_STANDARD_ERROR_LIMIT` (int)
  This must always be the last value to indicate the limit for standard errors.
`U_STATE_OLD_WARNING` (int)
  ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation.
`U_STATE_TOO_OLD_ERROR` (int)
  ICU cannot construct a service from this state, as it is no longer supported.
`U_STRING_NOT_TERMINATED_WARNING` (int)
  An output string could not be NUL-terminated because output `length==destCapacity`.
`U_STRINGPREP_CHECK_BIDI_ERROR` (int)
  Alias of `U_IDNA_CHECK_BIDI_ERROR`.
`U_STRINGPREP_PROHIBITED_ERROR` (int)
  Alias of `U_IDNA_PROHIBITED_ERROR`.
`U_STRINGPREP_UNASSIGNED_ERROR` (int)
  Alias of `U_IDNA_UNASSIGNED_ERROR`.
`U_TOO_MANY_ALIASES_ERROR` (int)
  There are too many aliases in the path to the requested resource. It is very possible that a circular alias definition has occurred.
`U_TRAILING_BACKSLASH` (int)
  A dangling backslash.
`U_TRUNCATED_CHAR_FOUND` (int)
  Character conversion: Incomplete input sequence.
`U_UNCLOSED_SEGMENT` (int)
  A closing `')'` is missing.
`U_UNDEFINED_SEGMENT_REFERENCE` (int)
  A segment reference does not correspond to a defined segment.
`U_UNDEFINED_VARIABLE` (int)
  A variable reference does not correspond to a defined variable.
`U_UNEXPECTED_TOKEN` (int)
  Syntax error in format pattern.
`U_UNMATCHED_BRACES` (int)
  Braces do not match in message pattern.
`U_UNQUOTED_SPECIAL` (int)
  A special character was not quoted or escaped.
`U_UNSUPPORTED_ATTRIBUTE` (int)
  Unused as of ICU 2.4.
`U_UNSUPPORTED_ERROR` (int)
  Requested operation not supported in current context.
`U_UNSUPPORTED_ESCAPE_SEQUENCE` (int)
  ISO-2022 unsupported escape sequence.
`U_UNSUPPORTED_PROPERTY` (int)
  Unused as of ICU 2.4.
`U_UNTERMINATED_QUOTE` (int)
  A closing single quote is missing.
`U_USELESS_COLLATOR_ERROR` (int)
  Collator is options only and no base is specified.
`U_USING_DEFAULT_WARNING` (int)
  A resource bundle lookup returned a result from the root locale (not an error).
`U_USING_FALLBACK_WARNING` (int)
  A resource bundle lookup returned a fallback result (not an error).
`U_VARIABLE_RANGE_EXHAUSTED` (int)
  Too many stand-ins generated for the given variable range.
`U_VARIABLE_RANGE_OVERLAP` (int)
  The variable range overlaps characters used in rules.
`U_ZERO_ERROR` (int)
  No error, no warning.

# Examples

## Table of Contents

- Basic usage of this extension

## Basic usage of this extension

Each module provides two kind of APIs: a procedural one and an object oriented one. Both are actually identical and described in the corresponding document.

> Note:

> All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Example #1 Example of using the procedural API

`<?php
$coll = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>`

Example #2 Example of using the object-oriented API

`<?php
$coll = new Collator('en_US');
$al = $coll->getLocale(Locale::ACTUAL_LOCALE);
echo "Actual locale: $al\n";
$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567);
?>`

# The Collator class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

## Class synopsis

class Collator {
/* Constants */
public const int DEFAULT_VALUE;
public const int PRIMARY;
public const int SECONDARY;
public const int TERTIARY;
public const int DEFAULT_STRENGTH;
public const int QUATERNARY;
public const int IDENTICAL;
public const int OFF;
public const int ON;
public const int SHIFTED;
public const int NON_IGNORABLE;
public const int LOWER_FIRST;
public const int UPPER_FIRST;
public const int FRENCH_COLLATION;
public const int ALTERNATE_HANDLING;
public const int CASE_FIRST;
public const int CASE_LEVEL;
public const int NORMALIZATION_MODE;
public const int STRENGTH;
public const int HIRAGANA_QUATERNARY_MODE;
public const int NUMERIC_COLLATION;
public const int SORT_REGULAR;
public const int SORT_STRING;
public const int SORT_NUMERIC;
/* Methods */
public __construct(string `$locale`)
public asort(array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool
public compare(string `$string1`, string `$string2`): int|false
public static create(string `$locale`): ?Collator
public getAttribute(int `$attribute`): int|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public getLocale(int `$type`): string|false
public getSortKey(string `$string`): string|false
public getStrength(): int
public setAttribute(int `$attribute`, int `$value`): bool
public setStrength(int `$strength`): true
public sort(array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool
public sortWithSortKeys(array `&$array`): bool
}

## Predefined Constants

`Collator::FRENCH_COLLATION` int

  Sort strings with different accents from the back of the string. This attribute is automatically set to On for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set On, but sort key length is unaffected. Possible values are:

  - `Collator::ON`
  - `Collator::OFF`(default)
  - `Collator::DEFAULT_VALUE`

  Example #1 FRENCH_COLLATION rules

  - F=OFF cote < coté < côte < côté
  - F=ON cote < côte < coté < côté
`Collator::ALTERNATE_HANDLING`

  The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to NonIgnorable (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to Shifted (S), then these characters are of only minor importance. The Shifted value is often used in combination with Strength set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable_Weighting in the » UCA. The reason the Alternate values are not simply On and Off is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased.

  Possible values are:

  - `Collator::NON_IGNORABLE`(default)
  - `Collator::SHIFTED`
  - `Collator::DEFAULT_VALUE`

  Example #2 ALTERNATE_HANDLING rules

  - S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA
  - S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA
  - S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA
`Collator::CASE_FIRST` int

  The Case_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are Uppercase_First (U) and Lowercase_First (L), plus the standard Default and Off. There is almost no difference between the Off and Lowercase_First options in terms of results, so typically users will not use Lowercase_First: only Off or Uppercase_First. (People interested in the detailed differences between X and L should consult the `Collation Customization`). Specifying either L or U won't affect string comparison performance, but will affect the sort key length.

  Possible values are:

  - `Collator::OFF`(default)
  - `Collator::LOWER_FIRST`
  - `Collator::UPPER_FIRST`
  - `Collator:DEFAULT`

  Example #3 CASE_FIRST rules

  - C=X or C=L "china" < "China" < "denmark" < "Denmark"
  - C=U "China" < "china" < "Denmark" < "denmark"
`Collator::CASE_LEVEL` int

  The Case_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be Primary, and Case_Level to be On. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be On.

  Possible values are:

  - `Collator::OFF`(default)
  - `Collator::ON`
  - `Collator::DEFAULT_VALUE`

  Example #4 CASE_LEVEL rules

  - S=1, E=X role = Role = rôle
  - S=1, E=O role = rôle < Role
`Collator::NORMALIZATION_MODE` int

  The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is On, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is On, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option.

  Possible values are:

  - `Collator::OFF`(default)
  - `Collator::ON`
  - `Collator::DEFAULT_VALUE`
`Collator::STRENGTH` int

  The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see collator_set_strength() chapter.

  Possible values are:

  - `Collator::PRIMARY`
  - `Collator::SECONDARY`
  - `Collator::TERTIARY`(default)
  - `Collator::QUATERNARY`
  - `Collator::IDENTICAL`
  - `Collator::DEFAULT_VALUE`
`Collator::HIRAGANA_QUATERNARY_MODE` int

  Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set On, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance.

  Possible values are:

  - `Collator::OFF`(default)
  - `Collator::ON`
  - `Collator::DEFAULT_VALUE`
`Collator::NUMERIC_COLLATION` int

  When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'.

  Possible values are:

  - `Collator::OFF`(default)
  - `Collator::ON`
  - `Collator::DEFAULT_VALUE`
`Collator::DEFAULT_VALUE` int
`Collator::PRIMARY` int
`Collator::SECONDARY` int
`Collator::TERTIARY` int
`Collator::DEFAULT_STRENGTH` int
`Collator::QUATERNARY` int
`Collator::IDENTICAL` int
`Collator::OFF` int
`Collator::ON` int
`Collator::SHIFTED` int
`Collator::NON_IGNORABLE` int
`Collator::LOWER_FIRST` int
`Collator::UPPER_FIRST` int
`Collator::SORT_REGULAR` int

`Collator::SORT_STRING` int

`Collator::SORT_NUMERIC` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# Collator::asort

# collator_asort

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

### Description

Object-oriented style

public Collator::asort(array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool

Procedural style

collator_asort(Collator `$object`, array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Array elements will have sort order according to current locale rules.

Equivalent to standard PHP asort().

### Parameters

`object`

  Collator object.

`array`

  Array of strings to sort.

`flags`

  Optional sorting type, one of the following:

  - `Collator::SORT_REGULAR` - compare items normally (don't change types)

  - `Collator::SORT_NUMERIC` - compare items numerically

  - `Collator::SORT_STRING` - compare items as strings

  Default `flags` value is `Collator::SORT_REGULAR`. It is also used if an invalid `flags` value has been specified.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 collator_asort() example

`<?php
$coll = collator_create( 'en_US' );
$arr = array(
'a' => '100',
'b' => '50',
'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );
collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>`

The above example will output:

    array (
      'c' => '7',
      'b' => '50',
      'a' => '100',
    )array (
      'a' => '100',
      'b' => '50',
      'c' => '7',
    )

### See Also

- Collator constants
- collator_sort() - Sort array using specified collator
- collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

# Collator::compare

# collator_compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

### Description

Object-oriented style

public Collator::compare(string `$string1`, string `$string2`): int|false

Procedural style

collator_compare(Collator `$object`, string `$string1`, string `$string2`): int|false

Compare two Unicode strings according to collation rules.

### Parameters

`object`

  Collator object.

`string1`

  The first string to compare.

`string2`

  The second string to compare.

### Return Values

Return comparison result:

- 1 if `string1` is greater than `string2` ;

- 0 if `string1` is equal to `string2`;

- -1 if `string1` is less than `string2` .

Returns `false` on failure.
Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Examples

Example #1 collator_compare() example

`<?php
$s1 = 'Hello';
$s2 = 'hello';
$coll = collator_create( 'en_US' );
$res = collator_compare( $coll, $s1, $s2 );
if ($res === false) {
echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
echo "s1 is less than s2\n";
} else {
echo "s1 is equal to s2\n";
}
?>`

The above example will output:

s1 is greater than s2

Example #2 Comparing strings without diacritics or case-sensitivity

`<?php
$c = new Collator( 'en' );
$c->setStrength( Collator::PRIMARY );
if ( $c->compare( 'Séan', 'Sean' ) == 0 )
{
echo "The same\n";
}`

The above example will output:

The same

This example instructs the collator to compare with only taking the base characters into account. The documentation for Collator->setStrength() explains the different strengths.

### See Also

- collator_sort() - Sort array using specified collator

# Collator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

### Description

public Collator::__construct(string `$locale`)

Creates a new instance of Collator.

### Parameters

`locale`

  The locale whose collation rules should be used. Special values for locales can be passed in - if an empty string is passed for the locale, the default locale's collation rules will be used. If `"root"` is passed, » UCA rules will be used.

  The `locale` attribute is typically the most important attribute for correct sorting and matching, according to the user expectations in different countries and regions. The default » UCA ordering will only sort a few languages such as Dutch and Portuguese correctly ("correctly" meaning according to the normal expectations for users of the languages). Otherwise, you need to supply the locale to UCA in order to properly collate text for a given language. Thus a locale needs to be supplied so as to choose a collator that is correctly tailored for that locale. The choice of a locale will automatically preset the values for all of the attributes to something that is reasonable for that locale. Thus most of the time the other attributes do not need to be explicitly set. In some cases, the choice of locale will make a difference in string comparison performance and/or sort key length.

### Errors/Exceptions

Returns an "empty" object on error. Use intl_get_error_code() and/or intl_get_error_message() to know what happened.

### Examples

Example #1 Collator::__construct() example

`<?php
$coll = new Collator('en_CA');
?>`

### See Also

- Collator::create() - Create a collator
- collator_create() - Create a collator

# Collator::create

# collator_create

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

### Description

Object-oriented style

public static Collator::create(string `$locale`): ?Collator

Procedural style

collator_create(string `$locale`): ?Collator

The strings will be compared using the options already specified.

### Parameters

`locale`

  The locale containing the required collation rules. Special values for locales can be passed in - if an empty string is passed for the locale, the default locale collation rules will be used. If `"root"` is passed, » UCA rules will be used.

### Return Values

Return new instance of Collator object, or `null` on error.

### Examples

Example #1 collator_create() example

`<?php
$coll = collator_create( 'en_US' );
if( !isset( $coll ) ) {
printf( "Collator creation failed: %s\n", intl_get_error_message() );
exit( 1 );
}
?>`

### See Also

- Collator::__construct() - Create a collator

# Collator::getAttribute

# collator_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

### Description

Object-oriented style

public Collator::getAttribute(int `$attribute`): int|false

Procedural style

collator_get_attribute(Collator `$object`, int `$attribute`): int|false

Get a value of an integer collator attribute.

### Parameters

`object`

  Collator object.

`attribute`

  Attribute to get value for.

### Return Values

Attribute value, or `false` on failure.

### Examples

Example #1 collator_get_attribute() example

`<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
// Handle error.
}
?>`

### See Also

- Collator constants
- collator_set_attribute() - Set collation attribute
- collator_get_strength() - Get current collation strength

# Collator::getErrorCode

# collator_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

### Description

Object-oriented style

public Collator::getErrorCode(): int|false

Procedural style

collator_get_error_code(Collator `$object`): int|false

### Parameters

`object`

  Collator object.

### Return Values

Error code returned by the last Collator API function call, or `false` on failure.

### Examples

Example #1 collator_get_error_code() example

`<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
handle_error( collator_get_error_code() );
?>`

### See Also

- collator_get_error_message() - Get text for collator's last error code

# Collator::getErrorMessage

# collator_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

### Description

Object-oriented style

public Collator::getErrorMessage(): string|false

Procedural style

collator_get_error_message(Collator `$object`): string|false

Retrieves the message for the last error.

### Parameters

`object`

  Collator object.

### Return Values

Description of an error occurred in the last Collator API function call, or `false` on failure.

### Examples

Example #1 collator_get_error_message() example

`<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
echo collator_get_error_message( $coll );
}
?>`

### See Also

- collator_get_error_code() - Get collator's last error code

# Collator::getLocale

# collator_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

### Description

Object-oriented style

public Collator::getLocale(int `$type`): string|false

Procedural style

collator_get_locale(Collator `$object`, int `$type`): string|false

Get collector locale name.

### Parameters

`object`

  Collator object.

`type`

  You can choose between valid and actual locale ( `Locale::VALID_LOCALE` and `Locale::ACTUAL_LOCALE`, respectively).

### Return Values

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns `false`.

### Examples

Example #1 collator_get_locale() example

`<?php
$coll = collator_create( 'en_US_California' );
$res_val = collator_get_locale( $coll, Locale::VALID_LOCALE );
$res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE );
printf( "Valid locale name: %s\nActual locale name: %s\n",
$res_val, $res_act );
?>`

The above example will output:

    Requested locale name: en_US_California
    Valid locale name: en_US
    Actual locale name: en

### See Also

- collator_create() - Create a collator

# Collator::getSortKey

# collator_get_sort_key

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 1.0.3)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

### Description

Object-oriented style

public Collator::getSortKey(string `$string`): string|false

Procedural style

collator_get_sort_key(Collator `$object`, string `$string`): string|false

Return collation key for a string. Collation keys can be compared directly instead of strings, though are implementation specific and may change between ICU library versions. Sort keys are generally only useful in databases or other circumstances where function calls are extremely expensive.

### Parameters

`object`

  Collator object.

`string`

  The string to produce the key from.

### Return Values

Returns the collation key for the string, or `false` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Examples

Example #1 collator_get_sort_key() example

`<?php
$s1 = 'Hello';
$coll = collator_create('en_US');
$res = collator_get_sort_key($coll, $s1);
echo bin2hex($res);
?>`

The above example will output something similar to:

3832404046010901dc08

Example #2 Collator::getSortKey() example with usort()

`<?php
$data = [
[ 'name' => '🇳🇱 Derick Rethans', 'linked_account' => 'https://phpc.social/users/derickr' ],
[ 'name' => 'Elephpant', 'linked_account' => 'https://phpc.social/phpc' ],
[ 'name' => '🇫🇷 Marcus Bointon', 'linked_account' => 'https://phpc.social/users/Synchro' ],
];
/* Create the collator */
$col = new Collator('en');
/* Sort upper-case letters before lower-case letters */
$col->setAttribute(Collator::CASE_FIRST, Collator::UPPER_FIRST);
/* Use a user-defined function with sort, that strips out the emojis */
usort(
$data,
function($a, $b) use ($col) {
/* Remove the character class 'S' (the Symbols), and remove whitespace
* (with trim) */
$aName = trim(preg_replace('/\p{S}+/u', '', $a['name']));
$bName = trim(preg_replace('/\p{S}+/u', '', $b['name']));
/* Create the sort key */
$aKey = $col->getSortKey($aName);
$bKey = $col->getSortKey($bName);
/* Use the sort key to signal which element sorts first */
return $aKey <=> $bKey;
}
);
var_dump($data);
?>`

The above example will output something similar to:

array(3) {
[0] =>
array(2) {
'name' =>
string(25) "🇳🇱 Derick Rethans"
'linked_account' =>
string(33) "https://phpc.social/users/derickr"
}
[1] =>
array(2) {
'name' =>
string(9) "Elephpant"
'linked_account' =>
string(24) "https://phpc.social/phpc"
}
[2] =>
array(2) {
'name' =>
string(25) "🇫🇷 Marcus Bointon"
'linked_account' =>
string(33) "https://phpc.social/users/Synchro"
}
}

### See Also

- collator_sort() - Sort array using specified collator
- collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

# Collator::getStrength

# collator_get_strength

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

### Description

Object-oriented style

public Collator::getStrength(): int

Procedural style

collator_get_strength(Collator `$object`): int

### Parameters

`object`

  Collator object.

### Return Values

Returns current collation strength, or `false` on failure.

### Examples

Example #1 collator_get_strength() example

`<?php
$coll = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>`

### See Also

- Collator constants
- collator_set_strength() - Set collation strength
- collator_get_attribute() - Get collation attribute value

# Collator::setAttribute

# collator_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

### Description

Object-oriented style

public Collator::setAttribute(int `$attribute`, int `$value`): bool

Procedural style

collator_set_attribute(Collator `$object`, int `$attribute`, int `$value`): bool

### Parameters

`object`

  Collator object.

`attribute`

  Attribute.

`value`

  Attribute value.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 collator_set_attribute() example

`<?php
$coll = collator_create('en_CA');
collator_set_attribute($coll, Collator::NORMALIZATION_MODE, Collator::ON);
?>`

### See Also

- Collator constants
- collator_get_attribute() - Get collation attribute value
- collator_set_strength() - Set collation strength

# Collator::setStrength

# collator_set_strength

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

### Description

Object-oriented style

public Collator::setStrength(int `$strength`): true

Procedural style

collator_set_strength(Collator `$object`, int `$strength`): true

The » ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.

1. Primary Level: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the `level 1` strength.

2. Secondary Level: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the `level 2` strength.

   > Note:

   > Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.

3. Tertiary Level: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "a" and "𝒶"). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the `level 3` strength.

4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at levels 1-3, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the `level 4` strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).

5. Identical Level: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 1-4. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as `level 5` strength.

For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.

### Parameters

`object`

  Collator object.

`strength`

  Strength to set.

  Possible values are:

  - `Collator::PRIMARY`

  - `Collator::SECONDARY`

  - `Collator::TERTIARY`

  - `Collator::QUATERNARY`

  - `Collator::IDENTICAL`

  - `Collator::DEFAULT_STRENGTH`

### Return Values

Always returns `true`.

### Examples

Example #1 collator_set_strength() example

`<?php
$arr = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );
// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );
// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>`

The above example will output:

    array (
      0 => 'ao',
      1 => 'Ao',
      2 => 'aò',
    )
    array (
      0 => 'aò',
      1 => 'Ao',
      2 => 'ao',
    )

### See Also

- Collator constants
- collator_get_strength() - Get current collation strength

# Collator::sort

# collator_sort

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

### Description

Object-oriented style

public Collator::sort(array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool

Procedural style

collator_sort(Collator `$object`, array `&$array`, int `$flags` = `Collator::SORT_REGULAR`): bool

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

### Parameters

`object`

  Collator object.

`array`

  Array of strings to sort.

`flags`

  Optional sorting type, one of the following:

  - `Collator::SORT_REGULAR` - compare items normally (don't change types)

  - `Collator::SORT_NUMERIC` - compare items numerically

  - `Collator::SORT_STRING` - compare items as strings

  Default sorting type is `Collator::SORT_REGULAR`. It is also used if an invalid `flags` value has been specified.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 collator_sort() example

`<?php
$coll = collator_create( 'en_US' );
$arr = array( 'at', 'às', 'as' );
var_export( $arr );
collator_sort( $coll, $arr );
var_export( $arr );
?>`

The above example will output:

    array (
      0 => 'at',
      1 => 'às',
      2 => 'as',
    )array (
      0 => 'as',
      1 => 'às',
      2 => 'at',
    )

### See Also

- Collator constants
- collator_asort() - Sort array maintaining index association
- collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

# Collator::sortWithSortKeys

# collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

### Description

Object-oriented style

public Collator::sortWithSortKeys(array `&$array`): bool

Procedural style

collator_sort_with_sort_keys(Collator `$object`, array `&$array`): bool

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

### Parameters

`object`

  Collator object.

`array`

  Array of strings to sort

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 collator_sort_with_sort_keys() example

`<?php
$arr = array( 'Köpfe', 'Kypper', 'Kopfe' );
$coll = collator_create( 'sv' );
collator_sort_with_sort_keys( $coll, $arr );
var_export( $arr );
?>`

The above example will output:

    array (
      0 => 'Kopfe',
      1 => 'Kypper',
      2 => 'Köpfe',
    )

### See Also

- Collator constants
- collator_sort() - Sort array using specified collator
- collator_asort() - Sort array maintaining index association

## Table of Contents

- Collator::asort — Sort array maintaining index association
- Collator::compare — Compare two Unicode strings
- Collator::__construct — Create a collator
- Collator::create — Create a collator
- Collator::getAttribute — Get collation attribute value
- Collator::getErrorCode — Get collator's last error code
- Collator::getErrorMessage — Get text for collator's last error code
- Collator::getLocale — Get the locale name of the collator
- Collator::getSortKey — Get sorting key for a string
- Collator::getStrength — Get current collation strength
- Collator::setAttribute — Set collation attribute
- Collator::setStrength — Set collation strength
- Collator::sort — Sort array using specified collator
- Collator::sortWithSortKeys — Sort array using specified collator and sort keys

# The NumberFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

- 9 988 776,65 € in France
- 9.988.776,65 € in Germany
- $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

## Class synopsis

class NumberFormatter {
/* Constants */
public const int PATTERN_DECIMAL;
public const int DECIMAL;
public const int DECIMAL_COMPACT_SHORT;
public const int DECIMAL_COMPACT_LONG;
public const int CURRENCY;
public const int PERCENT;
public const int SCIENTIFIC;
public const int SPELLOUT;
public const int ORDINAL;
public const int DURATION;
public const int PATTERN_RULEBASED;
public const int IGNORE;
public const int CURRENCY_ISO;
public const int CURRENCY_PLURAL;
public const int CURRENCY_ACCOUNTING;
public const int CASH_CURRENCY;
public const int CURRENCY_STANDARD;
public const int DEFAULT_STYLE;
public const int ROUND_CEILING;
public const int ROUND_FLOOR;
public const int ROUND_DOWN;
public const int ROUND_UP;
public const int ROUND_TOWARD_ZERO;
public const int ROUND_AWAY_FROM_ZERO;
public const int ROUND_HALFEVEN;
public const int ROUND_HALFODD;
public const int ROUND_HALFDOWN;
public const int ROUND_HALFUP;
public const int PAD_BEFORE_PREFIX;
public const int PAD_AFTER_PREFIX;
public const int PAD_BEFORE_SUFFIX;
public const int PAD_AFTER_SUFFIX;
public const int PARSE_INT_ONLY;
public const int GROUPING_USED;
public const int DECIMAL_ALWAYS_SHOWN;
public const int MAX_INTEGER_DIGITS;
public const int MIN_INTEGER_DIGITS;
public const int INTEGER_DIGITS;
public const int MAX_FRACTION_DIGITS;
public const int MIN_FRACTION_DIGITS;
public const int FRACTION_DIGITS;
public const int MULTIPLIER;
public const int GROUPING_SIZE;
public const int ROUNDING_MODE;
public const int ROUNDING_INCREMENT;
public const int FORMAT_WIDTH;
public const int PADDING_POSITION;
public const int SECONDARY_GROUPING_SIZE;
public const int SIGNIFICANT_DIGITS_USED;
public const int MIN_SIGNIFICANT_DIGITS;
public const int MAX_SIGNIFICANT_DIGITS;
public const int LENIENT_PARSE;
public const int POSITIVE_PREFIX;
public const int POSITIVE_SUFFIX;
public const int NEGATIVE_PREFIX;
public const int NEGATIVE_SUFFIX;
public const int PADDING_CHARACTER;
public const int CURRENCY_CODE;
public const int DEFAULT_RULESET;
public const int PUBLIC_RULESETS;
public const int DECIMAL_SEPARATOR_SYMBOL;
public const int GROUPING_SEPARATOR_SYMBOL;
public const int PATTERN_SEPARATOR_SYMBOL;
public const int PERCENT_SYMBOL;
public const int ZERO_DIGIT_SYMBOL;
public const int DIGIT_SYMBOL;
public const int MINUS_SIGN_SYMBOL;
public const int PLUS_SIGN_SYMBOL;
public const int CURRENCY_SYMBOL;
public const int INTL_CURRENCY_SYMBOL;
public const int MONETARY_SEPARATOR_SYMBOL;
public const int EXPONENTIAL_SYMBOL;
public const int PERMILL_SYMBOL;
public const int PAD_ESCAPE_SYMBOL;
public const int INFINITY_SYMBOL;
public const int NAN_SYMBOL;
public const int SIGNIFICANT_DIGIT_SYMBOL;
public const int MONETARY_GROUPING_SEPARATOR_SYMBOL;
public const int TYPE_DEFAULT;
public const int TYPE_INT32;
public const int TYPE_INT64;
public const int TYPE_DOUBLE;
public const int TYPE_CURRENCY;
/* Methods */
public __construct(string `$locale`, int `$style`, ?string `$pattern` = `null`)
public static create(string `$locale`, int `$style`, ?string `$pattern` = `null`): ?NumberFormatter
public format(int|float `$num`, int `$type` = `NumberFormatter::TYPE_DEFAULT`): string|false
public formatCurrency(float `$amount`, string `$currency`): string|false
public getAttribute(int `$attribute`): int|float|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int `$type` = `ULOC_ACTUAL_LOCALE`): string|false
public getPattern(): string|false
public getSymbol(int `$symbol`): string|false
public getTextAttribute(int `$attribute`): string|false
public parse(string `$string`, int `$type` = `NumberFormatter::TYPE_DOUBLE`, int `&$offset` = `null`): int|float|false
public parseCurrency(string `$string`, string `&$currency`, int `&$offset` = `null`): float|false
public setAttribute(int `$attribute`, int|float `$value`): bool
public setPattern(string `$pattern`): bool
public setSymbol(int `$symbol`, string `$value`): bool
public setTextAttribute(int `$attribute`, string `$value`): bool
}

## Predefined Constants

## Format Types

These styles are used by the numfmt_create() to define the type of the formatter.

`NumberFormatter::PATTERN_DECIMAL` int
  Decimal format defined by pattern
`NumberFormatter::DECIMAL` int
  Decimal format
`NumberFormatter::DECIMAL_COMPACT_SHORT` int
  Decimal format expressed using compact notation (short form), e.g. "23K", "45B". Available as of PHP 8.5.0 and ICU 56.
`NumberFormatter::DECIMAL_COMPACT_LONG` int
  Decimal format expressed using compact notation (long form), e.g. "23 thousand", "45 billion". Available as of PHP 8.5.0 and ICU 56.
`NumberFormatter::CURRENCY` int
  Currency format
`NumberFormatter::CURRENCY_ISO` int
  ISO currency format (e.g., "USD1.00"). Available as of PHP 8.5.0.
`NumberFormatter::CURRENCY_PLURAL` int
  Pluralized currency format (e.g., "1.00 US dollar" and "3.00 US dollars"). Available as of PHP 8.5.0.
`NumberFormatter::CASH_CURRENCY` int
  Currency symbol given CASH usage, e.g., "NT$3" instead of "NT$3.23". Available as of PHP 8.5.0 and ICU 54
`NumberFormatter::CURRENCY_STANDARD` int
  Currency symbol, e.g., "$1.00", using non-accounting style for negative values (e.g. minus sign). Available as of PHP 8.5.0 and ICU 56.
`NumberFormatter::PERCENT` int
  Percent format
`NumberFormatter::SCIENTIFIC` int
  Scientific format
`NumberFormatter::SPELLOUT` int
  Spellout rule-based format
`NumberFormatter::ORDINAL` int
  Ordinal rule-based format
`NumberFormatter::DURATION` int
  Duration rule-based format
`NumberFormatter::PATTERN_RULEBASED` int
  Rule-based format defined by pattern
`NumberFormatter::CURRENCY_ACCOUNTING` int
  Currency format for accounting, e.g., `($3.00)` for negative currency amount instead of `-$3.00`. Available as of PHP 7.4.1 and ICU 53.
`NumberFormatter::DEFAULT_STYLE` int
  Default format for the locale
`NumberFormatter::IGNORE` int
  Alias for PATTERN_DECIMAL

## Number Format Specifiers

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

`NumberFormatter::TYPE_DEFAULT` int
  Derive the type from variable type
`NumberFormatter::TYPE_INT32` int
  Format/parse as 32-bit integer
`NumberFormatter::TYPE_INT64` int
  Format/parse as 64-bit integer
`NumberFormatter::TYPE_DOUBLE` int
  Format/parse as floating point value
`NumberFormatter::TYPE_CURRENCY` int
  Format/parse as currency value. Deprecated as of PHP 8.3.0

## Number Format Attributes

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

`NumberFormatter::PARSE_INT_ONLY` int
  Parse integers only.
`NumberFormatter::GROUPING_USED` int
  Use grouping separator.
`NumberFormatter::DECIMAL_ALWAYS_SHOWN` int
  Always show decimal point.
`NumberFormatter::MAX_INTEGER_DIGITS` int
  Maximum integer digits.
`NumberFormatter::MIN_INTEGER_DIGITS` int
  Minimum integer digits.
`NumberFormatter::INTEGER_DIGITS` int
  Integer digits.
`NumberFormatter::MAX_FRACTION_DIGITS` int
  Maximum fraction digits.
`NumberFormatter::MIN_FRACTION_DIGITS` int
  Minimum fraction digits.
`NumberFormatter::FRACTION_DIGITS` int
  Fraction digits.
`NumberFormatter::MULTIPLIER` int
  Multiplier.
`NumberFormatter::GROUPING_SIZE` int
  Grouping size.
`NumberFormatter::ROUNDING_MODE` int
  Rounding Mode.
`NumberFormatter::ROUNDING_INCREMENT` int
  Rounding increment.
`NumberFormatter::FORMAT_WIDTH` int
  The width to which the output of format() is padded.
`NumberFormatter::PADDING_POSITION` int
  The position at which padding will take place. See pad position constants for possible argument values.
`NumberFormatter::SECONDARY_GROUPING_SIZE` int
  Secondary grouping size.
`NumberFormatter::SIGNIFICANT_DIGITS_USED` int
  Use significant digits.
`NumberFormatter::MIN_SIGNIFICANT_DIGITS` int
  Minimum significant digits.
`NumberFormatter::MAX_SIGNIFICANT_DIGITS` int
  Maximum significant digits.
`NumberFormatter::LENIENT_PARSE` int
  Lenient parse mode used by rule-based formats.

## Number Format Text Attributes

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

`NumberFormatter::POSITIVE_PREFIX` int
  Positive prefix.
`NumberFormatter::POSITIVE_SUFFIX` int
  Positive suffix.
`NumberFormatter::NEGATIVE_PREFIX` int
  Negative prefix.
`NumberFormatter::NEGATIVE_SUFFIX` int
  Negative suffix.
`NumberFormatter::PADDING_CHARACTER` int
  The character used to pad to the format width.
`NumberFormatter::CURRENCY_CODE` int
  The ISO currency code.
`NumberFormatter::DEFAULT_RULESET` int
  The default rule set. This is only available with rule-based formatters.
`NumberFormatter::PUBLIC_RULESETS` int
  The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

## Symbol Format Specifiers

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

`NumberFormatter::DECIMAL_SEPARATOR_SYMBOL` int
  The decimal separator.
`NumberFormatter::GROUPING_SEPARATOR_SYMBOL` int
  The grouping separator.
`NumberFormatter::PATTERN_SEPARATOR_SYMBOL` int
  The pattern separator.
`NumberFormatter::PERCENT_SYMBOL` int
  The percent sign.
`NumberFormatter::ZERO_DIGIT_SYMBOL` int
  Zero.
`NumberFormatter::DIGIT_SYMBOL` int
  Character representing a digit in the pattern.
`NumberFormatter::MINUS_SIGN_SYMBOL` int
  The minus sign.
`NumberFormatter::PLUS_SIGN_SYMBOL` int
  The plus sign.
`NumberFormatter::CURRENCY_SYMBOL` int
  The currency symbol.
`NumberFormatter::INTL_CURRENCY_SYMBOL` int
  The international currency symbol.
`NumberFormatter::MONETARY_SEPARATOR_SYMBOL` int
  The monetary separator.
`NumberFormatter::EXPONENTIAL_SYMBOL` int
  The exponential symbol.
`NumberFormatter::PERMILL_SYMBOL` int
  Per mill symbol.
`NumberFormatter::PAD_ESCAPE_SYMBOL` int
  Escape padding character.
`NumberFormatter::INFINITY_SYMBOL` int
  Infinity symbol.
`NumberFormatter::NAN_SYMBOL` int
  Not-a-number symbol.
`NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL` int
  Significant digit symbol.
`NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL` int
  The monetary grouping separator.

## Rounding Modes

Rounding mode values used by numfmt_get_attribute() and numfmt_set_attribute() with `NumberFormatter::ROUNDING_MODE` attribute.

`NumberFormatter::ROUND_AWAY_FROM_ZERO`
  Alias of `NumberFormatter::ROUND_UP`.
`NumberFormatter::ROUND_CEILING` int
  Rounding mode to round towards positive infinity.
`NumberFormatter::ROUND_DOWN` int
  Rounding mode to round towards zero.
`NumberFormatter::ROUND_FLOOR` int
  Rounding mode to round towards negative infinity.
`NumberFormatter::ROUND_HALFDOWN` int
  Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
`NumberFormatter::ROUND_HALFEVEN` int
  Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
`NumberFormatter::ROUND_HALFODD`
  Rounding mode to round towards the "odd neighbor".
`NumberFormatter::ROUND_HALFUP` int
  Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
`NumberFormatter::ROUND_TOWARD_ZERO`
  Alias of `NumberFormatter::ROUND_DOWN`.
`NumberFormatter::ROUND_UP` int
  Rounding mode to round away from zero.

## Padding Specifiers

Pad position values used by numfmt_get_attribute() and numfmt_set_attribute() with `NumberFormatter::PADDING_POSITION` attribute.

`NumberFormatter::PAD_AFTER_PREFIX` int
  Pad characters inserted after the prefix.
`NumberFormatter::PAD_AFTER_SUFFIX` int
  Pad characters inserted after the suffix.
`NumberFormatter::PAD_BEFORE_PREFIX` int
  Pad characters inserted before the prefix.
`NumberFormatter::PAD_BEFORE_SUFFIX` int
  Pad characters inserted before the suffix.

## See Also

- » ICU formatting documentation
- » ICU number formatters
- » ICU decimal formatters
- » ICU rule-based number formatters

## Changelog

Version | Description
--- | ---
8.5.0 | Added `NumberFormatter::DECIMAL_COMPACT_SHORT`, `NumberFormatter::DECIMAL_COMPACT_LONG`, `NumberFormatter::CURRENCY_ISO`, `NumberFormatter::CURRENCY_PLURAL`, `NumberFormatter::CASH_CURRENCY`, `NumberFormatter::CURRENCY_STANDARD`.
8.4.0 | The class constants are now typed.

# NumberFormatter::create

# numfmt_create

# NumberFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

### Description

Object-oriented style (method)

public static NumberFormatter::create(string `$locale`, int `$style`, ?string `$pattern` = `null`): ?NumberFormatter

Procedural style

numfmt_create(string `$locale`, int `$style`, ?string `$pattern` = `null`): ?NumberFormatter

Object-oriented style (constructor):

public NumberFormatter::__construct(string `$locale`, int `$style`, ?string `$pattern` = `null`)

Creates a number formatter.

### Parameters

`locale`

  Locale in which the number would be formatted (locale name, e.g. en_CA).

`style`

  Style of the formatting, one of the format style constants. If `NumberFormatter::PATTERN_DECIMAL` or `NumberFormatter::PATTERN_RULEBASED` is passed then the number format is opened using the given pattern, which must conform to the syntax described in » ICU DecimalFormat documentation or » ICU RuleBasedNumberFormat documentation, respectively.

`pattern`

  Pattern string if the chosen style requires a pattern.

### Return Values

Returns NumberFormatter object or `null` on error.

### Errors/Exceptions

A ValueError is thrown if `locale` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | A ValueError is thrown if `locale` is invalid.
8.0.0 | `pattern` is nullable now.

### Examples

Example #1 numfmt_create() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo numfmt_format($fmt, 1142)."\n";
?>`

Example #2 NumberFormatter::create() example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo $fmt->format(1142)."\n";
?>`

The above example will output:

    1.234.567,891
    millicentoquarantadue

### See Also

- numfmt_format() - Format a number
- numfmt_parse() - Parse a number

# NumberFormatter::format

# numfmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

### Description

Object-oriented style

public NumberFormatter::format(int|float `$num`, int `$type` = `NumberFormatter::TYPE_DEFAULT`): string|false

Procedural style

numfmt_format(NumberFormatter `$formatter`, int|float `$num`, int `$type` = `NumberFormatter::TYPE_DEFAULT`): string|false

Format a numeric value according to the formatter rules.

### Parameters

`formatter`

  NumberFormatter object.

`num`

  The value to format. Can be int or float, other values will be converted to a numeric value.

`type`

  The formatting type to use. Note that `NumberFormatter::TYPE_CURRENCY` is not supported; use NumberFormatter::formatCurrency() instead.

### Return Values

Returns the string containing formatted value, or `false` on error.

### Examples

Example #1 numfmt_format() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
var_dump($data);
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$data = $fmt->format(1234567.891234567890000);
var_dump($data);
?>`

The above example will output:

    string(13) "1.234.567,891"

### Notes

> Note:

> Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol.

> To fully utilize them use msgfmt_format_message().

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_format_currency() - Format a currency value
- numfmt_parse() - Parse a number
- msgfmt_format_message() - Quick format message

# NumberFormatter::formatCurrency

# numfmt_format_currency

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

### Description

Object-oriented style

public NumberFormatter::formatCurrency(float `$amount`, string `$currency`): string|false

Procedural style

numfmt_format_currency(NumberFormatter `$formatter`, float `$amount`, string `$currency`): string|false

Format the currency value according to the formatter rules.

### Parameters

`formatter`

  NumberFormatter object.

`amount`

  The numeric currency value.

`currency`

  The 3-letter ISO 4217 currency code indicating the currency to use.

### Return Values

String representing the formatted currency value, or `false` on failure.

### Examples

Example #1 numfmt_format_currency() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
$fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
?>`

The above example will output:

    1.234.567,89 €
    1.234.567,89 RUR
    1 234 567,89€
    1 234 567,89р.

### Notes

> Note:

> Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol.

> To fully utilize them use msgfmt_format_message().

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_format() - Format a number
- numfmt_parse_currency() - Parse a currency number
- msgfmt_format_message() - Quick format message

# NumberFormatter::getAttribute

# numfmt_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

### Description

Object-oriented style

public NumberFormatter::getAttribute(int `$attribute`): int|float|false

Procedural style

numfmt_get_attribute(NumberFormatter `$formatter`, int `$attribute`): int|float|false

Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

### Parameters

`formatter`

  NumberFormatter object.

`attribute`

  Attribute specifier - one of the numeric attribute constants.

### Return Values

Return attribute value on success, or `false` on error.

### Examples

Example #1 numfmt_get_attribute() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Digits: 3
    1.234.567,891
    Digits: 2
    1.234.567,89

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_get_text_attribute() - Get a text attribute
- numfmt_set_attribute() - Set an attribute

# NumberFormatter::getErrorCode

# numfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code

### Description

Object-oriented style

public NumberFormatter::getErrorCode(): int

Procedural style

numfmt_get_error_code(NumberFormatter `$formatter`): int

Get error code from the last function performed by the formatter.

### Parameters

`formatter`

  NumberFormatter object.

### Return Values

Returns error code from last formatter call.

### Examples

Example #1 numfmt_get_error_code() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if (intl_is_failure(numfmt_get_error_code($fmt))) {
echo 'Formatter error';
}
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if (intl_is_failure($fmt->getErrorCode())) {
echo 'Formatter error';
}
?>`

### See Also

- numfmt_get_error_message() - Get formatter's last error message
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# NumberFormatter::getErrorMessage

# numfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message

### Description

Object-oriented style

public NumberFormatter::getErrorMessage(): string

Procedural style

numfmt_get_error_message(NumberFormatter `$formatter`): string

Get error message from the last function performed by the formatter.

### Parameters

`formatter`

  NumberFormatter object.

### Return Values

Returns error message from last formatter call.

### Examples

Example #1 numfmt_get_error_message() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>`

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# NumberFormatter::getLocale

# numfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

### Description

Object-oriented style

public NumberFormatter::getLocale(int `$type` = `ULOC_ACTUAL_LOCALE`): string|false

Procedural style

numfmt_get_locale(NumberFormatter `$formatter`, int `$type` = `ULOC_ACTUAL_LOCALE`): string|false

Get formatter locale name.

### Parameters

`formatter`

  NumberFormatter object.

`type`

  You can choose between valid and actual locale ( `Locale::VALID_LOCALE`, `Locale::ACTUAL_LOCALE`, respectively). The default is the actual locale.

### Return Values

The locale name used to create the formatter, or `false` on failure.

### Examples

Example #1 numfmt_get_locale() example

`<?php
$req = 'fr_FR_PARIS';
$fmt = numfmt_create( $req, NumberFormatter::DECIMAL);
$res_val = numfmt_get_locale( $fmt, Locale::VALID_LOCALE );
$res_act = numfmt_get_locale( $fmt, Locale::ACTUAL_LOCALE );
printf( "Requested locale name: %s\nValid locale name: %s\nActual locale name: %s\n",
$req, $res_val, $res_act );
?>`

The above example will output:

    Requested locale name: fr_FR_PARIS
    Valid locale name: fr_FR
    Actual locale name: fr

### See Also

- numfmt_create() - Create a number formatter
- numfmt_get_error_code() - Get formatter's last error code

# NumberFormatter::getPattern

# numfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

### Description

Object-oriented style

public NumberFormatter::getPattern(): string|false

Procedural style

numfmt_get_pattern(NumberFormatter `$formatter`): string|false

Extract pattern used by the formatter.

### Parameters

`formatter`

  NumberFormatter object.

### Return Values

Pattern string that is used by the formatter, or `false` if an error happens.

### Examples

Example #1 numfmt_get_pattern() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Pattern: #,##0.###
    1.234.567,891
    Pattern: #0.# kg
    1234567,9 kg

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_set_pattern() - Set formatter pattern
- numfmt_create() - Create a number formatter

# NumberFormatter::getSymbol

# numfmt_get_symbol

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

### Description

Object-oriented style

public NumberFormatter::getSymbol(int `$symbol`): string|false

Procedural style

numfmt_get_symbol(NumberFormatter `$formatter`, int `$symbol`): string|false

Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

### Parameters

`formatter`

  NumberFormatter object.

`symbol`

  Symbol specifier, one of the format symbol constants.

### Return Values

The symbol string or `false` on error.

### Examples

Example #1 numfmt_get_symbol() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Sep: .
    1.234.567,891
    Sep: *
    1*234*567,891

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_set_symbol() - Set a symbol value

# NumberFormatter::getTextAttribute

# numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

### Description

Object-oriented style

public NumberFormatter::getTextAttribute(int `$attribute`): string|false

Procedural style

numfmt_get_text_attribute(NumberFormatter `$formatter`, int `$attribute`): string|false

Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, `U_UNSUPPORTED_ERROR` error is produced. Rule-based formatters only understand `NumberFormatter::DEFAULT_RULESET` and `NumberFormatter::PUBLIC_RULESETS`.

### Parameters

`formatter`

  NumberFormatter object.

`attribute`

  Attribute specifier - one of the text attribute constants.

### Return Values

Return attribute value on success, or `false` on error.

### Examples

Example #1 numfmt_get_text_attribute() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>`

The above example will output:

    Prefix: -
    -1.234.567,891
    Prefix: MINUS
    MINUS1.234.567,891

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_get_attribute() - Get an attribute
- numfmt_set_text_attribute() - Set a text attribute

# NumberFormatter::parse

# numfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

### Description

Object-oriented style

public NumberFormatter::parse(string `$string`, int `$type` = `NumberFormatter::TYPE_DOUBLE`, int `&$offset` = `null`): int|float|false

Procedural style

numfmt_parse(
NumberFormatter `$formatter`,
string `$string`,
int `$type` = `NumberFormatter::TYPE_DOUBLE`,
int `&$offset` = `null`
): int|float|false

Parse a string into a number using the current formatter rules.

### Parameters

`formatter`

  NumberFormatter object.

`string`

  The string to parse for the number.

`type`

  The formatting type to use. By default, `NumberFormatter::TYPE_DOUBLE` is used. Note that `NumberFormatter::TYPE_CURRENCY` is not supported; use NumberFormatter::parseCurrency() instead.

`offset`

  Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

### Return Values

The value of the parsed number or `false` on error.

### Examples

Example #1 numfmt_parse() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>`

The above example will output:

    1234567.891
    1234567

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_format() - Format a number
- numfmt_parse_currency() - Parse a currency number

# NumberFormatter::parseCurrency

# numfmt_parse_currency

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

### Description

Object-oriented style

public NumberFormatter::parseCurrency(string `$string`, string `&$currency`, int `&$offset` = `null`): float|false

Procedural style

numfmt_parse_currency(
NumberFormatter `$formatter`,
string `$string`,
string `&$currency`,
int `&$offset` = `null`
): float|false

Parse a string into a float and a currency using the current formatter.

### Parameters

`formatter`

  NumberFormatter object.

`currency`

  Parameter to receive the currency name (3-letter ISO 4217 currency code).

`offset`

  Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

### Return Values

The parsed numeric value or `false` on error.

### Examples

Example #1 numfmt_parse_currency() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>`

The above example will output:

    We have 1234567.89 in USD

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_parse() - Parse a number
- numfmt_format_currency() - Format a currency value

# NumberFormatter::setAttribute

# numfmt_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

### Description

Object-oriented style

public NumberFormatter::setAttribute(int `$attribute`, int|float `$value`): bool

Procedural style

numfmt_set_attribute(NumberFormatter `$formatter`, int `$attribute`, int|float `$value`): bool

Set a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

### Parameters

`formatter`

  NumberFormatter object.

`attribute`

  Attribute specifier - one of the numeric attribute constants.

`value`

  The attribute value.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 numfmt_set_attribute() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Digits: 3
    1.234.567,891
    Digits: 2
    1.234.567,89

Example #3 Using `NumberFormatter::ROUNDING_MODE` to truncate values

By default, NumberFormatter rounds values. Using `NumberFormatter::ROUND_DOWN` as the `NumberFormatter::ROUNDING_MODE` truncates the value to the specified number of fraction digits without rounding.

`<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo "Default rounding mode:\n";
echo $fmt->format(3.789), "\n"; // 3.79 (rounded up)
echo $fmt->format(3.781), "\n"; // 3.78 (rounded down)
$fmt->setAttribute(NumberFormatter::ROUNDING_MODE, NumberFormatter::ROUND_DOWN);
echo "\nWith ROUND_DOWN (truncate):\n";
echo $fmt->format(3.789), "\n"; // 3.78 (truncated)
echo $fmt->format(3.781), "\n"; // 3.78 (truncated)
?>`

The above example will output:

    Default rounding mode:
    3.79
    3.78

    With ROUND_DOWN (truncate):
    3.78
    3.78

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_get_attribute() - Get an attribute
- numfmt_set_text_attribute() - Set a text attribute

# NumberFormatter::setPattern

# numfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

### Description

Object-oriented style

public NumberFormatter::setPattern(string `$pattern`): bool

Procedural style

numfmt_set_pattern(NumberFormatter `$formatter`, string `$pattern`): bool

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

### Parameters

`formatter`

  NumberFormatter object.

`pattern`

  Pattern in syntax described in » ICU DecimalFormat documentation.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 numfmt_set_pattern() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Pattern: #,##0.###
    1.234.567,891
    Pattern: #0.# kg
    1234567,9 kg

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_create() - Create a number formatter
- numfmt_get_pattern() - Get formatter pattern

# NumberFormatter::setSymbol

# numfmt_set_symbol

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

### Description

Object-oriented style

public NumberFormatter::setSymbol(int `$symbol`, string `$value`): bool

Procedural style

numfmt_set_symbol(NumberFormatter `$formatter`, int `$symbol`, string `$value`): bool

Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

### Parameters

`formatter`

  NumberFormatter object.

`symbol`

  Symbol specifier, one of the format symbol constants.

`value`

  Text for the symbol.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 numfmt_set_symbol() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>`

The above example will output:

    Sep: .
    1.234.567,891
    Sep: *
    1*234*567,891

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_get_symbol() - Get a symbol value

# NumberFormatter::setTextAttribute

# numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

### Description

Object-oriented style

public NumberFormatter::setTextAttribute(int `$attribute`, string `$value`): bool

Procedural style

numfmt_set_text_attribute(NumberFormatter `$formatter`, int `$attribute`, string `$value`): bool

Set a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, `U_UNSUPPORTED_ERROR` error is produced. Rule-based formatters only understand `NumberFormatter::DEFAULT_RULESET` and `NumberFormatter::PUBLIC_RULESETS`.

### Parameters

`formatter`

  NumberFormatter object.

`attribute`

  Attribute specifier - one of the text attribute constants.

`value`

  Text for the attribute value.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 numfmt_set_text_attribute() example

`<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>`

Example #2 OO example

`<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>`

The above example will output:

    Prefix: -
    -1.234.567,891
    Prefix: MINUS
    MINUS1.234.567,891

### See Also

- numfmt_get_error_code() - Get formatter's last error code
- numfmt_get_text_attribute() - Get a text attribute
- numfmt_set_attribute() - Set an attribute

## Table of Contents

- NumberFormatter::create — Create a number formatter
- NumberFormatter::format — Format a number
- NumberFormatter::formatCurrency — Format a currency value
- NumberFormatter::getAttribute — Get an attribute
- NumberFormatter::getErrorCode — Get formatter's last error code
- NumberFormatter::getErrorMessage — Get formatter's last error message
- NumberFormatter::getLocale — Get formatter locale
- NumberFormatter::getPattern — Get formatter pattern
- NumberFormatter::getSymbol — Get a symbol value
- NumberFormatter::getTextAttribute — Get a text attribute
- NumberFormatter::parse — Parse a number
- NumberFormatter::parseCurrency — Parse a currency number
- NumberFormatter::setAttribute — Set an attribute
- NumberFormatter::setPattern — Set formatter pattern
- NumberFormatter::setSymbol — Set a symbol value
- NumberFormatter::setTextAttribute — Set a text attribute

# The Locale class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats.

Examples of identifiers include:

- en-US (English, United States)
- zh-Hant-TW (Chinese, Traditional Script, Taiwan)
- fr-CA, fr-FR (French for Canada and France respectively)

The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally.

Locales cannot be instantiated as objects. All of the functions/methods provided are static.

The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en_US_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification.

## Class synopsis

class Locale {
/* Constants */
public const int ACTUAL_LOCALE;
public const int VALID_LOCALE;
public const null DEFAULT_LOCALE = null;
public const string LANG_TAG;
public const string EXTLANG_TAG;
public const string SCRIPT_TAG;
public const string REGION_TAG;
public const string VARIANT_TAG;
public const string GRANDFATHERED_LANG_TAG;
public const string PRIVATE_TAG;
/* Methods */
public static acceptFromHttp(string `$header`): string|false
public static canonicalize(string `$locale`): ?string
public static composeLocale(array `$subtags`): string|false
public static filterMatches(string `$languageTag`, string `$locale`, bool `$canonicalize` = `false`): ?bool
public static getAllVariants(string `$locale`): ?array
public static getDefault(): string
public static getDisplayLanguage(string `$locale`, ?string `$displayLocale` = `null`): string|false
public static getDisplayName(string `$locale`, ?string `$displayLocale` = `null`): string|false
public static getDisplayRegion(string `$locale`, ?string `$displayLocale` = `null`): string|false
public static getDisplayScript(string `$locale`, ?string `$displayLocale` = `null`): string|false
public static getDisplayVariant(string `$locale`, ?string `$displayLocale` = `null`): string|false
public static getKeywords(string `$locale`): array|false|null
public static getPrimaryLanguage(string `$locale`): ?string
public static getRegion(string `$locale`): ?string
public static getScript(string `$locale`): ?string
public static isRightToLeft( string `$locale` = "" ): bool
public static lookup(
array `$languageTag`,
string `$locale`,
bool `$canonicalize` = `false`,
?string `$defaultLocale` = `null`
): ?string
public static parseLocale(string `$locale`): ?array
public static setDefault(string `$locale`): true
}

## Predefined Constants

`Locale::DEFAULT_LOCALE` null
  Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale.

These constants describe the choice of the locale for the getLocale method of different classes.

`Locale::ACTUAL_LOCALE` int
  This is locale the data actually comes from.
`Locale::VALID_LOCALE` int
  This is the most specific locale supported by ICU.

## Locale Subtags

These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to locale_compose() and are returned from locale_parse() as keys of the returned associative array.

`Locale::LANG_TAG` string
  Language subtag
`Locale::EXTLANG_TAG` string
  Extended language subtag
`Locale::SCRIPT_TAG` string
  Script subtag
`Locale::REGION_TAG` string
  Region subtag
`Locale::VARIANT_TAG` string
  Variant subtag
`Locale::GRANDFATHERED_LANG_TAG` string
  Grandfathered Language subtag
`Locale::PRIVATE_TAG` string
  Private subtag

## See Also

- » RFC 4646 - Tags for Identifying Languages
- » RFC 4647 - Matching of Language Tags
- » Unicode CLDR Project:Common Locale Data Repository
- » IANA Language Subtags Registry
- » ICU User Guide - Locale
- » ICU Locale api

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# Locale::acceptFromHttp

# locale_accept_from_http

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

### Description

Object-oriented style

public static Locale::acceptFromHttp(string `$header`): string|false

Procedural style

locale_accept_from_http(string `$header`): string|false

Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.

### Parameters

`header`

  The string containing the "Accept-Language" header according to format in RFC 2616.

### Return Values

The corresponding locale identifier.

Returns `false` when the length of `header` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_accept_from_http() example

`<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>`

Example #2 OO example

`<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>`

The above example will output:

    en_US

### See Also

- locale_lookup() - Searches the language tag list for the best match to the language

# Locale::canonicalize

# locale_canonicalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::canonicalize -- locale_canonicalize — Canonicalize the locale string

### Description

public static Locale::canonicalize(string `$locale`): ?string

Canonicalizes the passed locale string to ICU format.

This does not necessarily indicate or return a valid locale. It is only a version of the input that has been canonicalized according to ICU rules.

The behavior of this function depends on the version of ICU PHP is using (`INTL_ICU_VERSION`).

### Parameters

`locale`
  Original locale string.

### Return Values

Canonicalized locale string.

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_canonicalize() example

`echo Locale::canonicalize('en-US.utf8') . "\n";
echo Locale::canonicalize('totally-not-valid') . "\n";`

The above example will output something similar to:

    en_US
    totally_NOT_VALID

# Locale::composeLocale

# locale_compose

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

### Description

Object-oriented style

public static Locale::composeLocale(array `$subtags`): string|false

Procedural style

locale_compose(array `$subtags`): string|false

Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values.

### Parameters

`subtags`

  An array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values.

  > Note:

  > The `'variant'` and `'private'` subtags can take maximum 15 values whereas `'extlang'` can take maximum 3 values. For instance, variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be `variant0`, `variant1`, …,`variant14`. In the returned locale id, the subtag is ordered by suffix resulting in `variant0` followed by `variant1` followed by `variant2` and so on.

  > Alternatively, the `'variant'`, `'private'` and `'extlang'` values can be specified as array under specific key (e.g. `'variant'`). In this case no limits on the number of recognized subtags apply.

### Return Values

The corresponding locale identifier, or `false` when `subtags` is empty.

### Examples

Example #1 locale_compose() example

`<?php
$arr = array(
'language'=>'en',
'script' =>'Hans',
'region' =>'CN',
'variant2'=>'rozaj',
'variant1'=>'nedis',
'private1'=>'prv1',
'private2'=>'prv2',
);
echo locale_compose($arr);
?>`

Example #2 OO example

`<?php
$arr = array(
'language'=>'en' ,
'script' =>'Hans',
'region' =>'CN',
'variant2'=>'rozaj',
'variant1'=>'nedis',
'private1'=>'prv1',
'private2'=>'prv2',
);
echo Locale::composeLocale($arr);
?>`

The above example will output:

    Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

Example #3 Subtag limits

If `subtags` are given as separate keys with numeric suffix, unsupported keys are silently ignored (in this case `'extlang3'`), and ordered in the result by numeric suffix. There are no limits, if subtags are given as array; the order is as given.

`<?php
$arr = array(
'language' => 'en',
'script' => 'Hans',
'region' => 'CN',
'extlang3' => 'd',
'extlang2' => 'c',
'extlang1' => 'b',
'extlang0' => 'a',
);
echo locale_compose($arr), PHP_EOL;
$arr = array(
'language' => 'en',
'script' => 'Hans',
'region' => 'CN',
'extlang' => ['a', 'b', 'c', 'd'],
);
echo locale_compose($arr), PHP_EOL;
?>`

The above example will output:

    en_a_b_c_Hans_CN
    en_a_b_c_d_Hans_CN

### See Also

- locale_parse() - Returns a key-value array of locale ID subtag elements

# Locale::filterMatches

# locale_filter_matches

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

### Description

Object-oriented style

public static Locale::filterMatches(string `$languageTag`, string `$locale`, bool `$canonicalize` = `false`): ?bool

Procedural style

locale_filter_matches(string `$languageTag`, string `$locale`, bool `$canonicalize` = `false`): ?bool

Checks if a `languageTag` filter matches with `locale` according to RFC 4647's basic filtering algorithm

### Parameters

`languageTag`

  The language tag to check

`locale`

  The language range to check against

`canonicalize`

  If true, the arguments will be converted to canonical form before matching.

### Return Values

`true` if `locale` matches `languageTag` `false` otherwise.

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_filter_matches() example

`<?php
echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match";
?>`

Example #2 OO example

`<?php
echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match";
?>`

The above example will output:

    Does not match; Matches

### See Also

- locale_lookup() - Searches the language tag list for the best match to the language

# Locale::getAllVariants

# locale_get_all_variants

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

### Description

Object-oriented style

public static Locale::getAllVariants(string `$locale`): ?array

Procedural style

locale_get_all_variants(string `$locale`): ?array

Gets the variants for the input locale

### Parameters

`locale`

  The locale to extract the variants from

### Return Values

The array containing the list of all variants subtag for the locale or `null` if not present

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_get_all_variants() example

`<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>`

Example #2 OO example

`<?php
$arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>`

The above example will output:

    array (
        0 => 'NEDIS',
        1 => 'ROJAZ',
        2 => '1901',
    )

### See Also

- locale_get_primary_language() - Gets the primary language for the input locale
- locale_get_script() - Gets the script for the input locale
- locale_get_region() - Gets the region for the input locale

# Locale::getDefault

# locale_get_default

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

### Description

Object-oriented style

public static Locale::getDefault(): string

Procedural style

locale_get_default(): string

Gets the default locale value. At the PHP initialization this value is set to 'intl.default_locale' value from php.ini if that value exists or from ICU's function uloc_getDefault().

### Parameters

### Return Values

The current runtime locale

### Examples

Example #1 locale_get_default() example

`<?php
ini_set('intl.default_locale', 'de-DE');
echo locale_get_default();
echo '; ';
locale_set_default('fr');
echo locale_get_default();
?>`

Example #2 OO example

`<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>`

The above example will output:

    de-DE; fr

### See Also

- locale_set_default() - Sets the default runtime locale

# Locale::getDisplayLanguage

# locale_get_display_language

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

### Description

Object-oriented style

public static Locale::getDisplayLanguage(string `$locale`, ?string `$displayLocale` = `null`): string|false

Procedural style

locale_get_display_language(string `$locale`, ?string `$displayLocale` = `null`): string|false

Returns an appropriately localized display name for language of the input locale. If is `null` then the default locale is used.

### Parameters

`locale`

  The locale to return a display language for

`displayLocale`

  Optional format locale to use to display the language name

### Return Values

Display name of the language for the `locale` in the format appropriate for `displayLocale`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `displayLocale` is nullable now.

### Examples

Example #1 locale_get_display_language() example

`<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>`

Example #2 OO example

`<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>`

The above example will output:

    Slovenian;
    slov\xc3\xa8ne;
    Slowenisch

### See Also

- locale_get_display_name() - Returns an appropriately localized display name for the input locale
- locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
- locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
- locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

# Locale::getDisplayName

# locale_get_display_name

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

### Description

Object-oriented style

public static Locale::getDisplayName(string `$locale`, ?string `$displayLocale` = `null`): string|false

Procedural style

locale_get_display_name(string `$locale`, ?string `$displayLocale` = `null`): string|false

Returns an appropriately localized display name for the input locale. If `locale` is `null` then the default locale is used.

### Parameters

`locale`

  The locale to return a display name for.

`displayLocale`

  optional format locale

### Return Values

Display name of the locale in the format appropriate for `displayLocale`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `displayLocale` is nullable now.

### Examples

Example #1 locale_get_display_name() example

`<?php
echo locale_get_display_name('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'de');
?>`

Example #2 OO example

`<?php
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de');
?>`

The above example will output:

    Slovenian (Latin, Italy, Natisone dialect);
    slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
    Slowenisch (Lateinisch, Italien, NEDIS)

### See Also

- locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
- locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
- locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
- locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

# Locale::getDisplayRegion

# locale_get_display_region

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

### Description

Object-oriented style

public static Locale::getDisplayRegion(string `$locale`, ?string `$displayLocale` = `null`): string|false

Procedural style

locale_get_display_region(string `$locale`, ?string `$displayLocale` = `null`): string|false

Returns an appropriately localized display name for region of the input locale. If is `null` then the default locale is used.

### Parameters

`locale`

  The locale to return a display region for.

`displayLocale`

  Optional format locale to use to display the region name

### Return Values

Display name of the region for the `locale` in the format appropriate for `displayLocale`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `displayLocale` is nullable now.

### Examples

Example #1 locale_get_display_region() example

`<?php
echo locale_get_display_region('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'de');
?>`

Example #2 OO example

`<?php
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de');
?>`

The above example will output:

    Italy;
    Italie;
    Italien

### See Also

- locale_get_display_name() - Returns an appropriately localized display name for the input locale
- locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
- locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
- locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

# Locale::getDisplayScript

# locale_get_display_script

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

### Description

Object-oriented style

public static Locale::getDisplayScript(string `$locale`, ?string `$displayLocale` = `null`): string|false

Procedural style

locale_get_display_script(string `$locale`, ?string `$displayLocale` = `null`): string|false

Returns an appropriately localized display name for script of the input locale. If is `null` then the default locale is used.

### Parameters

`locale`

  The locale to return a display script for

`displayLocale`

  Optional format locale to use to display the script name

### Return Values

Display name of the script for the `locale` in the format appropriate for `displayLocale`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `displayLocale` is nullable now.

### Examples

Example #1 locale_get_display_script() example

`<?php
echo locale_get_display_script('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'de');
?>`

Example #2 OO example

`<?php
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'de');
?>`

The above example will output:

    Latin;
    latin;
    Lateinisch

### See Also

- locale_get_display_name() - Returns an appropriately localized display name for the input locale
- locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
- locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
- locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

# Locale::getDisplayVariant

# locale_get_display_variant

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

### Description

Object-oriented style

public static Locale::getDisplayVariant(string `$locale`, ?string `$displayLocale` = `null`): string|false

Procedural style

locale_get_display_variant(string `$locale`, ?string `$displayLocale` = `null`): string|false

Returns an appropriately localized display name for variants of the input locale. If is `null` then the default locale is used.

### Parameters

`locale`

  The locale to return a display variant for

`displayLocale`

  Optional format locale to use to display the variant name

### Return Values

Display name of the variant for the `locale` in the format appropriate for `displayLocale`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `displayLocale` is nullable now.

### Examples

Example #1 locale_get_display_variant() example

`<?php
echo locale_get_display_variant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'de');
?>`

Example #2 OO example

`<?php
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de');
?>`

The above example will output:

    Natisone dialect;
    dialecte de Natisone;
    NEDIS

### See Also

- locale_get_display_name() - Returns an appropriately localized display name for the input locale
- locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
- locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
- locale_get_display_region() - Returns an appropriately localized display name for region of the input locale

# Locale::getKeywords

# locale_get_keywords

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

### Description

Object-oriented style

public static Locale::getKeywords(string `$locale`): array|false|null

Procedural style

locale_get_keywords(string `$locale`): array|false|null

Gets the keywords for the input locale.

### Parameters

`locale`

  The locale to extract the keywords from

### Return Values

Associative array containing the keyword-value pairs for this locale

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_get_keywords() example

`<?php
$keywords_arr = locale_get_keywords('de_DE@currency=EUR;collation=PHONEBOOK');
if ($keywords_arr) {
foreach ($keywords_arr as $key => $value) {
echo "$key = $value\n";
}
}
?>`

Example #2 OO example

`<?php
$keywords_arr = Locale::getKeywords('de_DE@currency=EUR;collation=PHONEBOOK');
if ($keywords_arr) {
foreach ($keywords_arr as $key => $value) {
echo "$key = $value\n";
}
}
?>`

The above example will output:

    collation = PHONEBOOK
    currency = EUR

### See Also

- locale_get_all_variants() - Gets the variants for the input locale

# Locale::getPrimaryLanguage

# locale_get_primary_language

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

### Description

Object-oriented style

public static Locale::getPrimaryLanguage(string `$locale`): ?string

Procedural style

locale_get_primary_language(string `$locale`): ?string

Gets the primary language for the input locale

### Parameters

`locale`

  The locale to extract the primary language code from

### Return Values

The language code associated with the language.

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_get_primary_language() example

`<?php
echo locale_get_primary_language('zh-Hant');
?>`

Example #2 OO example

`<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>`

The above example will output:

    zh

### See Also

- locale_get_script() - Gets the script for the input locale
- locale_get_region() - Gets the region for the input locale
- locale_get_all_variants() - Gets the variants for the input locale

# Locale::getRegion

# locale_get_region

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

### Description

Object-oriented style

public static Locale::getRegion(string `$locale`): ?string

Procedural style

locale_get_region(string `$locale`): ?string

Gets the region for the input locale.

### Parameters

`locale`

  The locale to extract the region code from

### Return Values

The region subtag for the locale or `null` if not present

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_get_region() example

`<?php
echo locale_get_region('de-CH-1901');
?>`

Example #2 OO example

`<?php
echo Locale::getRegion('de-CH-1901');
?>`

The above example will output:

    CH

### See Also

- locale_get_primary_language() - Gets the primary language for the input locale
- locale_get_script() - Gets the script for the input locale
- locale_get_all_variants() - Gets the variants for the input locale

# Locale::getScript

# locale_get_script

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

### Description

Object-oriented style

public static Locale::getScript(string `$locale`): ?string

Procedural style

locale_get_script(string `$locale`): ?string

Gets the script for the input locale.

### Parameters

`locale`

  The locale to extract the script code from

### Return Values

The script subtag for the locale or `null` if not present

### Examples

Example #1 locale_get_script() example

`<?php
echo locale_get_script('sr-Cyrl');
?>`

Example #2 OO example

`<?php
echo Locale::getScript('sr-Cyrl');
?>`

The above example will output:

    Cyrl

### See Also

- locale_get_primary_language() - Gets the primary language for the input locale
- locale_get_region() - Gets the region for the input locale
- locale_get_all_variants() - Gets the variants for the input locale

# Locale::isRightToLeft

(No version information available, might only be in Git)

Locale::isRightToLeft — Check whether a locale uses a right-to-left writing system

### Description

public static Locale::isRightToLeft( string `$locale` = "" ): bool

Determines whether a locale uses a right-to-left writing system.

This method relies on the ICU library and evaluates the dominant script associated with the locale.

If an empty string is provided, the default locale is used.

### Parameters

`locale`
  The locale identifier. If empty, the default locale is used.

### Return Values

Returns `true` if the locale uses a right-to-left writing system, or `false` otherwise.

### Changelog

Version | Description
--- | ---
8.5.0 | Added Locale::isRightToLeft().

### Examples

Example #1 Checking text direction for a locale

    var_dump(Locale::isRightToLeft('en-US'));
    var_dump(Locale::isRightToLeft('ar'));

The above example will output:

    bool(false)
    bool(true)

# Locale::lookup

# locale_lookup

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

### Description

Object-oriented style

public static Locale::lookup(
array `$languageTag`,
string `$locale`,
bool `$canonicalize` = `false`,
?string `$defaultLocale` = `null`
): ?string

Procedural style

locale_lookup(
array `$languageTag`,
string `$locale`,
bool `$canonicalize` = `false`,
?string `$defaultLocale` = `null`
): ?string

Searches the items in `languageTag` for the best match to the language range specified in `locale` according to RFC 4647's lookup algorithm.

### Parameters

`languageTag`

  An array containing a list of language tags to compare to `locale`. Maximum 100 items allowed.

`locale`

  The locale to use as the language range when matching.

`canonicalize`

  If true, the arguments will be converted to canonical form before matching.

`defaultLocale`

  The locale to use if no match is found.

### Return Values

The closest matching language tag or default value.

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Changelog

Version | Description
--- | ---
7.4.0 | `defaultLocale` is nullable now.

### Examples

Example #1 locale_lookup() example

`<?php
$arr = array(
'de-DEVA',
'de-DE-1996',
'de',
'de-De'
);
echo locale_lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>`

Example #2 OO example

`<?php
$arr = array(
'de-DEVA',
'de-DE-1996',
'de',
'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>`

The above example will output:

    de_de_1996

### See Also

- locale_filter_matches() - Checks if a language tag filter matches with locale

# Locale::parseLocale

# locale_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements

### Description

Object-oriented style

public static Locale::parseLocale(string `$locale`): ?array

Procedural style

locale_parse(string `$locale`): ?array

Returns a key-value array of locale ID subtag elements.

### Parameters

`locale`

  The locale to extract the subtag array from. Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.

### Return Values

Returns an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. The array will be ordered as the locale id subtags e.g. in the locale id if variants are '-varX-varY-varZ' then the returned array will have variant0=>varX , variant1=>varY , variant2=>varZ

Returns `null` when the length of `locale` exceeds `INTL_MAX_LOCALE_LEN`.

### Examples

Example #1 locale_parse() example

`<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>`

Example #2 OO example

`<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>`

The above example will output:

    language : sl , script : Latn , region : IT , variant0 : NEDIS ,

### See Also

- locale_compose() - Returns a correctly ordered and delimited locale ID

# Locale::setDefault

# locale_set_default

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — Sets the default runtime locale

### Description

Object-oriented style

public static Locale::setDefault(string `$locale`): true

Procedural style

locale_set_default(string `$locale`): true

Sets the default runtime locale to `locale`. This changes the value of INTL global 'default_locale' locale identifier. UAX #35 extensions are accepted.

### Parameters

`locale`

  Is a BCP 47 compliant language tag.

### Return Values

Returns `true`.

### Examples

Example #1 locale_set_default() example

`<?php
locale_set_default('de-DE');
echo locale_get_default();
?>`

Example #2 OO example

`<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>`

The above example will output:

    de-DE

### See Also

- locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

## Table of Contents

- Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
- Locale::canonicalize — Canonicalize the locale string
- Locale::composeLocale — Returns a correctly ordered and delimited locale ID
- Locale::filterMatches — Checks if a language tag filter matches with locale
- Locale::getAllVariants — Gets the variants for the input locale
- Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
- Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
- Locale::getDisplayName — Returns an appropriately localized display name for the input locale
- Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
- Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
- Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
- Locale::getKeywords — Gets the keywords for the input locale
- Locale::getPrimaryLanguage — Gets the primary language for the input locale
- Locale::getRegion — Gets the region for the input locale
- Locale::getScript — Gets the script for the input locale
- Locale::isRightToLeft — Check whether a locale uses a right-to-left writing system
- Locale::lookup — Searches the language tag list for the best match to the language
- Locale::parseLocale — Returns a key-value array of locale ID subtag elements
- Locale::setDefault — Sets the default runtime locale

# The Normalizer class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation.

The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications:

- Normalization Form D (NFD) - Canonical Decomposition
- Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
- Normalization Form KD (NFKD) - Compatibility Decomposition
- Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition

The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files.

## Class synopsis

class Normalizer {
/* Constants */
public const int FORM_D;
public const int NFD;
public const int FORM_KD;
public const int NFKD;
public const int FORM_C;
public const int NFC;
public const int FORM_KC;
public const int NFKC;
public const int FORM_KC_CF;
public const int NFKC_CF;
/* Methods */
public static getRawDecomposition(string `$string`, int `$form` = `Normalizer::FORM_C`): ?string
public static isNormalized(string `$string`, int `$form` = `Normalizer::FORM_C`): bool
public static normalize(string `$string`, int `$form` = `Normalizer::FORM_C`): string|false
}

## Predefined Constants

The following constants define the normalization form used by the normalizer:

`Normalizer::FORM_C` int
  Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
`Normalizer::FORM_D` int
  Normalization Form D (NFD) - Canonical Decomposition
`Normalizer::NFD` int

`Normalizer::FORM_KC` int
  Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
`Normalizer::NFKC` int

`Normalizer::FORM_KC_CF` int

`Normalizer::FORM_KD` int
  Normalization Form KD (NFKD) - Compatibility Decomposition
`Normalizer::NFKD` int

`Normalizer::NFC` int

`Normalizer::NFKC_CF` int

## See Also

- » Unicode Normalization
- » Unicode Normalization FAQ
- » ICU User Guide - Normalization
- » ICU API Reference - Normalization

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
8.0.0 | `Normalizer::NONE` has been removed.

# Normalizer::getRawDecomposition

# normalizer_get_raw_decomposition

(PHP 7 >= 7.3, PHP 8)

Normalizer::getRawDecomposition -- normalizer_get_raw_decomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

### Description

Object-oriented style

public static Normalizer::getRawDecomposition(string `$string`, int `$form` = `Normalizer::FORM_C`): ?string

Procedural style

normalizer_get_raw_decomposition(string `$string`, int `$form` = `Normalizer::FORM_C`): ?string

Gets the Decomposition_Mapping property, as specified in the Unicode Character Database (UCD), for the given UTF-8 encoded code point.

### Parameters

`string`

  The input string, which should be a single, UTF-8 encoded, code point.

### Return Values

Returns a string containing the Decomposition_Mapping property, if present in the UCD.

Returns `null` if there is no Decomposition_Mapping property for the character.

### Examples

Example #1 Normalizer::getRawDecomposition() example

`<?php
$result = "";
$strings = [
"a",
"\u{FFDA}",
"\u{FDFA}",
"",
"aa",
"\xF5",
];
foreach ($strings as $string) {
$decomposition = Normalizer::getRawDecomposition($string);
// $decomposition = normalizer_get_raw_decomposition($string); Procedural way
$error_code = intl_get_error_code();
$error_message = intl_get_error_message();
$string_hex = bin2hex($string);
$result .= "---------------------\n";
if ($decomposition === null) {
$result .= "'$string_hex' has no decomposition mapping\n" ;
} else {
$result .= "'$string_hex' has the decomposition mapping '" . bin2hex($decomposition) . "'\n" ;
}
$result .= "error info: '$error_message' ($error_code)\n";
}
echo $result;
?>`

The above example will output:

    ---------------------
    '61' has no decomposition mapping
    error info: 'U_ZERO_ERROR' (0)
    ---------------------
    'efbf9a' has the decomposition mapping 'e385a1'
    error info: 'U_ZERO_ERROR' (0)
    ---------------------
    'efb7ba' has the decomposition mapping 'd8b5d984d98920d8a7d984d984d98720d8b9d984d98ad98720d988d8b3d984d985'
    error info: 'U_ZERO_ERROR' (0)
    ---------------------
    '' has no decomposition mapping
    error info: 'Input string must be exactly one UTF-8 encoded code point long.: U_ILLEGAL_ARGUMENT_ERROR' (1)
    ---------------------
    '6161' has no decomposition mapping
    error info: 'Input string must be exactly one UTF-8 encoded code point long.: U_ILLEGAL_ARGUMENT_ERROR' (1)
    ---------------------
    'f5' has no decomposition mapping
    error info: 'Code point out of range: U_ILLEGAL_ARGUMENT_ERROR' (1)

### See Also

- Normalizer::normalize() - Normalizes the input provided and returns the normalized string
- Normalizer::isNormalized() - Checks if the provided string is already in the specified normalization form

# Normalizer::isNormalized

# normalizer_is_normalized

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form

### Description

Object-oriented style

public static Normalizer::isNormalized(string `$string`, int `$form` = `Normalizer::FORM_C`): bool

Procedural style

normalizer_is_normalized(string `$string`, int `$form` = `Normalizer::FORM_C`): bool

Checks if the provided string is already in the specified normalization form.

### Parameters

`string`

  The input string to normalize

`form`

  One of the normalization forms.

### Return Values

`true` if normalized, `false` otherwise or if there an error

### Examples

Example #1 normalizer_is_normalized() example

`<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)
$char_orig = 'A' . $char_combining_ring_above;
$char_norm = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );
echo ( normalizer_is_normalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( normalizer_is_normalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>`

Example #2 OO example

`<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)
$char_orig = 'A' . $char_combining_ring_above;
$char_norm = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );
echo ( Normalizer::isNormalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( Normalizer::isNormalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>`

The above example will output:

    not normalized; normalized

### See Also

- normalizer_normalize() - Normalizes the input provided and returns the normalized string

# Normalizer::normalize

# normalizer_normalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

### Description

Object-oriented style

public static Normalizer::normalize(string `$string`, int `$form` = `Normalizer::FORM_C`): string|false

Procedural style

normalizer_normalize(string `$string`, int `$form` = `Normalizer::FORM_C`): string|false

Normalizes the input provided and returns the normalized string

### Parameters

`string`

  The input string to normalize

`form`

  One of the normalization forms.

### Return Values

The normalized string or `false` if an error occurred.

### Examples

Example #1 normalizer_normalize() example

`<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)
$char_1 = normalizer_normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );
echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>`

Example #2 OO example

`<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)
$char_1 = Normalizer::normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );
echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>`

The above example will output:

    %C3%85 %C3%85

### See Also

- normalizer_is_normalized() - Checks if the provided string is already in the specified normalization form

## Table of Contents

- Normalizer::getRawDecomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
- Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form
- Normalizer::normalize — Normalizes the input provided and returns the normalized string

# The MessageFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

MessageFormatter is a concrete class that enables users to produce concatenated, language-neutral messages. The methods supplied in this class are used to build all the messages that are seen by end users.

The MessageFormatter class assembles messages from various fragments (such as text fragments, numbers, and dates) supplied by the program. Because of the MessageFormatter class, the program does not need to know the order of the fragments. The class uses the formatting specifications for the fragments to assemble them into a message that is contained in a single string within a resource bundle. For example, MessageFormatter enables you to print the phrase "Finished printing x out of y files..." in a manner that still allows for flexibility in translation.

Previously, an end user message was created as a sentence and handled as a string. This procedure created problems for localizers because the sentence structure, word order, number format and so on are very different from language to language. The language-neutral way to create messages keeps each part of the message separate and provides keys to the data. Using these keys, the MessageFormatter class can concatenate the parts of the message, localize them, and display a well-formed string to the end user.

MessageFormatter takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. Choice formats can be used in conjunction with MessageFormatter to handle plurals, match numbers, and select from an array of items. Typically, the message format will come from resources and the arguments will be dynamically set at runtime.

## Class synopsis

class MessageFormatter {
/* Methods */
public __construct(string `$locale`, string `$pattern`)
public static create(string `$locale`, string `$pattern`): ?MessageFormatter
public format(array `$values`): string|false
public static formatMessage(string `$locale`, string `$pattern`, array `$values`): string|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(): string
public getPattern(): string|false
public parse(string `$string`): array|false
public static parseMessage(string `$locale`, string `$pattern`, string `$message`): array|false
public setPattern(string `$pattern`): bool
}

## See Also

- » ICU formatting documentation
- » ICU message formatting description
- » ICU message formatters
- » ICU choice formatters

# MessageFormatter::create

# MessageFormatter::__construct

# msgfmt_create

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

### Description

Object-oriented style (method)

public static MessageFormatter::create(string `$locale`, string `$pattern`): ?MessageFormatter

Object-oriented style (constructor):

public MessageFormatter::__construct(string `$locale`, string `$pattern`)

Procedural style

msgfmt_create(string `$locale`, string `$pattern`): ?MessageFormatter

Constructs a new Message Formatter

### Parameters

`locale`

  The locale to use when formatting arguments

`pattern`

  The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

### Return Values

The formatter object, or `null` on failure.

### Errors/Exceptions

When invoked as constructor, on failure an IntlException is thrown.

### Examples

Example #1 msgfmt_create() example

`<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>`

The above example will output:

    4,560 monkeys on 123 trees make 37.073 monkeys per tree
    4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

### See Also

- msgfmt_format() - Format the message
- msgfmt_parse() - Parse input string according to pattern
- msgfmt_get_error_code() - Get the error code from last operation
- msgfmt_get_error_message() - Get the error text from the last operation

# MessageFormatter::format

# msgfmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

### Description

Object-oriented style

public MessageFormatter::format(array `$values`): string|false

Procedural style

msgfmt_format(MessageFormatter `$formatter`, array `$values`): string|false

Format the message by substituting the data into the format string according to the locale rules

### Parameters

`formatter`

  The message formatter

`values`

  Arguments to insert into the format string

### Return Values

The formatted string, or `false` if an error occurred

### Examples

Example #1 msgfmt_format() example

`<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>`

The above example will output:

    4,560 monkeys on 123 trees make 37.073 monkeys per tree
    4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_parse() - Parse input string according to pattern
- msgfmt_format_message() - Quick format message
- msgfmt_get_error_code() - Get the error code from last operation
- msgfmt_get_error_message() - Get the error text from the last operation

# MessageFormatter::formatMessage

# msgfmt_format_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

### Description

Object-oriented style

public static MessageFormatter::formatMessage(string `$locale`, string `$pattern`, array `$values`): string|false

Procedural style

msgfmt_format_message(string `$locale`, string `$pattern`, array `$values`): string|false

Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept or when wanting to customize the output by providing additional context to ICU directly.

### Parameters

`locale`

  The locale to use for formatting locale-dependent parts

`pattern`

  The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

`values`

  The array of values to insert into the format string

### Return Values

The formatted pattern string or `false` if an error occurred

### Examples

Example #1 msgfmt_format_message() example

`<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("en", 'You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}!', ['place' => 3]), "\n";
echo msgfmt_format_message("en",
"There {apple, plural,
=0 {are no apples}
=1 {is one apple...}
other {are # apples!}
}",
['apple' => 0]
), "\n";`

Example #2 OO example

`<?php
echo MessageFormatter::formatMessage("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("en", 'You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}!', ['place' => 3]), "\n";
echo MessageFormatter::formatMessage("en",
"There {apple, plural,
=0 {are no apples}
=1 {is one apple...}
other {are # apples!}
}",
['apple' => 0]
), "\n";`

The above example will output:

    4,560 monkeys on 123 trees make 37.073 monkeys per tree
    4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum
    You finished 3rd!
    There are no apples

Example #3 Instructing ICU to format currency with common and with narrow currency symbol

Requires ICU ≥ 67.

`<?php
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD}", array(123.45));
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD unit-width-narrow}", array(123.45));`

The above example will output:

    123,45 CA$
    123,45 $

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_parse() - Parse input string according to pattern
- msgfmt_get_error_code() - Get the error code from last operation
- msgfmt_get_error_message() - Get the error text from the last operation

# MessageFormatter::getErrorCode

# msgfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

### Description

Object-oriented style

public MessageFormatter::getErrorCode(): int

Procedural style

msgfmt_get_error_code(MessageFormatter `$formatter`): int

Get the error code from last operation.

### Parameters

`formatter`

  The message formatter

### Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

### See Also

- msgfmt_get_error_message() - Get the error text from the last operation
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# MessageFormatter::getErrorMessage

# msgfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

### Description

Object-oriented style

public MessageFormatter::getErrorMessage(): string

Procedural style

msgfmt_get_error_message(MessageFormatter `$formatter`): string

Get the error text from the last operation.

### Parameters

`formatter`

  The message formatter

### Return Values

Description of the last error.

### Examples

Example #1 msgfmt_get_error_message() example

`<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>`

The above example will output:

    ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

### See Also

- msgfmt_get_error_code() - Get the error code from last operation
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# MessageFormatter::getLocale

# msgfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created

### Description

Object-oriented style

public MessageFormatter::getLocale(): string

Procedural style

msgfmt_get_locale(MessageFormatter `$formatter`): string

Get the locale for which the formatter was created.

### Parameters

`formatter`

  The formatter resource

### Return Values

The locale name

### Examples

Example #1 msgfmt_get_locale() example

`<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>`

The above example will output:

    en_US

### See Also

- msgfmt_create() - Constructs a new Message Formatter

# MessageFormatter::getPattern

# msgfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

### Description

Object-oriented style

public MessageFormatter::getPattern(): string|false

Procedural style

msgfmt_get_pattern(MessageFormatter `$formatter`): string|false

Get the pattern used by the formatter

### Parameters

`formatter`

  The message formatter

### Return Values

The pattern string for this message formatter, or `false` on failure.

### Examples

Example #1 msgfmt_get_pattern() example

`<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";
$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>`

The above example will output:

    Default pattern: '{0,number} monkeys on {1,number} trees'
    Formatting result: 123 monkeys on 456 trees
    New pattern: '{0,number} trees hosting {1,number} monkeys'
    Formatted number: 123 trees hosting 456 monkeys

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_set_pattern() - Set the pattern used by the formatter

# MessageFormatter::parse

# msgfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

### Description

Object-oriented style

public MessageFormatter::parse(string `$string`): array|false

Procedural style

msgfmt_parse(MessageFormatter `$formatter`, string `$string`): array|false

Parses input string and return any extracted items as an array.

### Parameters

`formatter`

  The message formatter

`string`

  The string to parse

### Return Values

An array containing the items extracted, or `false` on error

### Examples

Example #1 msgfmt_parse() example

`<?php
$fmt = msgfmt_create('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = msgfmt_parse($fmt, "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);
$fmt = msgfmt_create('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = msgfmt_parse($fmt, "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = $fmt->parse("4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);
$fmt = new MessageFormatter('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = $fmt->parse("4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>`

The above example will output:

    array (
      0 => 4560,
      1 => 123,
      2 => 37.073,
    )
    array (
      0 => 4560,
      1 => 123,
      2 => 37.073,
    )

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_format() - Format the message
- msgfmt_parse_message() - Quick parse input string

# MessageFormatter::parseMessage

# msgfmt_parse_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

### Description

Object-oriented style

public static MessageFormatter::parseMessage(string `$locale`, string `$pattern`, string `$message`): array|false

Procedural style

msgfmt_parse_message(string `$locale`, string `$pattern`, string `$message`): array|false

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept.

### Parameters

`locale`

  The locale to use for parsing locale-dependent parts

`pattern`

  The pattern with which to parse the `message`.

`message`

  The string to parse, conforming to the `pattern`.

### Return Values

An array containing items extracted, or `false` on error

### Examples

Example #1 msgfmt_parse_message() example

`<?php
$fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
"4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);
$fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
"4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>`

Example #2 OO example

`<?php
$fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
"4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);
$fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
"4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>`

The above example will output:

    array (
      0 => 4560,
      1 => 123,
      2 => 37.073,
    )
    array (
      0 => 4560,
      1 => 123,
      2 => 37.073,
    )

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_format_message() - Quick format message
- msgfmt_parse() - Parse input string according to pattern

# MessageFormatter::setPattern

# msgfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

### Description

Object-oriented style

public MessageFormatter::setPattern(string `$pattern`): bool

Procedural style

msgfmt_set_pattern(MessageFormatter `$formatter`, string `$pattern`): bool

Set the pattern used by the formatter

### Parameters

`formatter`

  The message formatter

`pattern`

  The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 msgfmt_set_pattern() example

`<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>`

Example #2 OO example

`<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";
$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>`

The above example will output:

    Default pattern: '{0,number} monkeys on {1,number} trees'
    Formatting result: 123 monkeys on 456 trees
    New pattern: '{0,number} trees hosting {1,number} monkeys'
    Formatted number: 123 trees hosting 456 monkeys

### See Also

- msgfmt_create() - Constructs a new Message Formatter
- msgfmt_get_pattern() - Get the pattern used by the formatter

## Table of Contents

- MessageFormatter::create — Constructs a new Message Formatter
- MessageFormatter::format — Format the message
- MessageFormatter::formatMessage — Quick format message
- MessageFormatter::getErrorCode — Get the error code from last operation
- MessageFormatter::getErrorMessage — Get the error text from the last operation
- MessageFormatter::getLocale — Get the locale for which the formatter was created
- MessageFormatter::getPattern — Get the pattern used by the formatter
- MessageFormatter::parse — Parse input string according to pattern
- MessageFormatter::parseMessage — Quick parse input string
- MessageFormatter::setPattern — Set the pattern used by the formatter

# The IntlCalendar class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

## Introduction

## Class synopsis

class IntlCalendar {
/* Constants */
public const int FIELD_ERA;
public const int FIELD_YEAR;
public const int FIELD_MONTH;
public const int FIELD_WEEK_OF_YEAR;
public const int FIELD_WEEK_OF_MONTH;
public const int FIELD_DATE;
public const int FIELD_DAY_OF_YEAR;
public const int FIELD_DAY_OF_WEEK;
public const int FIELD_DAY_OF_WEEK_IN_MONTH;
public const int FIELD_AM_PM;
public const int FIELD_HOUR;
public const int FIELD_HOUR_OF_DAY;
public const int FIELD_MINUTE;
public const int FIELD_SECOND;
public const int FIELD_MILLISECOND;
public const int FIELD_ZONE_OFFSET;
public const int FIELD_DST_OFFSET;
public const int FIELD_YEAR_WOY;
public const int FIELD_DOW_LOCAL;
public const int FIELD_EXTENDED_YEAR;
public const int FIELD_JULIAN_DAY;
public const int FIELD_MILLISECONDS_IN_DAY;
public const int FIELD_IS_LEAP_MONTH;
public const int FIELD_FIELD_COUNT;
public const int FIELD_DAY_OF_MONTH;
public const int DOW_SUNDAY;
public const int DOW_MONDAY;
public const int DOW_TUESDAY;
public const int DOW_WEDNESDAY;
public const int DOW_THURSDAY;
public const int DOW_FRIDAY;
public const int DOW_SATURDAY;
public const int DOW_TYPE_WEEKDAY;
public const int DOW_TYPE_WEEKEND;
public const int DOW_TYPE_WEEKEND_OFFSET;
public const int DOW_TYPE_WEEKEND_CEASE;
public const int WALLTIME_FIRST;
public const int WALLTIME_LAST;
public const int WALLTIME_NEXT_VALID;
/* Methods */
private __construct()
public add(int `$field`, int `$value`): bool
public after(IntlCalendar `$other`): bool
public before(IntlCalendar `$other`): bool
public clear(?int `$field` = `null`): true
public static createInstance(IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`, ?string `$locale` = `null`): ?IntlCalendar
public equals(IntlCalendar `$other`): bool
public fieldDifference(float `$timestamp`, int `$field`): int|false
public static fromDateTime(DateTime|string `$datetime`, ?string `$locale` = `null`): ?IntlCalendar
public get(int `$field`): int|false
public getActualMaximum(int `$field`): int|false
public getActualMinimum(int `$field`): int|false
public static getAvailableLocales(): array
public getDayOfWeekType(int `$dayOfWeek`): int|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public getFirstDayOfWeek(): int|false
public getGreatestMinimum(int `$field`): int|false
public static getKeywordValuesForLocale(string `$keyword`, string `$locale`, bool `$onlyCommon`): IntlIterator|false
public getLeastMaximum(int `$field`): int|false
public getLocale(int `$type`): string|false
public getMaximum(int `$field`): int|false
public getMinimalDaysInFirstWeek(): int|false
public getMinimum(int `$field`): int|false
public static getNow(): float
public getRepeatedWallTimeOption(): int
public getSkippedWallTimeOption(): int
public getTime(): float|false
public getTimeZone(): IntlTimeZone|false
public getType(): string
public getWeekendTransition(int `$dayOfWeek`): int|false
public inDaylightTime(): bool
public isEquivalentTo(IntlCalendar `$other`): bool
public isLenient(): bool
public isSet(int `$field`): bool
public isWeekend(?float `$timestamp` = `null`): bool
public roll(int `$field`, int|bool `$value`): bool
public set(int `$field`, int `$value`): true
public set(
int `$year`,
int `$month`,
int `$dayOfMonth` = NULL,
int `$hour` = NULL,
int `$minute` = NULL,
int `$second` = NULL
): true
public setDate(int `$year`, int `$month`, int `$dayOfMonth`): void
public setDateTime(
int `$year`,
int `$month`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
?int `$second` = `null`
): void
public setFirstDayOfWeek(int `$dayOfWeek`): true
public setLenient(bool `$lenient`): true
public setMinimalDaysInFirstWeek(int `$days`): true
public setRepeatedWallTimeOption(int `$option`): true
public setSkippedWallTimeOption(int `$option`): true
public setTime(float `$timestamp`): bool
public setTimeZone(IntlTimeZone|DateTimeZone|string|null `$timezone`): bool
public toDateTime(): DateTime|false
}

## Predefined Constants

`IntlCalendar::FIELD_ERA` int

  Calendar field numerically representing an era, for instance `1` for AD and `0` for BC in the Gregorian/Julian calendars and `235` for the Heisei (平成) era in the Japanese calendar. Not all calendars have more than one era.

`IntlCalendar::FIELD_YEAR` int

  Calendar field for the year. This is not unique across eras. If the calendar type has more than one era, generally the minimum value for this field will be `1`.

`IntlCalendar::FIELD_MONTH` int

  Calendar field for the month. The month sequence is zero-based, so January (here used to signify the first month of the calendar; this may be called another name, such as Muharram in the Islamic calendar) is represented by `0`, February by `1`, …, December by `11` and, for calendars that have it, the 13th or leap month by `12`.

`IntlCalendar::FIELD_WEEK_OF_YEAR` int

  Calendar field for the number of the week of the year. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

`IntlCalendar::FIELD_WEEK_OF_MONTH` int

  Calendar field for the number of the week of the month. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

`IntlCalendar::FIELD_DATE` int

  Calendar field for the day of the month. The same as `IntlCalendar::FIELD_DAY_OF_MONTH`, which has a clearer name.

`IntlCalendar::FIELD_DAY_OF_YEAR` int

  Calendar field for the day of the year. For the Gregorian calendar, starts with `1` and ends with `365` or `366`.

`IntlCalendar::FIELD_DAY_OF_WEEK` int

  Calendar field for the day of the week. Its values start with `1` (Sunday, see `IntlCalendar::DOW_SUNDAY` and subsequent constants) and the last valid value is 7 (Saturday).

`IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH` int

  Given a day of the week (Sunday, Monday, …), this calendar field assigns an ordinal to such a day of the week in a specific month. Thus, if the value of this field is `1` and the value of the day of the week is `2` (Monday), then the set day of the month is the 1st Monday of the month; the maximum value is `5`.

  Additionally, the value `0` and negative values are also allowed. The value `0` encompasses the seven days that occur immediately before the first seven days of a month (which therefore have a ‘day of week in month’ with value `1`). Negative values starts counting from the end of the month – `-1` points to the last occurrence of a day of the week in a month, `-2` to the second last, and so on.

  Unlike `IntlCalendar::FIELD_WEEK_OF_MONTH` and `IntlCalendar::FIELD_WEEK_OF_YEAR`, this value does not depend on IntlCalendar::getFirstDayOfWeek() or on IntlCalendar::getMinimalDaysInFirstWeek(). The first Monday is the first Monday, even if it occurs in a week that belongs to the previous month.

`IntlCalendar::FIELD_AM_PM` int

  Calendar field indicating whether a time is before noon (value `0`, AM) or after (`1`). Midnight is AM, noon is PM.

`IntlCalendar::FIELD_HOUR` int

  Calendar field for the hour, without specifying whether itʼs in the morning or in the afternoon. Valid values are `0` to `11`.

`IntlCalendar::FIELD_HOUR_OF_DAY` int

  Calendar field for the full (24h) hour of the day. Valid values are `0` to `23`.

`IntlCalendar::FIELD_MINUTE` int

  Calendar field for the minutes component of the time.

`IntlCalendar::FIELD_SECOND` int

  Calendar field for the seconds component of the time.

`IntlCalendar::FIELD_MILLISECOND` int

  Calendar field the milliseconds component of the time.

`IntlCalendar::FIELD_ZONE_OFFSET` int

  Calendar field indicating the raw offset of the timezone, in milliseconds. The raw offset is the timezone offset, excluding any offset due to daylight saving time.

`IntlCalendar::FIELD_DST_OFFSET` int

  Calendar field for the daylight saving time offset of the calendarʼs timezone, in milliseconds, if active for calendarʼs time.

`IntlCalendar::FIELD_YEAR_WOY` int

  Calendar field representing the year for week of year purposes.

`IntlCalendar::FIELD_DOW_LOCAL` int

  Calendar field for the localized day of the week. This is a value between `1` and `7`, `1` being used for the day of the week that matches the value returned by IntlCalendar::getFirstDayOfWeek().

`IntlCalendar::FIELD_EXTENDED_YEAR` int

  Calendar field for a year number representation that is continuous across eras. For the Gregorian calendar, the value of this field matches that of `IntlCalendar::FIELD_YEAR` for AD years; a BC year `y` is represented by `-y + 1`.

`IntlCalendar::FIELD_JULIAN_DAY` int

  Calendar field for a modified Julian day number. It is different from a conventional Julian day number in that its transitions occur at local zone midnight rather than at noon UTC. It uniquely identifies a date.

`IntlCalendar::FIELD_MILLISECONDS_IN_DAY` int

  Calendar field encompassing the information in `IntlCalendar::FIELD_HOUR_OF_DAY`, `IntlCalendar::FIELD_MINUTE`, `IntlCalendar::FIELD_SECOND` and `IntlCalendar::FIELD_MILLISECOND`. Range is from the `0` to `24 * 3600 * 1000 - 1`. It is not the amount of milliseconds elapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time.

`IntlCalendar::FIELD_IS_LEAP_MONTH` int

  Calendar field whose value is `1` for indicating a leap month and `0` otherwise.

`IntlCalendar::FIELD_FIELD_COUNT` int

  The total number of fields.

`IntlCalendar::FIELD_DAY_OF_MONTH` int

  Alias for `IntlCalendar::FIELD_DATE`.

`IntlCalendar::DOW_SUNDAY` int

  Sunday.

`IntlCalendar::DOW_MONDAY` int

  Monday.

`IntlCalendar::DOW_TUESDAY` int

  Tuesday.

`IntlCalendar::DOW_WEDNESDAY` int

  Wednesday.

`IntlCalendar::DOW_THURSDAY` int

  Thursday.

`IntlCalendar::DOW_FRIDAY` int

  Friday.

`IntlCalendar::DOW_SATURDAY` int

  Saturday.

`IntlCalendar::DOW_TYPE_WEEKDAY` int

  Output of IntlCalendar::getDayOfWeekType() indicating a day of week is a weekday.

`IntlCalendar::DOW_TYPE_WEEKEND` int

  Output of IntlCalendar::getDayOfWeekType() indicating a day of week belongs to the weekend.

`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET` int

  Output of IntlCalendar::getDayOfWeekType() indicating the weekend begins during the given day of week.

`IntlCalendar::DOW_TYPE_WEEKEND_CEASE` int

  Output of IntlCalendar::getDayOfWeekType() indicating the weekend ends during the given day of week.

`IntlCalendar::WALLTIME_FIRST` int

  Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour less and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the first occurrence of such wall time.

`IntlCalendar::WALLTIME_LAST` int

  Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour after and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the second occurrence of such wall time.

`IntlCalendar::WALLTIME_NEXT_VALID` int

  Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the instant when the daylight saving time transition occurs (begins).

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# IntlCalendar::add

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::add — Add a (signed) amount of time to a field

### Description

Object-oriented style

public IntlCalendar::add(int `$field`, int `$value`): bool

Procedural style

intlcal_add(IntlCalendar `$calendar`, int `$field`, int `$value`): bool

Add a signed amount to a field. Adding a positive amount allows advances in time, even if the numeric value of the field decreases (e.g. when working with years in BC dates).

Other fields may need to adjusted – for instance, adding a month to the 31st of January will result in the 28th (or 29th) of February. Contrary to IntlCalendar::roll(), when a value wraps around, more significant fields may change. For instance, adding a day to the 31st of January will result in the 1st of February, not the 1st of January.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

`value`

  The signed amount to add to the current field. If the amount is positive, the instant will be moved forward; if it is negative, the instant will be moved into the past. The unit is implicit to the field type. For instance, hours for `IntlCalendar::FIELD_HOUR_OF_DAY`.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 IntlCalendar::add()

`<?php
ini_set('intl.default_locale', 'fr_FR');
ini_set('date.timezone', 'UTC');
$cal = new IntlGregorianCalendar(2012, 0 /* January */, 31);
echo IntlDateFormatter::formatObject($cal), "\n";
$cal->add(IntlCalendar::FIELD_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";
$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";`

The above example will output:

    31 janv. 2012 00:00:00
    29 févr. 2012 00:00:00
    1 mars 2012 00:00:00

# IntlCalendar::after

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::after — Whether this objectʼs time is after that of the passed object

### Description

Object-oriented style

public IntlCalendar::after(IntlCalendar `$other`): bool

Procedural style

intlcal_after(IntlCalendar `$calendar`, IntlCalendar `$other`): bool

Returns whether this objectʼs time succeeds the argumentʼs time.

### Parameters

`calendar`

  An IntlCalendar instance.

`other`

  The calendar whose time will be checked against the primary objectʼs time.

### Return Values

Returns `true` if this objectʼs current time is after that of the `calendar` argumentʼs time. Returns `false` otherwise.

On failure `false` is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

### Examples

Example #1 IntlCalendar::after()

`<?php
$cal1 = IntlCalendar::createInstance();
$cal2 = clone $cal1;
var_dump($cal1->after($cal2), //false
$cal2->after($cal1)); //false
$cal1->roll(IntlCalendar::FIELD_MILLISECOND, true);
var_dump($cal1->after($cal2), //true
$cal2->after($cal1)); //false`

# IntlCalendar::before

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::before — Whether this objectʼs time is before that of the passed object

### Description

Object-oriented style

public IntlCalendar::before(IntlCalendar `$other`): bool

Procedural style

intlcal_before(IntlCalendar `$calendar`, IntlCalendar `$other`): bool

Returns whether this objectʼs time precedes the argumentʼs time.

### Parameters

`calendar`

  An IntlCalendar instance.

`other`

  The calendar whose time will be checked against the primary objectʼs time.

### Return Values

Returns `true` if this objectʼs current time is before that of the `calendar` argumentʼs time. Returns `false` otherwise.

On failure `false` is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

# IntlCalendar::clear

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::clear — Clear a field or all fields

### Description

Object-oriented style

public IntlCalendar::clear(?int `$field` = `null`): true

Procedural style

intlcal_clear(IntlCalendar `$calendar`, ?int `$field` = `null`): true

Clears either all of the fields or a specific field. A cleared field is marked as unset, giving it the lowest priority against overlapping fields or even default values when calculating the time. Additionally, its value is set to `0`, though given the fieldʼs low priority, its value may have been internally set to another value by the time the field has finished been queried.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.

### Examples

Example #1 IntlCalendar::clear() examples

`<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'UTC');
$fields = array(
'FIELD_ERA' => 0,
'FIELD_YEAR' => 1,
'FIELD_MONTH' => 2,
'FIELD_WEEK_OF_YEAR' => 3,
'FIELD_WEEK_OF_MONTH' => 4,
'FIELD_DATE' => 5,
'FIELD_DAY_OF_YEAR' => 6,
'FIELD_DAY_OF_WEEK' => 7,
'FIELD_DAY_OF_WEEK_IN_MONTH' => 8,
'FIELD_AM_PM' => 9,
'FIELD_HOUR' => 10,
'FIELD_HOUR_OF_DAY' => 11,
'FIELD_MINUTE' => 12,
'FIELD_SECOND' => 13,
'FIELD_MILLISECOND' => 14,
'FIELD_ZONE_OFFSET' => 15,
'FIELD_DST_OFFSET' => 16,
'FIELD_YEAR_WOY' => 17,
'FIELD_DOW_LOCAL' => 18,
'FIELD_EXTENDED_YEAR' => 19,
'FIELD_JULIAN_DAY' => 20,
'FIELD_MILLISECONDS_IN_DAY' => 21,
'FIELD_IS_LEAP_MONTH' => 22,
'FIELD_FIELD_COUNT' => 23,
);
function getSetFields(IntlCalendar $cal) {
global $fields;
$ret = array();
foreach ($fields as $name => $value) {
if ($cal->isSet($value)) {
$ret[] = $name;
}
}
return $ret;
}
$cal = new IntlGregorianCalendar(2013, 2 /* March */, 15);
echo "After GregorianCalendar creation\n";
print_r(getSetFields($cal));
echo "\n";
echo IntlDateFormatter::formatObject($cal), "\n";
echo "After the formatter requested the extended year\n";
print_r(getSetFields($cal));
echo "\n";
$cal->clear(IntlCalendar::FIELD_YEAR);
echo "After the year has been cleared, the date stays the same\n";
echo IntlDateFormatter::formatObject($cal), "\n";
echo "because FIELD_EXTENDED_YEAR is still set\n";
print_r(getSetFields($cal));
echo "\n";
var_dump($cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR));
echo "After the extended year has been cleared\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";
echo "\n";
echo "After the fields are recalculated,\n"
. " extended year is set again (to 1970)\n";
print_r(getSetFields($cal));
echo "\n";
$cal->clear();
echo "After calling variant with no arguments\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";`

The above example will output:

    After GregorianCalendar creation
    Array
    (
        [0] => FIELD_ERA
        [1] => FIELD_YEAR
        [2] => FIELD_MONTH
        [3] => FIELD_DATE
    )

    15/03/2013 00:00:00
    After the formatter requested the extended year
    Array
    (
        [0] => FIELD_ERA
        [1] => FIELD_YEAR
        [2] => FIELD_MONTH
        [3] => FIELD_DATE
        [4] => FIELD_EXTENDED_YEAR
    )

    After the year has been cleared, the date stays the same
    15/03/2013 00:00:00
    because FIELD_EXTENDED_YEAR is still set
    Array
    (
        [0] => FIELD_ERA
        [1] => FIELD_MONTH
        [2] => FIELD_DATE
        [3] => FIELD_EXTENDED_YEAR
    )

    bool(true)
    After the extended year has been cleared
    Array
    (
        [0] => FIELD_ERA
        [1] => FIELD_MONTH
        [2] => FIELD_DATE
    )
    15/03/1970 00:00:00

    After the fields are recalculated,
     extended year is set again (to 1970)
    Array
    (
        [0] => FIELD_ERA
        [1] => FIELD_MONTH
        [2] => FIELD_DATE
        [3] => FIELD_EXTENDED_YEAR
    )

    After calling variant with no arguments
    Array
    (
    )
    01/01/1970 00:00:00

# IntlCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::__construct — Private constructor for disallowing instantiation

### Description

private IntlCalendar::__construct()

A private constructor for disallowing instantiation with the new operator.

Call IntlCalendar::createInstance() instead.

### Parameters

This function has no parameters.

# IntlCalendar::createInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::createInstance — Create a new IntlCalendar

### Description

Object-oriented style

public static IntlCalendar::createInstance(IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`, ?string `$locale` = `null`): ?IntlCalendar

Procedural style

intlcal_create_instance(IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`, ?string `$locale` = `null`): ?IntlCalendar

Given a timezone and locale, this method creates an IntlCalendar object. This factory method may return a subclass of IntlCalendar.

The calendar created will represent the time instance at which it was created, based on the system time. The fields can all be cleared by calling IntCalendar::clear() with no arguments. See also IntlGregorianCalendar::__construct().

### Parameters

`timezone`

  The timezone to use.

  - `null`, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  - An IntlTimeZone, which will be used directly.

  - A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  - A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as `"GMT+08:30"` are also accepted.

`locale`

  A locale to use or `null` to use the default locale.

### Return Values

The created IntlCalendar instance or `null` on failure.

### Examples

Example #1 IntlCalendar::createInstance()

`<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'Europe/Madrid');
$cal = IntlCalendar::createInstance();
echo "No arguments\n";
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";
echo "Explicit timezone\n";
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT());
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";
echo "Explicit locale (with calendar)\n";
$cal = IntlCalendar::createInstance(NULL, 'es_ES@calendar=persian');
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));`

The above example will output:

    No arguments
    string(21) "IntlGregorianCalendar"
    string(68) "martes 18 de junio de 2013 14:11:02 Hora de verano de Europa Central"

    Explicit timezone
    string(21) "IntlGregorianCalendar"
    string(45) "martes 18 de junio de 2013 12:11:02 GMT+00:00"

    Explicit locale (with calendar)
    string(12) "IntlCalendar"
    string(70) "martes 28 de Khordad de 1392 14:11:02 Hora de verano de Europa Central"

### See Also

- IntlGregorianCalendar::__construct() - Create the Gregorian Calendar class

# IntlCalendar::equals

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::equals — Compare time of two IntlCalendar objects for equality

### Description

Object-oriented style

public IntlCalendar::equals(IntlCalendar `$other`): bool

Procedural style

intlcal_equals(IntlCalendar `$calendar`, IntlCalendar `$other`): bool

Returns true if this calendar and the given calendar have the same time. The settings, calendar types and field states do not have to be the same.

### Parameters

`calendar`

  An IntlCalendar instance.

`other`

  The calendar to compare with the primary object.

### Return Values

Returns `true` if the current time of both this and the passed in IntlCalendar object are the same, or `false` otherwise.

On failure `false` is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

### Examples

Example #1 IntlCalendar::equals()

`<?php
ini_set('date.timezone', 'UTC');
$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
$cal2 = clone $cal1;
var_dump($cal1->equals($cal2)); //TRUE
//The locale is not included in the comparison
$cal2 = IntlCalendar::createInstance(NULL, 'pt_PT');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE
//And set fields state is not included as well
$cal2->clear(IntlCalendar::FIELD_YEAR);
var_dump($cal1->isSet(IntlCalendar::FIELD_YEAR) ==
$cal2->isSet(IntlCalendar::FIELD_YEAR)); //FALSE
var_dump($cal1->equals($cal2)); //TRUE
//Neither is the calendar type
$cal2 = IntlCalendar::createInstance(NULL, 'es_ES@calendar=islamic');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE
//Only the time is
$cal2 = clone $cal1;
$cal2->setTime($cal1->getTime() + 1.);
var_dump($cal1->equals($cal2)); //FALSE`

# IntlCalendar::fieldDifference

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time

### Description

Object-oriented style

public IntlCalendar::fieldDifference(float `$timestamp`, int `$field`): int|false

Procedural style

intlcal_field_difference(IntlCalendar `$calendar`, float `$timestamp`, int `$field`): int|false

Return the difference between the given time and the time this object is set to, with respect to the quantity specified the `field` parameter.

This method is meant to be called successively, first with the most significant field of interest down to the least significant field. To this end, as a side effect, this calendarʼs value for the field specified is advanced by the amount returned.

### Parameters

`calendar`

  An IntlCalendar instance.

`timestamp`

  The time against which to compare the quantity represented by the `field`. For the result to be positive, the time given for this parameter must be ahead of the time of the object the method is being invoked on.

`field`

  The field that represents the quantity being compared.

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

Returns a (signed) difference of time in the unit associated with the specified field or `false` on failure.

### Examples

Example #1 IntlCalendar::fieldDifference()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');
$cal1 = IntlCalendar::fromDateTime('2012-02-29 09:00:11');
$cal2 = IntlCalendar::fromDateTime('2013-03-01 09:19:29');
$time = $cal2->getTime();
echo "Time before: ", IntlDateFormatter::formatObject($cal1), "\n";
printf(
"The difference in time is %d year(s), %d month(s), "
. "%d day(s), %d hour(s) and %d minute(s)\n",
$cal1->fieldDifference($time, IntlCalendar::FIELD_YEAR),
$cal1->fieldDifference($time, IntlCalendar::FIELD_MONTH),
$cal1->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_MONTH),
$cal1->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY),
$cal1->fieldDifference($time, IntlCalendar::FIELD_MINUTE)
);
//now it was advanced to the target time, exception for the seconds,
//for which we did not measure the difference
echo "Time after: ", IntlDateFormatter::formatObject($cal1), "\n";`

The above example will output:

    Time before: 29 févr. 2012 09:00:11
    The difference in time is 1 year(s), 0 month(s), 1 day(s), 0 hour(s) and 19 minute(s)
    Time after: 1 mars 2013 09:19:11

# IntlCalendar::fromDateTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a2)

IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string

### Description

Object-oriented style

public static IntlCalendar::fromDateTime(DateTime|string `$datetime`, ?string `$locale` = `null`): ?IntlCalendar

Procedural style

intlcal_from_date_time(DateTime|string `$datetime`, ?string `$locale` = `null`): ?IntlCalendar

Creates an IntlCalendar object either from a DateTime object or from a string from which a DateTime object can be built.

The new calendar will represent not only the same instant as the given DateTime (subject to precision loss for dates very far into the past or future), but also the same timezone (subject to the caveat that different timezone databases will be used, and therefore the results may differ).

### Parameters

`datetime`

  A DateTime object or a string that can be passed to DateTime::__construct().

### Return Values

The created IntlCalendar object or `null` in case of failure. If a string is passed, any exception that occurs inside the DateTime constructor is propagated.

### Examples

Example #1 IntlCalendar::fromDateTime()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
//same as IntlCalendar::fromDateTime(new DateTime(...))
$cal1 = IntlCalendar::fromDateTime('2013-02-28 00:01:02 Europe/Berlin', 'de_DE');
//Note the timezone is Europe/Berlin, not the default Europe/Lisbon
echo IntlDateFormatter::formatObject($cal1, 'yyyy MMMM d HH:mm:ss VVVV', 'de_DE'), "\n";`

The above example will output:

    2013 Februar 28 00:01:02 Deutschland Zeit

# IntlCalendar::get

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::get — Get the value for a field

### Description

Object-oriented style

public IntlCalendar::get(int `$field`): int|false

Procedural style

intlcal_get(IntlCalendar `$calendar`, int `$field`): int|false

Gets the value for a specific field.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An integer with the value of the time field.

### Examples

Example #1 IntlCalendar::get()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
$class = new ReflectionClass('IntlCalendar');
$fields = array();
foreach ($class->getConstants() as $name => $val) {
if (strpos($name, 'FIELD_') !== 0 || $val > 22)
continue;
$fields[$val] = $name;
}
$cal = IntlCalendar::createInstance(); // current time
var_dump(IntlDateFormatter::formatObject($cal));
foreach ($fields as $val => $name) {
echo "$val ($name)", "\n ", $cal->get($val), "\n";
}`

The above example will output:

    string(23) "Jul 1, 2013, 4:44:44 AM"
    0 (FIELD_ERA)
        1
    1 (FIELD_YEAR)
        2013
    2 (FIELD_MONTH)
        6
    3 (FIELD_WEEK_OF_YEAR)
        27
    4 (FIELD_WEEK_OF_MONTH)
        1
    5 (FIELD_DAY_OF_MONTH)
        1
    6 (FIELD_DAY_OF_YEAR)
        182
    7 (FIELD_DAY_OF_WEEK)
        2
    8 (FIELD_DAY_OF_WEEK_IN_MONTH)
        1
    9 (FIELD_AM_PM)
        0
    10 (FIELD_HOUR)
        4
    11 (FIELD_HOUR_OF_DAY)
        4
    12 (FIELD_MINUTE)
        44
    13 (FIELD_SECOND)
        44
    14 (FIELD_MILLISECOND)
        551
    15 (FIELD_ZONE_OFFSET)
        0
    16 (FIELD_DST_OFFSET)
        3600000
    17 (FIELD_YEAR_WOY)
        2013
    18 (FIELD_DOW_LOCAL)
        2
    19 (FIELD_EXTENDED_YEAR)
        2013
    20 (FIELD_JULIAN_DAY)
        2456475
    21 (FIELD_MILLISECONDS_IN_DAY)
        17084551
    22 (FIELD_IS_LEAP_MONTH)
        0

# IntlCalendar::getActualMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time

### Description

Object-oriented style

public IntlCalendar::getActualMaximum(int `$field`): int|false

Procedural style

intlcal_get_actual_maximum(IntlCalendar `$calendar`, int `$field`): int|false

Returns a fieldʼs relative maximum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the smallest relative maximum for the field and would increment it until reaching the global maximum or the field value wraps around, in which the value returned would be the global maximum or the value before the wrapping, respectively.

For instance, in the gregorian calendar, the actual maximum value for the day of month would vary between `28` and `31`, depending on the month and year of the current time.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing the maximum value in the units associated with the given `field` or `false` on failure.

### Examples

Example #1 IntlCalendar::getActualMaximum()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
$cal = IntlCalendar::fromDateTime('2013-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28
$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29`

The above example will output:

    int(28)
    int(29)

### See Also

- IntlCalendar::getMaximum() - Get the global maximum value for a field
- IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
- IntlCalendar::getActualMinimum() - The minimum value for a field, considering the objectʼs current time

# IntlCalendar::getActualMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time

### Description

Object-oriented style

public IntlCalendar::getActualMinimum(int `$field`): int|false

Procedural style

intlcal_get_actual_minimum(IntlCalendar `$calendar`, int `$field`): int|false

Returns a fieldʼs relative minimum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the greatest relative minimum for the field and would decrement it until reaching the global minimum or the field value wraps around, in which the value returned would be the global minimum or the value before the wrapping, respectively.

For the Gregorian calendar, this is always the same as IntlCalendar::getMinimum().

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing the minimum value in the fieldʼs unit or `false` on failure.

### See Also

- IntlCalendar::getMinimum() - Get the global minimum value for a field
- IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field
- IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time

# IntlCalendar::getAvailableLocales

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getAvailableLocales — Get array of locales for which there is data

### Description

Object-oriented style

public static IntlCalendar::getAvailableLocales(): array

Procedural style

intlcal_get_available_locales(): array

Gives the list of locales for which calendars are installed. As of ICU 51, this is the list of all installed ICU locales.

### Parameters

This function has no parameters.

### Return Values

An array of strings, one for which locale.

### Examples

Example #1 IntlCalendar::getAvailableLocales()

`<?php
print_r(IntlCalendar::getAvailableLocales());`

The above example will output:

    Array
    (
        [0] => af
        [1] => af_NA
        [2] => af_ZA
        [3] => agq
        [4] => agq_CM
        [5] => ak
        [6] => ak_GH
        [7] => am
        [8] => am_ET
        [9] => ar
        [10] => ar_001
        [11] => ar_AE
        [12] => ar_BH
        [13] => ar_DJ
        … output abbreviated …
        [595] => zh_Hant_HK
        [596] => zh_Hant_MO
        [597] => zh_Hant_TW
        [598] => zu
        [599] => zu_ZA
    )

# IntlCalendar::getDayOfWeekType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two

### Description

Object-oriented style

public IntlCalendar::getDayOfWeekType(int `$dayOfWeek`): int|false

Procedural style

intlcal_get_day_of_week_type(IntlCalendar `$calendar`, int `$dayOfWeek`): int|false

Returns whether the passed day is a weekday (`IntlCalendar::DOW_TYPE_WEEKDAY`), a weekend day (`IntlCalendar::DOW_TYPE_WEEKEND`), a day during which a transition occurs into the weekend (`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`) or a day during which the weekend ceases (`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`).

If the return is either `IntlCalendar::DOW_TYPE_WEEKEND_OFFSET` or `IntlCalendar::DOW_TYPE_WEEKEND_CEASE`, then IntlCalendar::getWeekendTransition() can be called to obtain the time of the transition.

This function requires ICU 4.4 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

`dayOfWeek`

  One of the constants `IntlCalendar::DOW_SUNDAY`, `IntlCalendar::DOW_MONDAY`, …, `IntlCalendar::DOW_SATURDAY`.

### Return Values

Returns one of the constants `IntlCalendar::DOW_TYPE_WEEKDAY`, `IntlCalendar::DOW_TYPE_WEEKEND`, `IntlCalendar::DOW_TYPE_WEEKEND_OFFSET` or `IntlCalendar::DOW_TYPE_WEEKEND_CEASE` or `false` on failure.

### Examples

Example #1 IntlCalendar::getDayOfWeekType()

`<?php
foreach (array('en_US', 'ar_SA') as $locale) {
echo "Locale: ", Locale::getDisplayName($locale, "en_US"), "\n";
$cal = IntlCalendar::createInstance('UTC', $locale);
for ($i = IntlCalendar::DOW_SUNDAY; $i <= IntlCalendar::DOW_SATURDAY; $i++) {
$type = $cal->getDayOfWeekType($i);
$transition = ($type !== IntlCalendar::DOW_TYPE_WEEKDAY)
? $cal->getWeekendTransition($i)
: '';
echo $i, " ", $type, " ", $transition, "\n";
}
echo "\n";
}
?>`

The above example will output:

    Locale: English (United States)
    1 1 86400000
    2 0
    3 0
    4 0
    5 0
    6 0
    7 1 0

    Locale: Arabic (Saudi Arabia)
    1 0
    2 0
    3 0
    4 0
    5 0
    6 1 0
    7 1 86400000

# IntlCalendar::getErrorCode

# intlcal_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getErrorCode -- intlcal_get_error_code — Get last error code on the object

### Description

Object-oriented style (method):

public IntlCalendar::getErrorCode(): int|false

Procedural style:

intlcal_get_error_code(IntlCalendar `$calendar`): int|false

Returns the numeric ICU error code for the last call on this object (including cloning) or the IntlCalendar given for the `calendar` parameter (in the procedural‒style version). This may indicate only a warning (negative error code) or no error at all (`U_ZERO_ERROR`). The actual presence of an error can be tested with intl_is_failure().

Invalid arguments detected on the PHP side (before invoking functions of the ICU library) are not recorded for the purposes of this function.

The last error that occurred in any call to a function of the intl extension, including early argument errors, can be obtained with intl_get_error_code(). This function resets the global error code, but not the objectʼs error code.

### Parameters

`calendar`

  The calendar object, on the procedural style interface.

### Return Values

An ICU error code indicating either success, failure or a warning. Returns `false` on failure.

### Examples

Example #1 IntlCalendar::getErrorCode() and IntlCalendar::getErrorMessage()

`<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");
$intlcal = new IntlGregorianCalendar(2012, 1, 29);
var_dump(
$intlcal->getErrorCode(),
$intlcal->getErrorMessage()
);
$intlcal->fieldDifference(-1e100, IntlCalendar::FIELD_SECOND);
var_dump(
$intlcal->getErrorCode(),
$intlcal->getErrorMessage()
);`

The above example will output:

    int(0)
    string(12) "U_ZERO_ERROR"

    Warning: IntlCalendar::fieldDifference(): intlcal_field_difference: Call to ICU method has failed in /home/glopes/php/ws/example.php on line 10
    int(1)
    string(81) "intlcal_field_difference: Call to ICU method has failed: U_ILLEGAL_ARGUMENT_ERROR"

### See Also

- IntlCalendar::getErrorMessage() - Get last error message on the object
- intl_is_failure() - Check whether the given error code indicates failure
- intl_error_name() - Get symbolic name for a given error code
- intl_get_error_code() - Get the last error code
- intl_get_error_message() - Get description of the last error

# IntlCalendar::getErrorMessage

# intlcal_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getErrorMessage -- intlcal_get_error_message — Get last error message on the object

### Description

Object-oriented style (method):

public IntlCalendar::getErrorMessage(): string|false

Procedural style:

intlcal_get_error_message(IntlCalendar `$calendar`): string|false

Returns the error message (if any) associated with the error reported by IntlCalendar::getErrorCode() or intlcal_get_error_code(). If there is no associated error message, only the string representation of the name of the error constant will be returned. Otherwise, the message also includes a message set on the side of the PHP binding.

### Parameters

`calendar`

  The calendar object, on the procedural style interface.

### Return Values

The error message associated with last error that occurred in a function call on this object, or a string indicating the non-existence of an error. Returns `false` on failure.

### Examples

Example #1 IntlCalendar::getErrorMessage()

`<?php
$cal = IntlCalendar::createInstance('UTC', 'en_US');
var_dump($cal->getErrorMessage());
$cal->getWeekendTransition(IntlCalendar::DOW_WEDNESDAY);
var_dump($cal->getErrorMessage());`

The above example will output:

    string(12) "U_ZERO_ERROR"
    string(82) "intlcal_get_weekend_transition: Error calling ICU method: U_ILLEGAL_ARGUMENT_ERROR"

# IntlCalendar::getFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale

### Description

Object-oriented style

public IntlCalendar::getFirstDayOfWeek(): int|false

Procedural style

intlcal_get_first_day_of_week(IntlCalendar `$calendar`): int|false

The week day deemed to start a week, either the default value for this locale or the value set with IntlCalendar::setFirstDayOfWeek().

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

One of the constants `IntlCalendar::DOW_SUNDAY`, `IntlCalendar::DOW_MONDAY`, …, `IntlCalendar::DOW_SATURDAY` or `false` on failure.

### Examples

Example #1 IntlCalendar::getFirstDayOfWeek()

`<?php
ini_set('date.timezone', 'UTC');
$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
var_dump($cal1->getFirstDayOfWeek()); // Monday
$cal1->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal1->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 5
$cal2 = IntlCalendar::createInstance(NULL, 'en_US');
var_dump($cal2->getFirstDayOfWeek()); // Sunday
$cal2->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal2->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 6`

The above example will output:

    int(2)
    int(5)
    int(1)
    int(6)

### See Also

- IntlCalendar::setFirstDayOfWeek() - Set the day on which the week is deemed to start

# IntlCalendar::getGreatestMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field

### Description

Object-oriented style

public IntlCalendar::getGreatestMinimum(int `$field`): int|false

Procedural style

intlcal_get_greatest_minimum(IntlCalendar `$calendar`, int `$field`): int|false

Returns the largest local minimum for a field. This should be a value larger or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn larger or equal to that returned by IntlCalendar::getMinimum(). All these three functions return the same value for the Gregorian calendar.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing a field value, in the fieldʼs unit, or `false` on failure.

# IntlCalendar::getKeywordValuesForLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values

### Description

Object-oriented style

public static IntlCalendar::getKeywordValuesForLocale(string `$keyword`, string `$locale`, bool `$onlyCommon`): IntlIterator|false

Procedural style

intlcal_get_keyword_values_for_locale(string `$keyword`, string `$locale`, bool `$onlyCommon`): IntlIterator|false

For a given locale key, get the set of values for that key that would result in a different behavior. For now, only the `'calendar'` keyword is supported.

This function requires ICU 4.2 or later.

### Parameters

`keyword`

  The locale keyword for which relevant values are to be queried. Only `'calendar'` is supported.

`locale`

  The locale onto which the keyword/value pair are to be appended.

`onlyCommon`

  Whether to show only the values commonly used for the specified locale.

### Return Values

An iterator that yields strings with the locale keyword values or `false` on failure.

### Examples

Example #1 IntlCalendar::getKeyworkValuesForLocale()

`<?php
print_r(
iterator_to_array(
IntlCalendar::getKeywordValuesForLocale(
'calendar', 'fa_IR', true)));
print_r(
iterator_to_array(
IntlCalendar::getKeywordValuesForLocale(
'calendar', 'fa_IR', false)));`

The above example will output:

    Array
    (
        [0] => persian
        [1] => gregorian
        [2] => islamic
        [3] => islamic-civil
    )
    Array
    (
        [0] => persian
        [1] => gregorian
        [2] => islamic
        [3] => islamic-civil
        [4] => japanese
        [5] => buddhist
        [6] => roc
        [7] => hebrew
        [8] => chinese
        [9] => indian
        [10] => coptic
        [11] => ethiopic
        [12] => ethiopic-amete-alem
    )

# IntlCalendar::getLeastMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field

### Description

Object-oriented style

public IntlCalendar::getLeastMaximum(int `$field`): int|false

Procedural style

intlcal_get_least_maximum(IntlCalendar `$calendar`, int `$field`): int|false

Returns the smallest local maximumw for a field. This should be a value smaller or equal to that returned by IntlCalendar::getActualMaxmimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getMaximum().

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing a field value in the fieldʼs unit or `false` on failure.

### Examples

Example #1 Maxima examples

`<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'it_IT');
$cal = new IntlGregorianCalendar(2013, 3 /* April */, 6);
var_dump(
$cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 28
$cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 30
$cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH) // 31
);`

The above example will output:

    int(28)
    int(30)
    int(31)

### See Also

- IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time
- IntlCalendar::getMaximum() - Get the global maximum value for a field
- IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field

# IntlCalendar::getLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getLocale — Get the locale associated with the object

### Description

Object-oriented style

public IntlCalendar::getLocale(int `$type`): string|false

Procedural style

intlcal_get_locale(IntlCalendar `$calendar`, int `$type`): string|false

Returns the locale used by this calendar object.

### Parameters

`calendar`

  An IntlCalendar instance.

`type`

  Whether to fetch the actual locale (the locale from which the calendar data originates, with `Locale::ACTUAL_LOCALE`) or the valid locale, i.e., the most specific locale supported by ICU relatively to the requested locale – see `Locale::VALID_LOCALE`. From the most general to the most specific, the locales are ordered in this fashion – actual locale, valid locale, requested locale.

### Return Values

A locale string or `false` on failure.

### Examples

Example #1 IntlCalendar::getLocale()

`<?php
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT(), 'en_US_CALIFORNIA');
var_dump(
$cal->getLocale(Locale::ACTUAL_LOCALE),
$cal->getLocale(Locale::VALID_LOCALE)
);`

The above example will output:

    string(2) "en"
    string(5) "en_US"

# IntlCalendar::getMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMaximum — Get the global maximum value for a field

### Description

Object-oriented style

public IntlCalendar::getMaximum(int `$field`): int|false

Procedural style

intlcal_get_maximum(IntlCalendar `$calendar`, int `$field`): int|false

Gets the global maximum for a field, in this specific calendar. This value is larger or equal to that returned by IntlCalendar::getActualMaximum(), which is in its turn larger or equal to that returned by IntlCalendar::getLeastMaximum().

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing a field value in the fieldʼs unit or `false` on failure.

### See Also

- IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time
- IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
- IntlCalendar::getMinimum() - Get the global minimum value for a field

# IntlCalendar::getMinimalDaysInFirstWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have

### Description

Object-oriented style

public IntlCalendar::getMinimalDaysInFirstWeek(): int|false

Procedural style

intlcal_get_minimal_days_in_first_week(IntlCalendar `$calendar`): int|false

Returns the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous yearʼs last week.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

An int representing a number of days or `false` on failure.

### Examples

Example #1 IntlCalendar::getMinimalDaysInFirstWeek()

`<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'en_US');
$cal = new IntlGregorianCalendar(2013, 0 /* January */, 2);
var_dump(IntlDateFormatter::formatObject($cal, 'cccc')); // Wednesday
var_dump($cal->getMinimalDaysInFirstWeek(), // 1
$cal->getFirstDayofWeek()); // 1 (Sunday)
// Week 1 of 2013
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));
$cal->setMinimalDaysInFirstWeek(4);
// Still Week 1 of 2013 (1st week has 5 days in the new year)
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));
$cal->setMinimalDaysInFirstWeek(6);
// Week 53 of 2012
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));`

The above example will output:

    string(9) "Wednesday"
    int(1)
    int(1)
    string(14) "Week 1 of 2013"
    string(14) "Week 1 of 2013"
    string(15) "Week 53 of 2012"

# IntlCalendar::getMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMinimum — Get the global minimum value for a field

### Description

Object-oriented style

public IntlCalendar::getMinimum(int `$field`): int|false

Procedural style

intlcal_get_minimum(IntlCalendar `$calendar`, int `$field`): int|false

Gets the global minimum for a field, in this specific calendar. This value is smaller or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getGreatestMinimum(). For the Gregorian calendar, these three functions always return the same value (for each field).

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

An int representing a value for the given field in the fieldʼs unit or `false` on failure.

# IntlCalendar::getNow

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getNow — Get number representing the current time

### Description

Object-oriented style

public static IntlCalendar::getNow(): float

Procedural style

intlcal_get_now(): float

The number of milliseconds that have passed since the reference date. This number is derived from the system time.

### Parameters

This function has no parameters.

### Return Values

A float representing a number of milliseconds since the epoch, not counting leap seconds.

### Examples

Example #1 IntlCalendar::getNow()

`<?php
$formatter = IntlDateFormatter::create('es_ES',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'Europe/Madrid');
$val = IntlCalendar::getNow();
var_dump($val);
echo $formatter->format(IntlCalendar::getNow() / 1000.), "\n";`

The above example will output:

    float(1371425814666)
    lunes, 17 de junio de 2013 01:36:54 Hora de verano de Europa central

# IntlCalendar::getRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time

### Description

Object-oriented style

public IntlCalendar::getRepeatedWallTimeOption(): int

Procedural style

intlcal_get_repeated_wall_time_option(IntlCalendar `$calendar`): int

Gets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is `IntlCalendar::WALLTIME_LAST`.

This function requires ICU 4.9 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

One of the constants `IntlCalendar::WALLTIME_FIRST` or `IntlCalendar::WALLTIME_LAST`.

### Examples

Example #1 IntlCalendar::getRepeatedWallTimeOption()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);
//On October 27th at 0200, the clock goes back 1 hour and from GMT+01 to GMT+00
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30);
var_dump($cal->getRepeatedWalltimeOption()); // 0 WALLTIME_LAST
$formatter = IntlDateFormatter::create(
NULL,
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000.));
$cal->setRepeatedWalltimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getRepeatedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);
var_dump($formatter->format($cal->getTime() / 1000.));`

The above example will output:

    int(0)
    string(42) "Sunday, October 27, 2013 at 1:30:00 AM GMT"
    int(1)
    string(43) "Sunday, October 27, 2013 at 12:30:00 AM GMT"

### See Also

- IntlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
- IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
- IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

# IntlCalendar::getSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time

### Description

Object-oriented style

public IntlCalendar::getSkippedWallTimeOption(): int

Procedural style

intlcal_get_skipped_wall_time_option(IntlCalendar `$calendar`): int

Gets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is `IntlCalendar::WALLTIME_LAST`.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

One of the constants `IntlCalendar::WALLTIME_FIRST`, `IntlCalendar::WALLTIME_LAST` or `IntlCalendar::WALLTIME_NEXT_VALID`.

### Examples

Example #1 IntlCalendar::getSkippedWallTimeOption()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);
//On March 31st at 0100, the clock goes forward 1 hour and from GMT+00 to GMT+01
$cal = new IntlGregorianCalendar(2013, 2 /* March */, 31, 1, 30);
var_dump(
$cal->isLenient(), // true
$cal->getSkippedWalltimeOption() // 0 WALLTIME_LAST
);
$formatter = IntlDateFormatter::create(
NULL,
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000));
$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getSkippedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);
var_dump($formatter->format($cal->getTime() / 1000));
$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_NEXT_VALID);
var_dump($cal->getSkippedWalltimeOption()); // 2 WALLTIME_NEXT_VALID
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);
var_dump($formatter->format($cal->getTime() / 1000));`

The above example will output:

    bool(true)
    int(0)
    string(40) "Sunday, March 31, 2013 at 1:30:00 AM GMT"
    int(1)
    string(41) "Sunday, March 31, 2013 at 12:30:00 AM GMT"
    int(2)
    string(40) "Sunday, March 31, 2013 at 1:00:00 AM GMT"

### See Also

- IntlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
- IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
- IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

# IntlCalendar::getTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getTime — Get time currently represented by the object

### Description

Object-oriented style

public IntlCalendar::getTime(): float|false

Procedural style

intlcal_get_time(IntlCalendar `$calendar`): float|false

Returns the time associated with this object, expressed as the number of milliseconds since the epoch.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC), or `false` on failure

### Examples

Example #1 IntlCalendar::getTime()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
$cal = new IntlGregorianCalendar(2013, 4 /* May */, 1, 0, 0, 0);
$time = $cal->getTime();
var_dump($time, $time / 1000 == strtotime('2013-05-01 00:00:00')); //true`

The above example will output:

    float(1367362800000)
    bool(true)

### See Also

- IntlCalendar::getNow() - Get number representing the current time

# IntlCalendar::getTimeZone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getTimeZone — Get the objectʼs timezone

### Description

Object-oriented style

public IntlCalendar::getTimeZone(): IntlTimeZone|false

Procedural style

intlcal_get_time_zone(IntlCalendar `$calendar`): IntlTimeZone|false

Returns the IntlTimeZone object associated with this calendar.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

An IntlTimeZone object corresponding to the one used internally in this object. Returns `false` on failure.

### Examples

Example #1 IntlCalendar::getTimeZone()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());
$cal->setTimeZone('UTC');
print_r($cal->getTimeZone());
$cal = IntlCalendar::fromDateTime('2012-01-01 00:00:00 GMT+03:33');
print_r($cal->getTimeZone());`

The above example will output:

    IntlTimeZone Object
    (
        [valid] => 1
        [id] => Europe/Lisbon
        [rawOffset] => 0
        [currentOffset] => 3600000
    )
    IntlTimeZone Object
    (
        [valid] => 1
        [id] => UTC
        [rawOffset] => 0
        [currentOffset] => 0
    )
    IntlTimeZone Object
    (
        [valid] => 1
        [id] => GMT+03:33
        [rawOffset] => 12780000
        [currentOffset] => 12780000
    )

### See Also

- IntlCalendar::setTimeZone() - Set the timezone used by this calendar
- IntlCalendar::createInstance() - Create a new IntlCalendar
- IntlGregorianCalendar::__construct() - Create the Gregorian Calendar class

# IntlCalendar::getType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getType — Get the calendar type

### Description

Object-oriented style

public IntlCalendar::getType(): string

Procedural style

intlcal_get_type(IntlCalendar `$calendar`): string

A string describing the type of this calendar. This is one of the valid values for the calendar keyword value `'calendar'`.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

A string representing the calendar type, such as `'gregorian'`, `'islamic'`, etc.

### Examples

Example #1 IntlCalendar::getType()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
$cal = IntlCalendar::createInstance(NULL, '@calendar=ethiopic-amete-alem');
var_dump($cal->getType());
$cal = new IntlGregorianCalendar();
var_dump($cal->getType());`

The above example will output:

    string(19) "ethiopic-amete-alem"
    string(9) "gregorian"

# IntlCalendar::getWeekendTransition

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends

### Description

Object-oriented style

public IntlCalendar::getWeekendTransition(int `$dayOfWeek`): int|false

Procedural style

intlcal_get_weekend_transition(IntlCalendar `$calendar`, int `$dayOfWeek`): int|false

Returns the number of milliseconds after midnight at which the weekend begins or ends.

This is only applicable for days of the week for which IntlCalendar::getDayOfWeekType() returns either `IntlCalendar::DOW_TYPE_WEEKEND_OFFSET` or `IntlCalendar::DOW_TYPE_WEEKEND_CEASE`. Calling this function for other days of the week is an error condition.

This function requires ICU 4.4 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

`dayOfWeek`

  One of the constants `IntlCalendar::DOW_SUNDAY`, `IntlCalendar::DOW_MONDAY`, …, `IntlCalendar::DOW_SATURDAY`.

### Return Values

The number of milliseconds into the day at which the weekend begins or ends or `false` on failure.

### Examples

See example on IntlCalendar::getDayOfWeekType().

# IntlCalendar::inDaylightTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time

### Description

Object-oriented style

public IntlCalendar::inDaylightTime(): bool

Procedural style

intlcal_in_daylight_time(IntlCalendar `$calendar`): bool

Whether, for the instant represented by this object and for this objectʼs timezone, daylight saving time is in place.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

Returns `true` if the date is in Daylight Savings Time, `false` otherwise.

On failure `false` is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

### Examples

Example #1 IntlCalendar::inDaylightTime()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1, 4, 56, 31);
var_dump($cal->inDaylightTime()); // true
$cal->set(IntlCalendar::FIELD_MONTH, 11 /* December */);
var_dump($cal->inDaylightTime()); // false
//DST end transition on 2013-10-27 at 0200 (wall time back 1 hour)
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30, 0);
var_dump($cal->inDaylightTime()); // false (default WALLTIME_LAST)
$cal->setRepeatedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1); // force time recalculation
var_dump($cal->inDaylightTime()); // true`

# IntlCalendar::isEquivalentTo

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time

### Description

Object-oriented style

public IntlCalendar::isEquivalentTo(IntlCalendar `$other`): bool

Procedural style

intlcal_is_equivalent_to(IntlCalendar `$calendar`, IntlCalendar `$other`): bool

Returns whether this and the given object are equivalent for all purposes except as to the time they have set. The locales do not have to match, as long as no change in behavior results from such mismatch. This includes the timezone, whether the lenient mode is set, the repeated and skipped wall time settings, the days of the week when the weekend starts and ceases and the times where such transitions occur. It may also include other calendar specific settings, such as the Gregorian/Julian transition instant.

### Parameters

`calendar`

  An IntlCalendar instance.

`other`

  The other calendar against which the comparison is to be made.

### Return Values

Assuming there are no argument errors, returns `true` if the calendars are equivalent except possibly for their set time.

### Examples

Example #1 IntlCalendar::isEquivalentTo()

`<?php
$cal1 = IntlCalendar::createInstance('Europe/Lisbon', 'pt_PT');
$cal2 = IntlCalendar::createInstance('Europe/Lisbon', 'es_ES');
$cal2->clear();
var_dump($cal1->isEquivalentTo($cal2)); // true
$cal3 = IntlCalendar::createInstance('Europe/Lisbon', 'en_US');
var_dump($cal1->isEquivalentTo($cal3)); // false
var_dump($cal1->getFirstDayOfWeek(), // 2 (Monday)
$cal3->getFirstDayOfWeek()); // 1 (Sunday)`

The above example will output:

    bool(true)
    bool(false)
    int(2)
    int(1)

### See Also

- IntlCalendar::equals() - Compare time of two IntlCalendar objects for equality

# IntlCalendar::isLenient

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode

### Description

Object-oriented style

public IntlCalendar::isLenient(): bool

Procedural style

intlcal_is_lenient(IntlCalendar `$calendar`): bool

Returns whether the current date/time interpretations is lenient (the default). If that is case, some out of range values for fields will be accepted instead of raising an error.

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

A bool representing whether the calendar is set to lenient mode.

### Examples

Example #1 IntlCalendar::isLenient()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
ini_set('intl.use_exceptions', '1');
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
var_dump(IntlDateFormatter::formatObject($cal), // 01/07/2013, 00:00:00
$cal->isLenient()); // true
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // 02/08/2013, 00:00:00
$cal->setLenient(false);
var_dump($cal->isLenient()); // false
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // error`

The above example will output:

    string(20) "01/07/2013, 00:00:00"
    bool(true)
    string(20) "02/08/2013, 00:00:00"
    bool(false)

    Fatal error: Uncaught exception 'IntlException' with message 'datefmt_format_object: error obtaining instant from IntlCalendar' in /home/foobar/example.php:16
    Stack trace:
    #0 /home/foobar/example.php(16): IntlDateFormatter::formatObject(Object(IntlGregorianCalendar))
    #1 {main}
      thrown in /home/foobar/example.php on line 16

# IntlCalendar::isSet

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isSet — Whether a field is set

### Description

Object-oriented style

public IntlCalendar::isSet(int `$field`): bool

Procedural style

intlcal_is_set(IntlCalendar `$calendar`, int `$field`): bool

Returns whether a field is set (as opposed to clear). Set fields take priority over unset fields and their default values when the date/time is being calculated. Fields set later take priority over fields set earlier.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

### Return Values

Assuming there are no argument errors, returns `true` if the field is set.

### Examples

See the example on IntlCalendar::clear().

### See Also

- IntlCalendar::clear() - Clear a field or all fields
- IntlCalendar::set() - Set a time field or several common fields at once

# IntlCalendar::isWeekend

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isWeekend — Whether a certain date/time is in the weekend

### Description

Object-oriented style

public IntlCalendar::isWeekend(?float `$timestamp` = `null`): bool

Procedural style

intlcal_is_weekend(IntlCalendar `$calendar`, ?float `$timestamp` = `null`): bool

Returns whether either the obejctʼs current time or the provided timestamp occur during a weekend in this objectʼs calendar system.

This function requires ICU 4.4 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

`timestamp`

  An optional timestamp representing the number of milliseconds since the epoch, excluding leap seconds. If `null`, this objectʼs current time is used instead.

### Return Values

A bool indicating whether the given or this objectʼs time occurs in a weekend.

On failure `false` is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

### Examples

Example #1 IntlCalendar::isWeekend()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
$cal = new IntlGregorianCalendar(NULL, 'en_US');
$cal->set(2013, 6 /* July */, 7); // a Sunday
var_dump($cal->isWeekend()); // true
var_dump($cal->isWeekend(strtotime('2013-07-01 00:00:00'))); // false, Monday
$cal = new IntlGregorianCalendar(NULL, 'ar_SA');
$cal->set(2013, 6 /* July */, 7); // a Sunday
var_dump($cal->isWeekend()); // false, Sunday not in weekend in this calendar`

### See Also

- IntlCalendar::getDayOfWeekType() - Tell whether a day is a weekday, weekend or a day that has a transition between the two
- IntlCalendar::getWeekendTransition() - Get time of the day at which weekend begins or ends

# IntlCalendar::roll

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::roll — Add value to field without carrying into more significant fields

### Description

Object-oriented style

public IntlCalendar::roll(int `$field`, int|bool `$value`): bool

Procedural style

intlcal_roll(IntlCalendar `$calendar`, int `$field`, int|bool `$value`): bool

Adds a (signed) amount to a field. The difference with respect to IntlCalendar::add() is that when the field value overflows, it does not carry into more significant fields.

### Parameters

`calendar`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

`value`

  The (signed) amount to add to the field, `true` for rolling up (adding `1`), or `false` for rolling down (subtracting `1`).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 IntlCalendar::roll()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
$cal = new IntlGregorianCalendar(2013, 5 /* June */, 30);
$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
var_dump(IntlDateFormatter::formatObject($cal)); // "01/07/2013, 00:00:00"
$cal->set(2013, 5 /* June */, 30);
$cal->roll(IntlCalendar::FIELD_DAY_OF_MONTH, true); // roll up, same as rolling +1
var_dump(IntlDateFormatter::formatObject($cal)); // "01/06/2013, 00:00:00"`

The above example will output:

    string(20) "01/07/2013, 00:00:00"
    string(20) "01/06/2013, 00:00:00"

### See Also

- IntlCalendar::add() - Add a (signed) amount of time to a field
- IntlCalendar::set() - Set a time field or several common fields at once

# IntlCalendar::set

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::set — Set a time field or several common fields at once

### Description

Object-oriented style

public IntlCalendar::set(int `$field`, int `$value`): true
public IntlCalendar::set(
int `$year`,
int `$month`,
int `$dayOfMonth` = NULL,
int `$hour` = NULL,
int `$minute` = NULL,
int `$second` = NULL
): true

Procedural style

intlcal_set(IntlCalendar `$cal`, int `$field`, int `$value`): true
intlcal_set(
IntlCalendar `$cal`,
int `$year`,
int `$month`,
int `$dayOfMonth` = NULL,
int `$hour` = NULL,
int `$minute` = NULL,
int `$second` = NULL
): bool

Sets either a specific field to the given value, or sets at once several common fields. The range of values that are accepted depend on whether the calendar is using the lenient mode.

For fields that conflict, the fields that are set later have priority.

This method cannot be called with exactly four arguments.

### Parameters

`cal`

  An IntlCalendar instance.

`field`

  One of the IntlCalendar date/time field constants. These are integer values between `0` and `IntlCalendar::FIELD_COUNT`.

`value`

  The new value of the given field.

`year`

  The new value for `IntlCalendar::FIELD_YEAR`.

`month`

  The new value for `IntlCalendar::FIELD_MONTH`. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

`dayOfMonth`

  The new value for `IntlCalendar::FIELD_DAY_OF_MONTH`.

`hour`

  The new value for `IntlCalendar::FIELD_HOUR_OF_DAY`.

`minute`

  The new value for `IntlCalendar::FIELD_MINUTE`.

`second`

  The new value for `IntlCalendar::FIELD_SECOND`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.
8.4.0 | This had been deprecated in favor of the methods IntlCalendar::setDate() and IntlCalendar::setDateTime().

### Examples

Example #1 IntlCalendar::set()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
//Calls made later have priority
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
var_dump(IntlDateFormatter::formatObject($cal));
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
//the time has not been recalculated yet. If we clear the extended year,
//the year set before will be used
$cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR);
var_dump(IntlDateFormatter::formatObject($cal));`

The above example will output:

    string(20) "01/07/2011, 00:00:00"
    string(20) "01/07/2012, 00:00:00"

### See Also

- IntlCalendar::get() - Get the value for a field
- IntlCalendar::add() - Add a (signed) amount of time to a field
- IntlCalendar::roll() - Add value to field without carrying into more significant fields

# IntlCalendar::setDate

(PHP 8 >= 8.3.0)

IntlCalendar::setDate — Set a date fields

### Description

public IntlCalendar::setDate(int `$year`, int `$month`, int `$dayOfMonth`): void

Sets a date fields to the given value.

### Parameters

`year`

  The new value for `IntlCalendar::FIELD_YEAR`.

`month`

  The new value for `IntlCalendar::FIELD_MONTH`. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

`dayOfMonth`

  The new value for `IntlCalendar::FIELD_DAY_OF_MONTH`.

### Return Values

No value is returned.

### Examples

Example #1 IntlCalendar::setDate() example

`<?php
$intlCal = IntlCalendar::createInstance('UTC');
$intlCal->setDate(2012, 1, 29);
?>`

# IntlCalendar::setDateTime

(PHP 8 >= 8.3.0)

IntlCalendar::setDateTime — Set a date and time fields

### Description

public IntlCalendar::setDateTime(
int `$year`,
int `$month`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
?int `$second` = `null`
): void

Sets a date and time fields to the given value.

### Parameters

`year`

  The new value for `IntlCalendar::FIELD_YEAR`.

`month`

  The new value for `IntlCalendar::FIELD_MONTH`. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

`dayOfMonth`

  The new value for `IntlCalendar::FIELD_DAY_OF_MONTH`.

`hour`

  The new value for `IntlCalendar::FIELD_HOUR_OF_DAY`.

`minute`

  The new value for `IntlCalendar::FIELD_MINUTE`.

`second`

  The new value for `IntlCalendar::FIELD_SECOND`.

### Return Values

No value is returned.

### Examples

Example #1 IntlCalendar::setDateTime() example

`<?php
$intlCal = IntlCalendar::createInstance('UTC');
$intlCal->setDateTime(2012, 1, 29, 23, 58);
?>`

# IntlCalendar::setFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start

### Description

Object-oriented style

public IntlCalendar::setFirstDayOfWeek(int `$dayOfWeek`): true

Procedural style

intlcal_set_first_day_of_week(IntlCalendar `$calendar`, int `$dayOfWeek`): true

Defines the day of week deemed to start the week. This affects the behavior of fields that depend on the concept of week start and end such as `IntlCalendar::FIELD_WEEK_OF_YEAR` and `IntlCalendar::FIELD_YEAR_WOY`.

### Parameters

`calendar`

  An IntlCalendar instance.

`dayOfWeek`

  One of the constants `IntlCalendar::DOW_SUNDAY`, `IntlCalendar::DOW_MONDAY`, …, `IntlCalendar::DOW_SATURDAY`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.

### Examples

Example #1 IntlCalendar::setFirstDayOfWeek()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');
$cal = IntlCalendar::createInstance();
$cal->set(2013, 5 /* June */, 30); // A Sunday
var_dump($cal->getFirstDayOfWeek()); // 2 (Monday)
echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month : 'W'
week of year : 'ww
EOD
), "\n";
$cal->setFirstDayOfWeek(IntlCalendar::DOW_SUNDAY);
echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month : 'W'
week of year : 'ww
EOD
), "\n";`

The above example will output:

    int(2)
    local day of week: 7
    week of month    : 4
    week of year     : 26
    local day of week: 1
    week of month    : 5
    week of year     : 27

# IntlCalendar::setLenient

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient

### Description

Object-oriented style

public IntlCalendar::setLenient(bool `$lenient`): true

Procedural style

intlcal_set_lenient(IntlCalendar `$calendar`, bool `$lenient`): true

Defines whether the calendar is ‘lenient mode’. In such a mode, some of out-of-bounds values for some fields are accepted, the behavior being similar to that of IntlCalendar::add() (i.e., the value wraps around, carrying into more significant fields each time). If the lenient mode is off, then such values will generate an error.

### Parameters

`calendar`

  An IntlCalendar instance.

`lenient`

  Use `true` to activate the lenient mode; `false` otherwise.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.

### Examples

See the example in IntlCalendar::isLenient().

# IntlCalendar::setMinimalDaysInFirstWeek

(PHP 5 >= 5.5.1, PHP 7, PHP 8)

IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have

### Description

Object-oriented style

public IntlCalendar::setMinimalDaysInFirstWeek(int `$days`): true

Procedural style

intlcal_set_minimal_days_in_first_week(IntlCalendar `$calendar`, int `$days`): true

Sets the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous yearʼs last week.

### Parameters

`calendar`

  An IntlCalendar instance.

`days`

  The number of minimal days to set.

### Return Values

Always returns `true`.

### Errors/Exceptions

ValueError if `days` is out of range (less than `1` or more than `7`).

### Changelog

Version | Description
--- | ---
8.0.0 | A ValueError is now thrown on invalid input. Previously, `false` was returned.

# IntlCalendar::setRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions

### Description

Object-oriented style

public IntlCalendar::setRepeatedWallTimeOption(int `$option`): true

Procedural style

intlcal_set_repeated_wall_time_option(IntlCalendar `$calendar`, int `$option`): true

Sets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is `IntlCalendar::WALLTIME_LAST` (take the post-DST instant). The other possible value is `IntlCalendar::WALLTIME_FIRST` (take the instant that occurs during DST).

This function requires ICU 4.9 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

`option`

  One of the constants `IntlCalendar::WALLTIME_FIRST` or `IntlCalendar::WALLTIME_LAST`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.

### Examples

See the example on IntlCalendar::getRepeatedWallTimeOption().

### See Also

- intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
- intlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
- intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time

# IntlCalendar::setSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions

### Description

Object-oriented style

public IntlCalendar::setSkippedWallTimeOption(int `$option`): true

Procedural style

intlcal_set_skipped_wall_time_option(IntlCalendar `$calendar`, int `$option`): true

Sets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is `IntlCalendar::WALLTIME_LAST` (take it as being the same instant as the one when the wall time is one hour more). Alternative values are `IntlCalendar::WALLTIME_FIRST` (same instant as the one with a wall time of one hour less) and `IntlCalendar::WALLTIME_NEXT_VALID` (same instant as when DST begins).

This affects only the instant represented by the calendar (as reported by IntlCalendar::getTime()), the field values will not be rewritten accordingly.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

### Parameters

`calendar`

  An IntlCalendar instance.

`option`

  One of the constants `IntlCalendar::WALLTIME_FIRST`, `IntlCalendar::WALLTIME_LAST` or `IntlCalendar::WALLTIME_NEXT_VALID`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.2.0 | The return type is `true` now; previously, it was bool.

### Examples

See the example on IntlCalendar::getSkippedWallTimeOption().

### See Also

- intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
- intlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions
- intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time

# IntlCalendar::setTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch

### Description

Object-oriented style

public IntlCalendar::setTime(float `$timestamp`): bool

Procedural style

intlcal_set_time(IntlCalendar `$calendar`, float `$timestamp`): bool

Sets the instant represented by this object. The instant is represented by a float whose value should be an integer number of milliseconds since the epoch (1 Jan 1970 00:00:00.000 UTC), ignoring leap seconds. All the field values will be recalculated accordingly.

### Parameters

`calendar`

  An IntlCalendar instance.

`timestamp`

  An instant represented by the number of number of milliseconds between such instant and the epoch, ignoring leap seconds.

### Return Values

Returns `true` on success and `false` on failure.

### Examples

Example #1 IntlCalendar::setTime()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');
$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
/* In Europe/Lisbon, on 2013-10-27 at 0200, the clock goes back one hour and
the timezone from UTC+01 to UTC+00 */
$cal->setTime(strtotime('2013-10-27 00:30:00 UTC') * 1000.);
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
$cal->setTime(strtotime('2013-10-27 01:30:00 UTC') * 1000.);
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";`

The above example will output:

    samedi 1 juin 2013 12:00:00 heure avancée d’Europe de l’Ouest
    dimanche 27 octobre 2013 01:30:00 heure avancée d’Europe de l’Ouest
    dimanche 27 octobre 2013 01:30:00 heure normale d’Europe de l’Ouest

# IntlCalendar::setTimeZone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setTimeZone — Set the timezone used by this calendar

### Description

Object-oriented style

public IntlCalendar::setTimeZone(IntlTimeZone|DateTimeZone|string|null `$timezone`): bool

Procedural style

intlcal_set_time_zone(IntlCalendar `$calendar`, IntlTimeZone|DateTimeZone|string|null `$timezone`): bool

Defines a new timezone for this calendar. The time represented by the object is preserved to the detriment of the field values.

### Parameters

`calendar`

  An IntlCalendar instance.

`timezone`

  The new timezone to be used by this calendar. It can be specified in the following ways:

  - `null`, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  - An IntlTimeZone, which will be used directly.

  - A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  - A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as `"GMT+08:30"` are also accepted.

### Return Values

Returns `true` on success and `false` on failure.

### Examples

Example #1 IntlCalendar::setTimeZone()

`<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');
$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";
$cal->setTimeZone(IntlTimeZone::getGMT());
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";
$cal->setTimeZone('GMT+03:33');
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";`

The above example will output:

    sábado, 1 de junio de 2013 12:00:00 Hora de verano de Europa occidental
    (instant 1370084400000)
    sábado, 1 de junio de 2013 11:00:00 GMT
    (instant 1370084400000)
    sábado, 1 de junio de 2013 14:33:00 GMT+03:33
    (instant 1370084400000)

# IntlCalendar::toDateTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a2)

IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

### Description

Object-oriented style

public IntlCalendar::toDateTime(): DateTime|false

Procedural style

intlcal_to_date_time(IntlCalendar `$calendar`): DateTime|false

Create a DateTime object that represents the same instant (up to second precision, with a rounding error of less than 1 second) and has an analog timezone to this object (the difference being DateTimeʼs timezone will be backed by PHPʼs timezone while IntlCalendarʼs timezone is backed by ICUʼs).

### Parameters

`calendar`

  An IntlCalendar instance.

### Return Values

A DateTime object with the same timezone as this object (though using PHPʼs database instead of ICUʼs) and the same time, except for the smaller precision (second precision instead of millisecond). Returns `false` on failure.

### Examples

Example #1 IntlCalendar::toDateTime()

`<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'pt_PT');
$cal = IntlCalendar::createInstance('Europe/Lisbon'); //current time
$dt = $cal->toDateTime();
print_r($dt);`

The above example will output:

    DateTime Object
    (
        [date] => 2013-07-02 00:29:13
        [timezone_type] => 3
        [timezone] => Europe/Lisbon
    )

### See Also

- IntlCalendar::fromDateTime() - Create an IntlCalendar from a DateTime object or string
- IntlCalendar::getTime() - Get time currently represented by the object
- IntlCalendar::createInstance() - Create a new IntlCalendar
- DateTime::__construct() - Returns new DateTime object

## Table of Contents

- IntlCalendar::add — Add a (signed) amount of time to a field
- IntlCalendar::after — Whether this objectʼs time is after that of the passed object
- IntlCalendar::before — Whether this objectʼs time is before that of the passed object
- IntlCalendar::clear — Clear a field or all fields
- IntlCalendar::__construct — Private constructor for disallowing instantiation
- IntlCalendar::createInstance — Create a new IntlCalendar
- IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
- IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time
- IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
- IntlCalendar::get — Get the value for a field
- IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time
- IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time
- IntlCalendar::getAvailableLocales — Get array of locales for which there is data
- IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
- IntlCalendar::getErrorCode — Get last error code on the object
- IntlCalendar::getErrorMessage — Get last error message on the object
- IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale
- IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
- IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
- IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
- IntlCalendar::getLocale — Get the locale associated with the object
- IntlCalendar::getMaximum — Get the global maximum value for a field
- IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
- IntlCalendar::getMinimum — Get the global minimum value for a field
- IntlCalendar::getNow — Get number representing the current time
- IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
- IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
- IntlCalendar::getTime — Get time currently represented by the object
- IntlCalendar::getTimeZone — Get the objectʼs timezone
- IntlCalendar::getType — Get the calendar type
- IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
- IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time
- IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
- IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
- IntlCalendar::isSet — Whether a field is set
- IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
- IntlCalendar::roll — Add value to field without carrying into more significant fields
- IntlCalendar::set — Set a time field or several common fields at once
- IntlCalendar::setDate — Set a date fields
- IntlCalendar::setDateTime — Set a date and time fields
- IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
- IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
- IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
- IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
- IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
- IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
- IntlCalendar::setTimeZone — Set the timezone used by this calendar
- IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

# The IntlGregorianCalendar class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

## Class synopsis

class IntlGregorianCalendar extends IntlCalendar {
/* Inherited constants */
public const int IntlCalendar::FIELD_ERA;
public const int IntlCalendar::FIELD_YEAR;
public const int IntlCalendar::FIELD_MONTH;
public const int IntlCalendar::FIELD_WEEK_OF_YEAR;
public const int IntlCalendar::FIELD_WEEK_OF_MONTH;
public const int IntlCalendar::FIELD_DATE;
public const int IntlCalendar::FIELD_DAY_OF_YEAR;
public const int IntlCalendar::FIELD_DAY_OF_WEEK;
public const int IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH;
public const int IntlCalendar::FIELD_AM_PM;
public const int IntlCalendar::FIELD_HOUR;
public const int IntlCalendar::FIELD_HOUR_OF_DAY;
public const int IntlCalendar::FIELD_MINUTE;
public const int IntlCalendar::FIELD_SECOND;
public const int IntlCalendar::FIELD_MILLISECOND;
public const int IntlCalendar::FIELD_ZONE_OFFSET;
public const int IntlCalendar::FIELD_DST_OFFSET;
public const int IntlCalendar::FIELD_YEAR_WOY;
public const int IntlCalendar::FIELD_DOW_LOCAL;
public const int IntlCalendar::FIELD_EXTENDED_YEAR;
public const int IntlCalendar::FIELD_JULIAN_DAY;
public const int IntlCalendar::FIELD_MILLISECONDS_IN_DAY;
public const int IntlCalendar::FIELD_IS_LEAP_MONTH;
public const int IntlCalendar::FIELD_FIELD_COUNT;
public const int IntlCalendar::FIELD_DAY_OF_MONTH;
public const int IntlCalendar::DOW_SUNDAY;
public const int IntlCalendar::DOW_MONDAY;
public const int IntlCalendar::DOW_TUESDAY;
public const int IntlCalendar::DOW_WEDNESDAY;
public const int IntlCalendar::DOW_THURSDAY;
public const int IntlCalendar::DOW_FRIDAY;
public const int IntlCalendar::DOW_SATURDAY;
public const int IntlCalendar::DOW_TYPE_WEEKDAY;
public const int IntlCalendar::DOW_TYPE_WEEKEND;
public const int IntlCalendar::DOW_TYPE_WEEKEND_OFFSET;
public const int IntlCalendar::DOW_TYPE_WEEKEND_CEASE;
public const int IntlCalendar::WALLTIME_FIRST;
public const int IntlCalendar::WALLTIME_LAST;
public const int IntlCalendar::WALLTIME_NEXT_VALID;
/* Methods */
public __construct(IntlTimeZone `$tz` = ?, string `$locale` = ?)
public __construct(int `$timeZoneOrYear`, int `$localeOrMonth`, int `$dayOfMonth`)
public __construct(
int `$timeZoneOrYear`,
int `$localeOrMonth`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
int `$second` = ?
)
public static createFromDate(int `$year`, int `$month`, int `$dayOfMonth`): static
public static createFromDateTime(
int `$year`,
int `$month`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
?int `$second` = `null`
): static
public getGregorianChange(): float
public isLeapYear(int `$year`): bool
public setGregorianChange(float `$timestamp`): bool
/* Inherited methods */
public IntlCalendar::add(int `$field`, int `$value`): bool
public IntlCalendar::after(IntlCalendar `$other`): bool
public IntlCalendar::before(IntlCalendar `$other`): bool
public IntlCalendar::clear(?int `$field` = `null`): true
public static IntlCalendar::createInstance(IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`, ?string `$locale` = `null`): ?IntlCalendar
public IntlCalendar::equals(IntlCalendar `$other`): bool
public IntlCalendar::fieldDifference(float `$timestamp`, int `$field`): int|false
public static IntlCalendar::fromDateTime(DateTime|string `$datetime`, ?string `$locale` = `null`): ?IntlCalendar
public IntlCalendar::get(int `$field`): int|false
public IntlCalendar::getActualMaximum(int `$field`): int|false
public IntlCalendar::getActualMinimum(int `$field`): int|false
public static IntlCalendar::getAvailableLocales(): array
public IntlCalendar::getDayOfWeekType(int `$dayOfWeek`): int|false
public IntlCalendar::getErrorCode(): int|false
public IntlCalendar::getErrorMessage(): string|false
public IntlCalendar::getFirstDayOfWeek(): int|false
public IntlCalendar::getGreatestMinimum(int `$field`): int|false
public static IntlCalendar::getKeywordValuesForLocale(string `$keyword`, string `$locale`, bool `$onlyCommon`): IntlIterator|false
public IntlCalendar::getLeastMaximum(int `$field`): int|false
public IntlCalendar::getLocale(int `$type`): string|false
public IntlCalendar::getMaximum(int `$field`): int|false
public IntlCalendar::getMinimalDaysInFirstWeek(): int|false
public IntlCalendar::getMinimum(int `$field`): int|false
public static IntlCalendar::getNow(): float
public IntlCalendar::getRepeatedWallTimeOption(): int
public IntlCalendar::getSkippedWallTimeOption(): int
public IntlCalendar::getTime(): float|false
public IntlCalendar::getTimeZone(): IntlTimeZone|false
public IntlCalendar::getType(): string
public IntlCalendar::getWeekendTransition(int `$dayOfWeek`): int|false
public IntlCalendar::inDaylightTime(): bool
public IntlCalendar::isEquivalentTo(IntlCalendar `$other`): bool
public IntlCalendar::isLenient(): bool
public IntlCalendar::isSet(int `$field`): bool
public IntlCalendar::isWeekend(?float `$timestamp` = `null`): bool
public IntlCalendar::roll(int `$field`, int|bool `$value`): bool
public IntlCalendar::set(int `$field`, int `$value`): true
public IntlCalendar::set(
int `$year`,
int `$month`,
int `$dayOfMonth` = NULL,
int `$hour` = NULL,
int `$minute` = NULL,
int `$second` = NULL
): true
public IntlCalendar::setDate(int `$year`, int `$month`, int `$dayOfMonth`): void
public IntlCalendar::setDateTime(
int `$year`,
int `$month`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
?int `$second` = `null`
): void
public IntlCalendar::setFirstDayOfWeek(int `$dayOfWeek`): true
public IntlCalendar::setLenient(bool `$lenient`): true
public IntlCalendar::setMinimalDaysInFirstWeek(int `$days`): true
public IntlCalendar::setRepeatedWallTimeOption(int `$option`): true
public IntlCalendar::setSkippedWallTimeOption(int `$option`): true
public IntlCalendar::setTime(float `$timestamp`): bool
public IntlCalendar::setTimeZone(IntlTimeZone|DateTimeZone|string|null `$timezone`): bool
public IntlCalendar::toDateTime(): DateTime|false
}

# IntlGregorianCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::__construct — Create the Gregorian Calendar class

### Description

public IntlGregorianCalendar::__construct(IntlTimeZone `$tz` = ?, string `$locale` = ?)
public IntlGregorianCalendar::__construct(int `$timeZoneOrYear`, int `$localeOrMonth`, int `$dayOfMonth`)
public IntlGregorianCalendar::__construct(
int `$timeZoneOrYear`,
int `$localeOrMonth`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
int `$second` = ?
)

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`tz`

`locale`

`timeZoneOrYear`

`localeOrMonth`

`dayOfMonth`

`hour`

`minute`

`second`

### Changelog

Version | Description
--- | ---
8.4.0 | This had been deprecated in favor of the methods IntlGregorianCalendar::createFromDate() and IntlGregorianCalendar::createFromDateTime().

# IntlGregorianCalendar::createFromDate

(PHP 8 >= 8.3.0)

IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date

### Description

public static IntlGregorianCalendar::createFromDate(int `$year`, int `$month`, int `$dayOfMonth`): static

Creates a new IntlGregorianCalendar instance from date.

### Parameters

`year`

  The new value for `IntlGregorianCalendar::FIELD_YEAR`.

`month`

  The new value for `IntlGregorianCalendar::FIELD_MONTH`. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

`dayOfMonth`

  The new value for `IntlGregorianCalendar::FIELD_DAY_OF_MONTH`.

### Return Values

Returns a new IntlGregorianCalendar instance.

### Examples

Example #1 IntlGregorianCalendar::createFromDate() example

`<?php
$intlCalendar = IntlGregorianCalendar::createFromDate(2023, 11, 23);
var_dump($intlCalendar);
?>`

The above example will output something similar to:

    object(IntlGregorianCalendar)#1 (5) {
      ["valid"]=>
      bool(true)
      ["type"]=>
      string(9) "gregorian"
      ["timeZone"]=>
      array(4) {
        ["valid"]=>
        bool(true)
        ["id"]=>
        string(16) "Europe/Amsterdam"
        ["rawOffset"]=>
        int(3600000)
        ["currentOffset"]=>
        int(3600000)
      }
      ["locale"]=>
      string(11) "en_US_POSIX"
      ["fields"]=>
      array(23) {
        ["era"]=>
        int(1)
        ["year"]=>
        int(2023)
        ["month"]=>
        int(11)
        ["week of year"]=>
        int(51)
        ["week of month"]=>
        int(4)
        ["day of year"]=>
        int(357)
        ["day of month"]=>
        int(23)
        ["day of week"]=>
        int(7)
        ["day of week in month"]=>
        int(4)
        ["AM/PM"]=>
        int(0)
        ["hour"]=>
        int(0)
        ["hour of day"]=>
        int(0)
        ["minute"]=>
        int(0)
        ["second"]=>
        int(0)
        ["millisecond"]=>
        int(0)
        ["zone offset"]=>
        int(3600000)
        ["DST offset"]=>
        int(0)
        ["year for week of year"]=>
        int(2023)
        ["localized day of week"]=>
        int(7)
        ["extended year"]=>
        int(2023)
        ["julian day"]=>
        int(2460302)
        ["milliseconds in day"]=>
        int(0)
        ["is leap month"]=>
        int(0)
      }
    }

### See Also

- IntlGregorianCalendar::createFromDateTime() - Create a new IntlGregorianCalendar instance from date and time

# IntlGregorianCalendar::createFromDateTime

(PHP 8 >= 8.3.0)

IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time

### Description

public static IntlGregorianCalendar::createFromDateTime(
int `$year`,
int `$month`,
int `$dayOfMonth`,
int `$hour`,
int `$minute`,
?int `$second` = `null`
): static

Creates a new IntlGregorianCalendar instance from date and time.

### Parameters

`year`

  The new value for `IntlGregorianCalendar::FIELD_YEAR`.

`month`

  The new value for `IntlGregorianCalendar::FIELD_MONTH`. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

`dayOfMonth`

  The new value for `IntlGregorianCalendar::FIELD_DAY_OF_MONTH`.

`hour`

  The new value for `IntlGregorianCalendar::FIELD_HOUR_OF_DAY`.

`minute`

  The new value for `IntlGregorianCalendar::FIELD_MINUTE`.

`second`

  The new value for `IntlGregorianCalendar::FIELD_SECOND`.

### Return Values

Returns a new IntlGregorianCalendar instance.

### Examples

Example #1 IntlGregorianCalendar::createFromDateTime() example

`<?php
$intlCalendar = IntlGregorianCalendar::createFromDateTime(2023, 11, 23, 12, 00);
var_dump($intlCalendar);
?>`

The above example will output something similar to:

    object(IntlGregorianCalendar)#1 (5) {
      ["valid"]=>
      bool(true)
      ["type"]=>
      string(9) "gregorian"
      ["timeZone"]=>
      array(4) {
        ["valid"]=>
        bool(true)
        ["id"]=>
        string(16) "Europe/Amsterdam"
        ["rawOffset"]=>
        int(3600000)
        ["currentOffset"]=>
        int(3600000)
      }
      ["locale"]=>
      string(11) "en_US_POSIX"
      ["fields"]=>
      array(23) {
        ["era"]=>
        int(1)
        ["year"]=>
        int(2023)
        ["month"]=>
        int(11)
        ["week of year"]=>
        int(51)
        ["week of month"]=>
        int(4)
        ["day of year"]=>
        int(357)
        ["day of month"]=>
        int(23)
        ["day of week"]=>
        int(7)
        ["day of week in month"]=>
        int(4)
        ["AM/PM"]=>
        int(1)
        ["hour"]=>
        int(0)
        ["hour of day"]=>
        int(12)
        ["minute"]=>
        int(0)
        ["second"]=>
        int(0)
        ["millisecond"]=>
        int(0)
        ["zone offset"]=>
        int(3600000)
        ["DST offset"]=>
        int(0)
        ["year for week of year"]=>
        int(2023)
        ["localized day of week"]=>
        int(7)
        ["extended year"]=>
        int(2023)
        ["julian day"]=>
        int(2460302)
        ["milliseconds in day"]=>
        int(43200000)
        ["is leap month"]=>
        int(0)
      }
    }

### See Also

- IntlGregorianCalendar::createFromDate() - Create a new IntlGregorianCalendar instance from date

# IntlGregorianCalendar::getGregorianChange

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date

### Description

public IntlGregorianCalendar::getGregorianChange(): float

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns the change date.

# IntlGregorianCalendar::isLeapYear

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year

### Description

public IntlGregorianCalendar::isLeapYear(int `$year`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`year`

### Return Values

Returns `true` for leap years, `false` otherwise and on failure.

# IntlGregorianCalendar::setGregorianChange

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date

### Description

public IntlGregorianCalendar::setGregorianChange(float `$timestamp`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timestamp`

### Return Values

Returns `true` on success or `false` on failure.

## Table of Contents

- IntlGregorianCalendar::__construct — Create the Gregorian Calendar class
- IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date
- IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time
- IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date
- IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year
- IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date

# The IntlTimeZone class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

## Introduction

## Class synopsis

class IntlTimeZone {
/* Constants */
public const int DISPLAY_SHORT;
public const int DISPLAY_LONG;
public const int DISPLAY_SHORT_GENERIC;
public const int DISPLAY_LONG_GENERIC;
public const int DISPLAY_SHORT_GMT;
public const int DISPLAY_LONG_GMT;
public const int DISPLAY_SHORT_COMMONLY_USED;
public const int DISPLAY_GENERIC_LOCATION;
public const int TYPE_ANY;
public const int TYPE_CANONICAL;
public const int TYPE_CANONICAL_LOCATION;
/* Methods */
private __construct()
public static countEquivalentIDs(string `$timezoneId`): int|false
public static createDefault(): IntlTimeZone
public static createEnumeration(string|int|null `$countryOrRawOffset` = `null`): IntlIterator|false
public static createTimeZone(string `$timezoneId`): ?IntlTimeZone
public static createTimeZoneIDEnumeration(int `$type`, ?string `$region` = `null`, ?int `$rawOffset` = `null`): IntlIterator|false
public static fromDateTimeZone(DateTimeZone `$timezone`): ?IntlTimeZone
public static getCanonicalID(string `$timezoneId`, bool `&$isSystemId` = `null`): string|false
public getDisplayName(bool `$dst` = `false`, int `$style` = `IntlTimeZone::DISPLAY_LONG`, ?string `$locale` = `null`): string|false
public getDSTSavings(): int
public static getEquivalentID(string `$timezoneId`, int `$offset`): string|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public static getGMT(): IntlTimeZone
public getID(): string|false
public static getIDForWindowsID(string `$timezoneId`, ?string `$region` = `null`): string|false
public getOffset(
float `$timestamp`,
bool `$local`,
int `&$rawOffset`,
int `&$dstOffset`
): bool
public getRawOffset(): int
public static getRegion(string `$timezoneId`): string|false
public static getTZDataVersion(): string|false
public static getUnknown(): IntlTimeZone
public static getWindowsID(string `$timezoneId`): string|false
public hasSameRules(IntlTimeZone `$other`): bool
public toDateTimeZone(): DateTimeZone|false
public useDaylightTime(): bool
}

## Predefined Constants

`IntlTimeZone::DISPLAY_SHORT` int

`IntlTimeZone::DISPLAY_LONG` int

`IntlTimeZone::DISPLAY_SHORT_GENERIC` int

`IntlTimeZone::DISPLAY_LONG_GENERIC` int

`IntlTimeZone::DISPLAY_SHORT_GMT` int

`IntlTimeZone::DISPLAY_LONG_GMT` int

`IntlTimeZone::DISPLAY_SHORT_COMMONLY_USED` int

`IntlTimeZone::DISPLAY_GENERIC_LOCATION` int

`IntlTimeZone::TYPE_ANY` int

`IntlTimeZone::TYPE_CANONICAL` int

`IntlTimeZone::TYPE_CANONICAL_LOCATION` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# IntlTimeZone::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::__construct — Private constructor to disallow direct instantiation

### Description

private IntlTimeZone::__construct()

### Parameters

This function has no parameters.

# IntlTimeZone::countEquivalentIDs

# intltz_count_equivalent_ids

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::countEquivalentIDs -- intltz_count_equivalent_ids — Get the number of IDs in the equivalency group that includes the given ID

### Description

Object-oriented style (method):

public static IntlTimeZone::countEquivalentIDs(string `$timezoneId`): int|false

Procedural style:

intltz_count_equivalent_ids(string `$timezoneId`): int|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

### Return Values

# IntlTimeZone::createDefault

# intltz_create_default

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createDefault -- intltz_create_default — Create a new copy of the default timezone for this host

### Description

Object-oriented style (method):

public static IntlTimeZone::createDefault(): IntlTimeZone

Procedural style:

intltz_create_default(): IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::createEnumeration

# intltz_create_enumeration

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createEnumeration -- intltz_create_enumeration — Get an enumeration over time zone IDs associated with the given country or offset

### Description

Object-oriented style (method):

public static IntlTimeZone::createEnumeration(string|int|null `$countryOrRawOffset` = `null`): IntlIterator|false

Procedural style:

intltz_create_enumeration(string|int|null `$countryOrRawOffset` = `null`): IntlIterator|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`countryOrRawOffset`

### Return Values

# IntlTimeZone::createTimeZone

# intltz_create_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createTimeZone -- intltz_create_time_zone — Create a timezone object for the given ID

### Description

Object-oriented style (method):

public static IntlTimeZone::createTimeZone(string `$timezoneId`): ?IntlTimeZone

Procedural style:

intltz_create_time_zone(string `$timezoneId`): ?IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

### Return Values

# IntlTimeZone::createTimeZoneIDEnumeration

# intltz_create_time_zone_id_enumeration

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::createTimeZoneIDEnumeration -- intltz_create_time_zone_id_enumeration — Get an enumeration over system time zone IDs with the given filter conditions

### Description

Object-oriented style (method):

public static IntlTimeZone::createTimeZoneIDEnumeration(int `$type`, ?string `$region` = `null`, ?int `$rawOffset` = `null`): IntlIterator|false

Procedural style:

intltz_create_time_zone_id_enumeration(int `$type`, ?string `$region` = `null`, ?int `$rawOffset` = `null`): IntlIterator|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`type`

`region`

`rawOffset`

### Return Values

Returns IntlIterator or `false` on failure.

# IntlTimeZone::fromDateTimeZone

# intltz_from_date_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::fromDateTimeZone -- intltz_from_date_time_zone — Create a timezone object from DateTimeZone

### Description

Object-oriented style (method):

public static IntlTimeZone::fromDateTimeZone(DateTimeZone `$timezone`): ?IntlTimeZone

Procedural style:

intltz_from_date_time_zone(DateTimeZone `$timezone`): ?IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezone`

### Return Values

# IntlTimeZone::getCanonicalID

# intltz_get_canonical_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getCanonicalID -- intltz_get_canonical_id — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

### Description

Object-oriented style (method):

public static IntlTimeZone::getCanonicalID(string `$timezoneId`, bool `&$isSystemId` = `null`): string|false

Procedural style:

intltz_get_canonical_id(string `$timezoneId`, bool `&$isSystemId` = `null`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

`isSystemId`

### Return Values

# IntlTimeZone::getDisplayName

# intltz_get_display_name

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getDisplayName -- intltz_get_display_name — Get a name of this time zone suitable for presentation to the user

### Description

Object-oriented style (method):

public IntlTimeZone::getDisplayName(bool `$dst` = `false`, int `$style` = `IntlTimeZone::DISPLAY_LONG`, ?string `$locale` = `null`): string|false

Procedural style:

intltz_get_display_name(
IntlTimeZone `$timezone`,
bool `$dst` = `false`,
int `$style` = `IntlTimeZone::DISPLAY_LONG`,
?string `$locale` = `null`
): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`dst`

`style`

`locale`

### Return Values

# IntlTimeZone::getDSTSavings

# intltz_get_dst_savings

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getDSTSavings -- intltz_get_dst_savings — Get the amount of time to be added to local standard time to get local wall clock time

### Description

Object-oriented style (method):

public IntlTimeZone::getDSTSavings(): int

Procedural style:

intltz_get_dst_savings(IntlTimeZone `$timezone`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getEquivalentID

# intltz_get_equivalent_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getEquivalentID -- intltz_get_equivalent_id — Get an ID in the equivalency group that includes the given ID

### Description

Object-oriented style (method):

public static IntlTimeZone::getEquivalentID(string `$timezoneId`, int `$offset`): string|false

Procedural style:

intltz_get_equivalent_id(string `$timezoneId`, int `$offset`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

`offset`

### Return Values

# IntlTimeZone::getErrorCode

# intltz_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getErrorCode -- intltz_get_error_code — Get last error code on the object

### Description

Object-oriented style (method):

public IntlTimeZone::getErrorCode(): int|false

Procedural style:

intltz_get_error_code(IntlTimeZone `$timezone`): int|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getErrorMessage

# intltz_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getErrorMessage -- intltz_get_error_message — Get last error message on the object

### Description

Object-oriented style (method):

public IntlTimeZone::getErrorMessage(): string|false

Procedural style:

intltz_get_error_message(IntlTimeZone `$timezone`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getGMT

# intltz_get_gmt

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getGMT -- intltz_get_gmt — Create GMT (UTC) timezone

### Description

Object-oriented style (method):

public static IntlTimeZone::getGMT(): IntlTimeZone

Procedural style:

intltz_get_gmt(): IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getID

# intltz_get_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getID -- intltz_get_id — Get timezone ID

### Description

Object-oriented style (method):

public IntlTimeZone::getID(): string|false

Procedural style:

intltz_get_id(IntlTimeZone `$timezone`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getIDForWindowsID

# intltz_get_id_for_windows_id

(PHP 7 >= 7.1.0, PHP 8)

IntlTimeZone::getIDForWindowsID -- intltz_get_id_for_windows_id — Translate a Windows timezone into a system timezone

### Description

Object-oriented style (method):

public static IntlTimeZone::getIDForWindowsID(string `$timezoneId`, ?string `$region` = `null`): string|false

Procedural style:

intltz_get_id_for_windows_id(string `$timezoneId`, ?string `$region` = `null`): string|false

Translates a Windows timezone (e.g. "Pacific Standard Time") into a system timezone (e.g. "America/Los_Angeles").

> Note: This function requires ICU version ≥ 52.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

`region`

### Return Values

Returns the system timezone or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `region` is now nullable.

### See Also

- IntlTimeZone::getWindowsID() - Translate a system timezone into a Windows timezone

# IntlTimeZone::getOffset

# intltz_get_offset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getOffset -- intltz_get_offset — Get the time zone raw and GMT offset for the given moment in time

### Description

Object-oriented style (method):

public IntlTimeZone::getOffset(
float `$timestamp`,
bool `$local`,
int `&$rawOffset`,
int `&$dstOffset`
): bool

Procedural style:

intltz_get_offset(
IntlTimeZone `$timezone`,
float `$timestamp`,
bool `$local`,
int `&$rawOffset`,
int `&$dstOffset`
): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timestamp`

`local`

`rawOffset`

`dstOffset`

### Return Values

# IntlTimeZone::getRawOffset

# intltz_get_raw_offset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getRawOffset -- intltz_get_raw_offset — Get the raw GMT offset (before taking daylight savings time into account

### Description

Object-oriented style (method):

public IntlTimeZone::getRawOffset(): int

Procedural style:

intltz_get_raw_offset(IntlTimeZone `$timezone`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getRegion

# intltz_get_region

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::getRegion -- intltz_get_region — Get the region code associated with the given system time zone ID

### Description

Object-oriented style (method):

public static IntlTimeZone::getRegion(string `$timezoneId`): string|false

Procedural style:

intltz_get_region(string `$timezoneId`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

### Return Values

Return region or `false` on failure.

# IntlTimeZone::getTZDataVersion

# intltz_get_tz_data_version

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getTZDataVersion -- intltz_get_tz_data_version — Get the timezone data version currently used by ICU

### Description

Object-oriented style (method):

public static IntlTimeZone::getTZDataVersion(): string|false

Procedural style:

intltz_get_tz_data_version(): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::getUnknown

# intltz_get_unknown

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::getUnknown -- intltz_get_unknown — Get the "unknown" time zone

### Description

Object-oriented style (method):

public static IntlTimeZone::getUnknown(): IntlTimeZone

Procedural style:

intltz_get_unknown(): IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns IntlTimeZone or `null` on failure.

# IntlTimeZone::getWindowsID

# intltz_get_windows_id

(PHP 7 >= 7.1.0, PHP 8)

IntlTimeZone::getWindowsID -- intltz_get_windows_id — Translate a system timezone into a Windows timezone

### Description

Object-oriented style (method):

public static IntlTimeZone::getWindowsID(string `$timezoneId`): string|false

Procedural style:

intltz_get_windows_id(string `$timezoneId`): string|false

Translates a system timezone (e.g. "America/Los_Angeles") into a Windows timezone (e.g. "Pacific Standard Time").

> Note: This function requires ICU version ≥ 52.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`timezoneId`

### Return Values

Returns the Windows timezone or `false` on failure.

### See Also

- IntlTimeZone::getIDForWindowsID() - Translate a Windows timezone into a system timezone

# IntlTimeZone::hasSameRules

# intltz_has_same_rules

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::hasSameRules -- intltz_has_same_rules — Check if this zone has the same rules and offset as another zone

### Description

Object-oriented style (method):

public IntlTimeZone::hasSameRules(IntlTimeZone `$other`): bool

Procedural style:

intltz_has_same_rules(IntlTimeZone `$timezone`, IntlTimeZone `$other`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`other`

### Return Values

# IntlTimeZone::toDateTimeZone

# intltz_to_date_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::toDateTimeZone -- intltz_to_date_time_zone — Convert to DateTimeZone object

### Description

Object-oriented style (method):

public IntlTimeZone::toDateTimeZone(): DateTimeZone|false

Procedural style:

intltz_to_date_time_zone(IntlTimeZone `$timezone`): DateTimeZone|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlTimeZone::useDaylightTime

# intltz_use_daylight_time

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::useDaylightTime -- intltz_use_daylight_time — Check if this time zone uses daylight savings time

### Description

Object-oriented style (method):

public IntlTimeZone::useDaylightTime(): bool

Procedural style:

intltz_use_daylight_time(IntlTimeZone `$timezone`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- IntlTimeZone::__construct — Private constructor to disallow direct instantiation
- IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
- IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
- IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
- IntlTimeZone::createTimeZone — Create a timezone object for the given ID
- IntlTimeZone::createTimeZoneIDEnumeration — Get an enumeration over system time zone IDs with the given filter conditions
- IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
- IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
- IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
- IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
- IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
- IntlTimeZone::getErrorCode — Get last error code on the object
- IntlTimeZone::getErrorMessage — Get last error message on the object
- IntlTimeZone::getGMT — Create GMT (UTC) timezone
- IntlTimeZone::getID — Get timezone ID
- IntlTimeZone::getIDForWindowsID — Translate a Windows timezone into a system timezone
- IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
- IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
- IntlTimeZone::getRegion — Get the region code associated with the given system time zone ID
- IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
- IntlTimeZone::getUnknown — Get the "unknown" time zone
- IntlTimeZone::getWindowsID — Translate a system timezone into a Windows timezone
- IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
- IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
- IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

# The IntlDateFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

## Introduction

Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

## Class synopsis

class IntlDateFormatter {
/* Constants */
public const int FULL;
public const int LONG;
public const int MEDIUM;
public const int SHORT;
public const int NONE;
public const int RELATIVE_FULL;
public const int RELATIVE_LONG;
public const int RELATIVE_MEDIUM;
public const int RELATIVE_SHORT;
public const int PATTERN;
public const int GREGORIAN;
public const int TRADITIONAL;
/* Methods */
public __construct(
?string `$locale`,
int `$dateType` = `IntlDateFormatter::FULL`,
int `$timeType` = `IntlDateFormatter::FULL`,
IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`,
IntlCalendar|int|null `$calendar` = `null`,
?string `$pattern` = `null`
)
public static create(
?string `$locale`,
int `$dateType` = `IntlDateFormatter::FULL`,
int `$timeType` = `IntlDateFormatter::FULL`,
IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`,
IntlCalendar|int|null `$calendar` = `null`,
?string `$pattern` = `null`
): ?IntlDateFormatter
public format(IntlCalendar|DateTimeInterface|array|string|int|float `$datetime`): string|false
public static formatObject(IntlCalendar|DateTimeInterface `$datetime`, array|int|string|null `$format` = `null`, ?string `$locale` = `null`): string|false
public getCalendar(): int|false
public getDateType(): int|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int `$type` = `ULOC_ACTUAL_LOCALE`): string|false
public getPattern(): string|false
public getTimeType(): int|false
public getTimeZoneId(): string|false
public getCalendarObject(): IntlCalendar|false|null
public getTimeZone(): IntlTimeZone|false
public isLenient(): bool
public localtime(string `$string`, int `&$offset` = `null`): array|false
public parse(string `$string`, int `&$offset` = `null`): int|float|false
public setCalendar(IntlCalendar|int|null `$calendar`): bool
public setLenient(bool `$lenient`): void
public setPattern(string `$pattern`): bool
public setTimeZone(IntlTimeZone|DateTimeZone|string|null `$timezone`): bool
}

## Changelog

Version | Description
--- | ---
8.4.0 | Added `IntlDateFormatter::PATTERN`.

## See Also

- » ICU Date formatter

- » ICU Date formats

## Predefined Constants

These constants are used to specify different formats in the constructor for DateType and TimeType.

`IntlDateFormatter::NONE` int
  Do not include this element
`IntlDateFormatter::FULL` int
  Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
`IntlDateFormatter::LONG` int
  Long style (January 12, 1952 or 3:30:32pm)
`IntlDateFormatter::MEDIUM` int
  Medium style (Jan 12, 1952)
`IntlDateFormatter::SHORT` int
  Most abbreviated style, only essential data (12/13/52 or 3:30pm)
`IntlDateFormatter::RELATIVE_FULL` int
  The same as `IntlDateFormatter::FULL`, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only.
`IntlDateFormatter::RELATIVE_LONG` int
  The same as `IntlDateFormatter::LONG`, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only.
`IntlDateFormatter::RELATIVE_MEDIUM` int
  The same as `IntlDateFormatter::MEDIUM`, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only.
`IntlDateFormatter::RELATIVE_SHORT` int
  The same as `IntlDateFormatter::SHORT`, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only.
`IntlDateFormatter::PATTERN` int
  Uses the pattern given in `pattern`. Available as of PHP 8.4.0.

The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".

`IntlDateFormatter::TRADITIONAL` int
  Non-Gregorian Calendar
`IntlDateFormatter::GREGORIAN` int
  Gregorian Calendar

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# IntlDateFormatter::create

# datefmt_create

# IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

### Description

Object-oriented style

public static IntlDateFormatter::create(
?string `$locale`,
int `$dateType` = `IntlDateFormatter::FULL`,
int `$timeType` = `IntlDateFormatter::FULL`,
IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`,
IntlCalendar|int|null `$calendar` = `null`,
?string `$pattern` = `null`
): ?IntlDateFormatter

Object-oriented style (constructor)

public IntlDateFormatter::__construct(
?string `$locale`,
int `$dateType` = `IntlDateFormatter::FULL`,
int `$timeType` = `IntlDateFormatter::FULL`,
IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`,
IntlCalendar|int|null `$calendar` = `null`,
?string `$pattern` = `null`
)

Procedural style

datefmt_create(
?string `$locale`,
int `$dateType` = `IntlDateFormatter::FULL`,
int `$timeType` = `IntlDateFormatter::FULL`,
IntlTimeZone|DateTimeZone|string|null `$timezone` = `null`,
IntlCalendar|int|null `$calendar` = `null`,
?string `$pattern` = `null`
): ?IntlDateFormatter

Create a date formatter.

### Parameters

`locale`

  Locale to use when formatting or parsing or `null` to use the value specified in the ini setting intl.default_locale.

`dateType`

  Format of the date determined by one of the IntlDateFormatter constants. The default value is `IntlDateFormatter::FULL`.

`timeType`

  Format of the time determined by one of the IntlDateFormatter constants. The default value is `IntlDateFormatter::FULL`.

`timezone`

  Time zone ID. The default (and the one used if `null` is given) is the one returned by date_default_timezone_get() or, if applicable, that of the IntlCalendar object passed for the `calendar` parameter. This ID must be a valid identifier on ICUʼs database or an ID representing an explicit offset, such as `GMT-05:30`.

  This can also be an IntlTimeZone or a DateTimeZone object.

`calendar`

  Calendar to use for formatting or parsing. The default value is `null`, which corresponds to `IntlDateFormatter::GREGORIAN`. This can either be one of the IntlDateFormatter calendar constants or an IntlCalendar. Any IntlCalendar object passed will be clone; it will not be changed by the IntlDateFormatter. This will determine the calendar type used (gregorian, islamic, persian, etc.) and, if `null` is given for the `timezone` parameter, also the timezone used.

`pattern`

  Optional pattern to use when formatting or parsing. Possible patterns are documented at » https://unicode-org.github.io/icu/userguide/format_parse/datetime/.

### Return Values

The created IntlDateFormatter or `null` in case of failure.

### Errors/Exceptions

A ValueError is thrown if `locale` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | A ValueError is thrown if `locale` is invalid.
8.1.0 | Parameters `dateType` and `timeType` are now optional.

### Examples

Example #1 datefmt_create() example

`<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles', IntlDateFormatter::GREGORIAN );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "Second Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>`

Example #3 Example of invalid locale handling

`<?php
try {
$fmt = new IntlDateFormatter(
'invalid_locale',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'dunno',
IntlDateFormatter::GREGORIAN,
);
} catch (\Error $e) {
// ...
}
?>`

The above example will output:

    First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
    Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
    First Formatted output with pattern is 12/31/1969
    Second Formatted output with pattern is 12/31/1969

### See Also

- datefmt_format() - Format the date/time value as a string
- datefmt_parse() - Parse string to a timestamp value
- datefmt_get_error_code() - Get the error code from last operation
- datefmt_get_error_message() - Get the error text from the last operation

# IntlDateFormatter::format

# datefmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

### Description

Object-oriented style

public IntlDateFormatter::format(IntlCalendar|DateTimeInterface|array|string|int|float `$datetime`): string|false

Procedural style

datefmt_format(IntlDateFormatter `$formatter`, IntlCalendar|DateTimeInterface|array|string|int|float `$datetime`): string|false

Formats the time value as a string.

### Parameters

`formatter`

  The date formatter resource.

`datetime`

  Value to format. This may be a DateTimeInterface object, an IntlCalendar object, a numeric type representing a (possibly fractional) number of seconds since epoch or an array in the format output by localtime().

  If a DateTime or an IntlCalendar object is passed, its timezone is not considered. The object will be formatted using the formaterʼs configured timezone. If one wants to use the timezone of the object to be formatted, IntlDateFormatter::setTimeZone() must be called before with the objectʼs timezone. Alternatively, the static function IntlDateFormatter::formatObject() may be used instead.

### Return Values

The formatted string or, if an error occurred, `false`.

### Changelog

Version | Description
--- | ---
7.1.5 | Support for providing general DateTimeInterface objects to the `datetime` parameter was added. Formerly, only proper DateTime objects were supported.
PECL intl 3.0.0 | Support for providing IntlCalendar objects to the `datetime` parameter was added.

### Examples

Example #1 datefmt_format() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo "Second Formatted output with pattern is " . datefmt_format($fmt, 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Second Formatted output with pattern is ' . $fmt->format(0);
?>`

The above example will output:

    First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
    Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
    First Formatted output with pattern is 12/31/1969
    Second Formatted output with pattern is 12/31/1969

Example #3 With IntlCalendar object

`<?php
$tz = reset(iterator_to_array(IntlTimeZone::createEnumeration('FR')));
$formatter = IntlDateFormatter::create(
'fr_FR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
$tz,
IntlDateFormatter::GREGORIAN
);
$cal = IntlCalendar::createInstance($tz, '@calendar=islamic-civil');
$cal->set(IntlCalendar::FIELD_MONTH, 8); //9th month, Ramadan
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 1); //1st day
$cal->clear(IntlCalendar::FIELD_HOUR_OF_DAY);
$cal->clear(IntlCalendar::FIELD_MINUTE);
$cal->clear(IntlCalendar::FIELD_SECOND);
$cal->clear(IntlCalendar::FIELD_MILLISECOND);
echo "In this islamic year, Ramadan started/will start on:\n\t",
$formatter->format($cal), "\n";
//Itʼs the formatterʼs timezone that is used:
$formatter->setTimeZone('Asia/Tokyo');
echo "After changing timezone:\n\t",
$formatter->format($cal), "\n";`

The above example will output:

    In this islamic year, Ramadan started/will start on:
        mardi 9 juillet 2013 19:00:00 heure avancée d’Europe centrale
    After changing timezone:
        mercredi 10 juillet 2013 02:00:00 heure normale du Japon

### See Also

- datefmt_create() - Create a date formatter
- datefmt_parse() - Parse string to a timestamp value
- datefmt_get_error_code() - Get the error code from last operation
- datefmt_get_error_message() - Get the error text from the last operation
- datefmt_format_object() - Formats an object

# IntlDateFormatter::formatObject

# datefmt_format_object

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_object — Formats an object

### Description

Object-oriented style

public static IntlDateFormatter::formatObject(IntlCalendar|DateTimeInterface `$datetime`, array|int|string|null `$format` = `null`, ?string `$locale` = `null`): string|false

Procedural style

datefmt_format_object(IntlCalendar|DateTimeInterface `$datetime`, array|int|string|null `$format` = `null`, ?string `$locale` = `null`): string|false

This function allows formatting an IntlCalendar or DateTime object without first explicitly creating a IntlDateFormatter object.

The temporary IntlDateFormatter that will be created will take the timezone from the passed in object. The timezone database bundled with PHP will not be used – ICU's will be used instead. The timezone identifier used in DateTime objects must therefore also exist in ICU's database.

### Parameters

`datetime`

  An object of type IntlCalendar or DateTime. The timezone information in the object will be used.

`format`

  How to format the date/time. This can either be an array with two elements (first the date style, then the time style, these being one of the constants `IntlDateFormatter::NONE`, `IntlDateFormatter::SHORT`, `IntlDateFormatter::MEDIUM`, `IntlDateFormatter::LONG`, `IntlDateFormatter::FULL`), an int with the value of one of these constants (in which case it will be used both for the time and the date) or a string with the format described in » the ICU documentation. If `null`, the default style will be used.

`locale`

  The locale to use, or `null` to use the default one.

### Return Values

A string with result or `false` on failure.

### Examples

Example #1 IntlDateFormatter::formatObject() examples

`<?php
/* default timezone is irrelevant; timezone taken from the object */
ini_set('date.timezone', 'UTC');
/* default locale is taken from this ini setting */
ini_set('intl.default_locale', 'fr_FR');
$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo "default:\n\t",
IntlDateFormatter::formatObject($cal),
"\n";
echo "long \$format (full):\n\t",
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
"\n";
echo "array \$format (none, full):\n\t",
IntlDateFormatter::formatObject($cal, array(
IntlDateFormatter::NONE,
IntlDateFormatter::FULL)),
"\n";
echo "string \$format (d 'of' MMMM y):\n\t",
IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'en_US'),
"\n";
echo "with DateTime:\n\t",
IntlDateFormatter::formatObject(
new DateTime("2013-09-09 09:09:09 Europe/Madrid"),
IntlDateFormatter::FULL,
'es_ES'),
"\n";`

The above example will output:

    default:
        6 juin 2013 17:05:06
    long $format (full):
        jeudi 6 juin 2013 17:05:06 heure d’été irlandaise
    array $format (none, full):
        17:05:06 heure d’été irlandaise
    string $format (d 'of' MMMM y):
        6 of June 2013
    with DateTime:
        lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central

# IntlDateFormatter::getCalendar

# datefmt_get_calendar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar type used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::getCalendar(): int|false

Procedural style

datefmt_get_calendar(IntlDateFormatter `$formatter`): int|false

### Parameters

`formatter`

  The formatter resource

### Return Values

The calendar type being used by the formatter. Either `IntlDateFormatter::TRADITIONAL` or `IntlDateFormatter::GREGORIAN`. Returns `false` on failure.

### Examples

Example #1 datefmt_get_calendar() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();
?>`

Example #3 Example of invalid locale handling

`<?php
try {
$fmt = new IntlDateFormatter(
'invalid_locale',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'dunno',
IntlDateFormatter::GREGORIAN,
);
$cal = $fmt->getCalendar();
} catch (\Error $e) {
// ...
}
?>`

The above example will output:

    calendar of the formatter is : 1
    Now calendar of the formatter is : 0

### See Also

- datefmt_get_calendar_object() - Get copy of formatterʼs calendar object
- datefmt_set_calendar() - Sets the calendar type used by the formatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::getDateType

# datefmt_get_datetype

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::getDateType(): int|false

Procedural style

datefmt_get_datetype(IntlDateFormatter `$formatter`): int|false

Returns date type used by the formatter.

### Parameters

`formatter`

  The formatter resource.

### Return Values

The current date type value of the formatter, or `false` on failure.

### Examples

Example #1 datefmt_get_datetype() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'First Formatted output with datetype is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::SHORT,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'Second Formatted output with datetype is ' . datefmt_format($fmt, 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . $fmt->getDateType();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::SHORT,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . $fmt->getDateType();
echo 'Second Formatted output is ' . $fmt->format(0);
?>`

The above example will output:

    datetype of the formatter is : 0
    First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
    Now datetype of the formatter is : 2
    Second Formatted output is 12/31/69 4:00:00 PM PT

### See Also

- datefmt_get_timetype() - Get the timetype used for the IntlDateFormatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::getErrorCode

# datefmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

### Description

Object-oriented style

public IntlDateFormatter::getErrorCode(): int

Procedural style

datefmt_get_error_code(IntlDateFormatter `$formatter`): int

Returns the error code from the last formatting operation.

### Parameters

`formatter`

  The formatter resource.

### Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

### Examples

Example #1 datefmt_get_error_code() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt, 0);
printf(
"ERROR: %s (%d)\n",
datefmt_get_error_message($fmt),
datefmt_get_error_code($fmt)
);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = $fmt->format(0);
printf(
"ERROR: %s (%d)\n",
$fmt->getErrorMessage(),
$fmt->getErrorCode()
);
?>`

The above example will output:

    ERROR: U_ZERO_ERROR (0)

### See Also

- datefmt_get_error_message() - Get the error text from the last operation
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# IntlDateFormatter::getErrorMessage

# datefmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation

### Description

Object-oriented style

public IntlDateFormatter::getErrorMessage(): string

Procedural style

datefmt_get_error_message(IntlDateFormatter `$formatter`): string

Get the error text from the last operation.

### Parameters

`formatter`

  The formatter resource.

### Return Values

Description of the last error.

### Examples

Example #1 datefmt_get_error_message() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt, 0);
printf(
"ERROR: %s (%d)\n",
datefmt_get_error_message($fmt),
datefmt_get_error_code($fmt)
);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = $fmt->format(0);
printf(
"ERROR: %s (%d)\n",
$fmt->getErrorMessage(),
$fmt->getErrorCode()
);
?>`

The above example will output:

    ERROR: U_ZERO_ERROR (0)

### See Also

- datefmt_get_error_code() - Get the error code from last operation
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# IntlDateFormatter::getLocale

# datefmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

### Description

Object-oriented style

public IntlDateFormatter::getLocale(int `$type` = `ULOC_ACTUAL_LOCALE`): string|false

Procedural style

datefmt_get_locale(IntlDateFormatter `$formatter`, int `$type` = `ULOC_ACTUAL_LOCALE`): string|false

Get locale used by the formatter.

### Parameters

`formatter`

  The formatter resource

`type`

  You can choose between valid and actual locale ( `Locale::VALID_LOCALE`, `Locale::ACTUAL_LOCALE`, respectively). The default is the actual locale.

### Return Values

The locale of this formatter, or `false` on failure.

### Examples

Example #1 datefmt_get_locale() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . datefmt_get_locale($fmt);
echo 'First Formatted output is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . datefmt_get_locale($fmt);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'Second Formatted output is ' . $fmt->format(0);
?>`

The above example will output:

    locale of the formatter is : en
    First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
    locale of the formatter is : de
    Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00

### See Also

- datefmt_create() - Create a date formatter

# IntlDateFormatter::getPattern

# datefmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::getPattern(): string|false

Procedural style

datefmt_get_pattern(IntlDateFormatter `$formatter`): string|false

Get pattern used by the formatter.

### Parameters

`formatter`

  The formatter resource.

### Return Values

The pattern string being used to format/parse, or `false` on failure.

### Examples

Example #1 datefmt_get_pattern() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'Second Formatted output with pattern is ' . datefmt_format($fmt, 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);
?>`

The above example will output:

    pattern of the formatter is : MM/dd/yyyy
    First Formatted output is 12/31/1969
    Now pattern of the formatter is : yyyymmdd hh:mm:ss z
    Second Formatted output is 19690031 04:00:00 PST

### See Also

- datefmt_set_pattern() - Set the pattern used for the IntlDateFormatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::getTimeType

# datefmt_get_timetype

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::getTimeType(): int|false

Procedural style

datefmt_get_timetype(IntlDateFormatter `$formatter`): int|false

Return time type used by the formatter.

### Parameters

`formatter`

  The formatter resource.

### Return Values

The current date type value of the formatter, or `false` on failure.

### Examples

Example #1 datefmt_get_timetype() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'First Formatted output with timetype is ' . datefmt_format($fmt, 0);
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'Second Formatted output with timetype is ' . datefmt_format($fmt, 0);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . $fmt->getTimeType();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . $fmt->getTimeType();
echo 'Second Formatted output is ' . $fmt->format(0);
?>`

The above example will output:

    timetype of the formatter is : 0
    First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
    Now timetype of the formatter is : 3
    Second Formatted output is Wednesday, December 31, 1969 4:00 PM

### See Also

- datefmt_get_datetype() - Get the datetype used for the IntlDateFormatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::getTimeZoneId

# datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::getTimeZoneId(): string|false

Procedural style

datefmt_get_timezone_id(IntlDateFormatter `$formatter`): string|false

Get the timezone-id used for the IntlDateFormatter.

### Parameters

`formatter`

  The formatter resource.

### Return Values

ID string for the time zone used by this formatter, or `false` on failure.

### Examples

Example #1 datefmt_get_timezone_id() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt) . "\n";
datefmt_set_timezone($fmt, 'Europe/Madrid');
echo 'Now timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is: ' . $fmt->getTimezoneId() . "\n";
$fmt->setTimezone('Europe/Madrid');
echo 'Now timezone_id of the formatter is: ' . $fmt->getTimezoneId();
?>`

The above example will output:

    timezone_id of the formatter is: America/Los_Angeles
    Now timezone_id of the formatter is: Europe/Madrid

### See Also

- datefmt_set_timezone() - Sets formatterʼs timezone
- datefmt_create() - Create a date formatter

# IntlDateFormatter::getCalendarObject

# datefmt_get_calendar_object

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::getCalendarObject -- datefmt_get_calendar_object — Get copy of formatterʼs calendar object

### Description

Object-oriented style

public IntlDateFormatter::getCalendarObject(): IntlCalendar|false|null

Procedural style

datefmt_get_calendar_object(IntlDateFormatter `$formatter`): IntlCalendar|false|null

Obtain a copy of the calendar object used internally by this formatter. This calendar will have a type (as in gregorian, japanese, buddhist, roc, persian, islamic, etc.) and a timezone that match the type and timezone used by the formatter. The date/time of the object is unspecified.

### Parameters

This function has no parameters.

### Return Values

A copy of the internal calendar object used by this formatter, or `null` if none has been set, or `false` on failure.

### Examples

Example #1 IntlDateFormatter::getCalendarObject() example

`<?php
$formatter = IntlDateFormatter::create(
"fr_FR@calendar=islamic",
NULL,
NULL,
"GMT-01:00",
IntlDateFormatter::TRADITIONAL
);
$cal = $formatter->getCalendarObject();
var_dump(
$cal->getType(),
$cal->getTimeZone(),
$cal->getLocale(Locale::VALID_LOCALE)
);`

The above example will output:

    string(7) "islamic"
    object(IntlTimeZone)#3 (4) {
      ["valid"]=>
      bool(true)
      ["id"]=>
      string(9) "GMT-01:00"
      ["rawOffset"]=>
      int(-3600000)
      ["currentOffset"]=>
      int(-3600000)
    }
    string(5) "fr_FR"

### See Also

- IntlDateFormatter::getCalendar() - Get the calendar type used for the IntlDateFormatter
- IntlDateFormatter::setCalendar() - Sets the calendar type used by the formatter
- IntlCalendar

# IntlDateFormatter::getTimeZone

# datefmt_get_timezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::getTimeZone -- datefmt_get_timezone — Get formatterʼs timezone

### Description

Object-oriented style

public IntlDateFormatter::getTimeZone(): IntlTimeZone|false

Procedural style

datefmt_get_timezone(IntlDateFormatter `$formatter`): IntlTimeZone|false

Returns an IntlTimeZone object representing the timezone that will be used by this object to format dates and times. When formatting IntlCalendar and DateTime objects with this IntlDateFormatter, the timezone used will be the one returned by this method, not the one associated with the objects being formatted.

### Parameters

This function has no parameters.

### Return Values

The associated IntlTimeZone object or `false` on failure.

### Examples

Example #1 IntlDateFormatter::getTimeZone() examples

`<?php
$madrid = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Madrid');
$lisbon = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Lisbon');
var_dump($madrid->getTimezone());
echo $madrid->getTimezone()->getDisplayName(
false, IntlTimeZone::DISPLAY_GENERIC_LOCATION, "en_US"), "\n";
echo $lisbon->getTimeZone()->getId(), "\n";
//The id can also be retrieved with ->getTimezoneId()
echo $lisbon->getTimeZoneId(), "\n";`

The above example will output:

    object(IntlTimeZone)#4 (4) {
      ["valid"]=>
      bool(true)
      ["id"]=>
      string(13) "Europe/Madrid"
      ["rawOffset"]=>
      int(3600000)
      ["currentOffset"]=>
      int(7200000)
    }
    Spain Time
    Europe/Lisbon
    Europe/Lisbon

### See Also

- IntlDateFormatter::getTimeZoneId() - Get the timezone-id used for the IntlDateFormatter
- IntlDateFormatter::setTimeZone() - Sets formatterʼs timezone
- IntlTimeZone

# IntlDateFormatter::isLenient

# datefmt_is_lenient

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::isLenient(): bool

Procedural style

datefmt_is_lenient(IntlDateFormatter `$formatter`): bool

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

### Parameters

`formatter`

  The formatter resource.

### Return Values

`true` if parser is lenient, `false` if parser is strict. By default the parser is lenient.

### Examples

Example #1 datefmt_is_lenient() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/mm/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').Result is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
"dd/mm/yyyy"
);
echo "lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0){
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
$fmt->setLenient(FALSE);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
?>`

The above example will output:

    lenient of the formatter is : TRUE
    Trying to do parse('35/13/1971').
    Result is : -2147483
    Now lenient of the formatter is : FALSE
    Trying to do parse('35/13/1971').
    Result is :
    Error_msg is : Date parsing failed: U_PARSE_ERROR
    Error_code is : 9

### See Also

- datefmt_set_lenient() - Set the leniency of the parser
- datefmt_create() - Create a date formatter

# IntlDateFormatter::localtime

# datefmt_localtime

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

### Description

Object-oriented style

public IntlDateFormatter::localtime(string `$string`, int `&$offset` = `null`): array|false

Procedural style

datefmt_localtime(IntlDateFormatter `$formatter`, string `$string`, int `&$offset` = `null`): array|false

Converts string $value to a field-based time value ( an array of various fields), starting at $parse_pos and consuming as much of the input value as possible.

### Parameters

`formatter`

  The formatter resource

`string`

  string to convert to a time

`offset`

  Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse_pos > strlen($value), the parse fails immediately.

### Return Values

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field, or `false` on failure.

### Examples

Example #1 datefmt_localtime() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = datefmt_localtime($fmt, 'Wednesday, December 31, 1969 at 4:00:00 PM Pacific Standard Time', $offset);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = $fmt->localtime('Wednesday, December 31, 1969 at 4:00:00 PM Pacific Standard Time', $offset);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>`

The above example will output:

    First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 69 ,
    tm_mday : 31 , tm_wday : 3 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,

### See Also

- datefmt_create() - Create a date formatter
- datefmt_format() - Format the date/time value as a string
- datefmt_parse() - Parse string to a timestamp value
- datefmt_get_error_code() - Get the error code from last operation
- datefmt_get_error_message() - Get the error text from the last operation

# IntlDateFormatter::parse

# datefmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

### Description

Object-oriented style

public IntlDateFormatter::parse(string `$string`, int `&$offset` = `null`): int|float|false

Procedural style

datefmt_parse(IntlDateFormatter `$formatter`, string `$string`, int `&$offset` = `null`): int|float|false

Converts `string` to an incremental time value, starting at `offset` and consuming as much of the input value as possible.

### Parameters

`formatter`

  The formatter resource

`string`

  string to convert to a time

`offset`

  Position at which to start the parsing in `string` (zero-based). If no error occurs before `string` is consumed, `offset` will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If `offset` > `strlen($string)`, the parse fails immediately.

### Return Values

Timestamp of parsed value, or `false` if value cannot be parsed.

### Examples

Example #1 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . $fmt->parse('Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
?>`

Example #2 datefmt_parse() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . datefmt_parse($fmt, 'Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second parsed output is ' . datefmt_parse($fmt, 'Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00');
?>`

The above example will output:

    First parsed output is 630201600
    Second parsed output is 630201600

### See Also

- datefmt_create() - Create a date formatter
- datefmt_format() - Format the date/time value as a string
- datefmt_localtime() - Parse string to a field-based time value
- datefmt_get_error_code() - Get the error code from last operation
- datefmt_get_error_message() - Get the error text from the last operation

# IntlDateFormatter::setCalendar

# datefmt_set_calendar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — Sets the calendar type used by the formatter

### Description

Object-oriented style

public IntlDateFormatter::setCalendar(IntlCalendar|int|null `$calendar`): bool

Procedural style

datefmt_set_calendar(IntlDateFormatter `$formatter`, IntlCalendar|int|null `$calendar`): bool

Sets the calendar or calendar type used by the formatter.

### Parameters

`formatter`

  The formatter resource.

`calendar`

  This can either be: the calendar type to use (default is `IntlDateFormatter::GREGORIAN`, which is also used if `null` is specified) or an IntlCalendar object.

  Any IntlCalendar object passed in will be cloned; no modifications will be made to the argument object.

  The timezone of the formatter will only be kept if an IntlCalendar object is not passed, otherwise the new timezone will be that of the passed object.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
PECL intl 3.0.0 | It became possible to pass an IntlCalendar object.

### Examples

Example #1 datefmt_set_calendar() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();
?>`

The above example will output:

    calendar of the formatter is : 1
    Now calendar of the formatter is : 0

Example #3 Example with IntlCalendar argument

`<?php
$time = strtotime("2013-03-03 00:00:00 UTC");
$formatter = IntlDateFormatter::create("en_US", NULL, NULL, "Europe/Amsterdam");
echo "before: ", $formatter->format($time), "\n";
/* note that the calendar's locale is not used! */
$formatter->setCalendar(IntlCalendar::createInstance(
"America/New_York", "pt_PT@calendar=islamic"));
echo "after: ", $formatter->format($time), "\n";`

The above example will output:

    before: Sunday, March 3, 2013 at 1:00:00 AM Central European Standard Time
    after:  Saturday, Rabiʻ II 20, 1434 at 7:00:00 PM Eastern Standard Time

### See Also

- datefmt_get_calendar() - Get the calendar type used for the IntlDateFormatter
- datefmt_get_calendar_object() - Get copy of formatterʼs calendar object
- datefmt_create() - Create a date formatter

# IntlDateFormatter::setLenient

# datefmt_set_lenient

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

### Description

Object-oriented style

public IntlDateFormatter::setLenient(bool `$lenient`): void

Procedural style

datefmt_set_lenient(IntlDateFormatter `$formatter`, bool `$lenient`): void

Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted.

### Parameters

`formatter`

  The formatter resource

`lenient`

  Sets whether the parser is lenient or not, default is `true` (lenient).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 datefmt_set_lenient() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/MM/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt, false);
echo "\nNow lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\nTrying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : ".intl_get_error_message();
echo "\nError_code is : ".intl_get_error_code();
}
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/MM/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
$fmt->setLenient(FALSE);
echo "\nNow lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
?>`

The above example will output:

    lenient of the formatter is : TRUE
    Trying to do parse('35/13/1971').
    Result is : 66038400
    Now lenient of the formatter is : FALSE
    Trying to do parse('35/13/1971').
    Result is :
    Error_msg is : Date parsing failed: U_PARSE_ERROR
    Error_code is : 9

### See Also

- datefmt_is_lenient() - Get the lenient used for the IntlDateFormatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::setPattern

# datefmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

### Description

Object-oriented style

public IntlDateFormatter::setPattern(string `$pattern`): bool

Procedural style

datefmt_set_pattern(IntlDateFormatter `$formatter`, string `$pattern`): bool

Set the pattern used for the IntlDateFormatter.

### Parameters

`formatter`

  The formatter resource.

`pattern`

  New pattern string to use. Possible patterns are documented at » https://unicode-org.github.io/icu/userguide/format_parse/datetime/.

### Return Values

Returns `true` on success or `false` on failure. Bad formatstrings are usually the cause of the failure.

### Examples

Example #1 datefmt_set_pattern() example

`<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Pattern of the formatter is : ', datefmt_get_pattern($fmt), PHP_EOL;
echo 'First Formatted output with pattern is ', datefmt_format($fmt, 0), PHP_EOL;
datefmt_set_pattern($fmt, 'yyyyMMdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ', datefmt_get_pattern($fmt), PHP_EOL;
echo 'Second Formatted output with pattern is ', datefmt_format($fmt, 0), PHP_EOL;
?>`

Example #2 OO example

`<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Pattern of the formatter is : ', $fmt->getPattern(), PHP_EOL;
echo 'First Formatted output is ', $fmt->format(0), PHP_EOL;
$fmt->setPattern('yyyyMMdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ', $fmt->getPattern(), PHP_EOL;
echo 'Second Formatted output is ', $fmt->format(0), PHP_EOL;
?>`

The above example will output:

    Pattern of the formatter is : MM/dd/yyyy
    First Formatted output is 12/31/1969
    Now pattern of the formatter is : yyyyMMdd hh:mm:ss z
    Second Formatted output is 19691231 04:00:00 PST

### See Also

- datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
- datefmt_create() - Create a date formatter

# IntlDateFormatter::setTimeZone

# datefmt_set_timezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::setTimeZone -- datefmt_set_timezone — Sets formatterʼs timezone

### Description

Object-oriented style

public IntlDateFormatter::setTimeZone(IntlTimeZone|DateTimeZone|string|null `$timezone`): bool

Procedural style

datefmt_set_timezone(IntlDateFormatter `$formatter`, IntlTimeZone|DateTimeZone|string|null `$timezone`): bool

Sets the timezone used for the IntlDateFormatter. object.

### Parameters

`formatter`

  The formatter resource.

`timezone`

  The timezone to use for this formatter. This can be specified in the following forms:

  - `null`, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  - An IntlTimeZone, which will be used directly.

  - A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  - A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as `"GMT+08:30"` are also accepted.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | This function now returns `true` on success; previously it returns `null`.

### Examples

Example #1 IntlDateFormatter::setTimeZone() examples

`<?php
ini_set('date.timezone', 'Europe/Amsterdam');
$formatter = IntlDateFormatter::create(NULL, NULL, NULL, "UTC");
$formatter->setTimeZone(NULL);
echo "NULL\n ", $formatter->getTimeZone()->getId(), "\n";
$formatter->setTimeZone(IntlTimeZone::createTimeZone('Europe/Lisbon'));
echo "IntlTimeZone\n ", $formatter->getTimeZone()->getId(), "\n";
$formatter->setTimeZone(new DateTimeZone('Europe/Paris'));
echo "DateTimeZone\n ", $formatter->getTimeZone()->getId(), "\n";
$formatter->setTimeZone('Europe/Rome');
echo "String\n ", $formatter->getTimeZone()->getId(), "\n";
$formatter->setTimeZone('GMT+00:30');
print_r($formatter->getTimeZone());`

The above example will output:

    NULL
        Europe/Amsterdam
    IntlTimeZone
        Europe/Lisbon
    DateTimeZone
        Europe/Paris
    String
        Europe/Rome
    IntlTimeZone Object
    (
        [valid] => 1
        [id] => GMT+00:30
        [rawOffset] => 1800000
        [currentOffset] => 1800000
    )

### See Also

- IntlDateFormatter::getTimeZone() - Get formatterʼs timezone

## Table of Contents

- IntlDateFormatter::create — Create a date formatter
- IntlDateFormatter::format — Format the date/time value as a string
- IntlDateFormatter::formatObject — Formats an object
- IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
- IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
- IntlDateFormatter::getErrorCode — Get the error code from last operation
- IntlDateFormatter::getErrorMessage — Get the error text from the last operation
- IntlDateFormatter::getLocale — Get the locale used by formatter
- IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
- IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
- IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
- IntlDateFormatter::getCalendarObject — Get copy of formatterʼs calendar object
- IntlDateFormatter::getTimeZone — Get formatterʼs timezone
- IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
- IntlDateFormatter::localtime — Parse string to a field-based time value
- IntlDateFormatter::parse — Parse string to a timestamp value
- IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
- IntlDateFormatter::setLenient — Set the leniency of the parser
- IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
- IntlDateFormatter::setTimeZone — Sets formatterʼs timezone

# The ResourceBundle class

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

## Introduction

Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion.

This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data.

ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following types: string, integer, binary data field or integer array.

ResourceBundle supports direct access to the data through array access pattern and iteration via foreach, as well as access via class methods. The result will be PHP value for simple resources and ResourceBundle object for complex ones. All resources are read-only.

## Class synopsis

class ResourceBundle implements IteratorAggregate, Countable {
/* Methods */
public __construct(?string `$locale`, ?string `$bundle`, bool `$fallback` = `true`)
public count(): int
public static create(?string `$locale`, ?string `$bundle`, bool `$fallback` = `true`): ?ResourceBundle
public get(string|int `$index`, bool `$fallback` = `true`): ResourceBundle|array|string|int|null
public getErrorCode(): int
public getErrorMessage(): string
public static getLocales(string `$bundle`): array|false
}

## Changelog

Version | Description
--- | ---
8.0.0 | ResourceBundle implements IteratorAggregate now. Previously, Traversable was implemented instead.
7.4.0 | ResourceBundle implements Countable now.

## See Also

- » ICU Resource Management
- » ICU Data

# ResourceBundle::count

# resourcebundle_count

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

### Description

Object-oriented style

public ResourceBundle::count(): int

Procedural style

resourcebundle_count(ResourceBundle `$bundle`): int

Get the number of elements in the bundle.

### Parameters

`bundle`

  ResourceBundle object.

### Return Values

Returns number of elements in the bundle.

### Examples

Example #1 resourcebundle_count() example

`<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>`

Example #2 OO example

`<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>`

The above example will output:

    42

### See Also

- resourcebundle_get() - Get data from the bundle

# ResourceBundle::create

# resourcebundle_create

# ResourceBundle::__construct

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

### Description

Object-oriented style (method)

public static ResourceBundle::create(?string `$locale`, ?string `$bundle`, bool `$fallback` = `true`): ?ResourceBundle

Procedural style

resourcebundle_create(?string `$locale`, ?string `$bundle`, bool `$fallback` = `true`): ?ResourceBundle

Object-oriented style (constructor):

public ResourceBundle::__construct(?string `$locale`, ?string `$bundle`, bool `$fallback` = `true`)

Creates a resource bundle.

### Parameters

`locale`

  Locale for which the resources should be loaded (locale name, e.g. en_CA).

`bundle`

  The directory where the data is stored or the name of the .dat file.

`fallback`

  Whether locale should match exactly or fallback to parent locale is allowed.

### Return Values

Returns ResourceBundle object or `null` on error.

### Examples

Example #1 resourcebundle_create() example

`<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>`

Example #2 ResourceBundle::create() example

`<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>`

The above example will output:

    ¡Hola, mundo!

### See Also

- resourcebundle_get() - Get data from the bundle

# ResourceBundle::get

# resourcebundle_get

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

### Description

Object-oriented style

public ResourceBundle::get(string|int `$index`, bool `$fallback` = `true`): ResourceBundle|array|string|int|null

Procedural style

resourcebundle_get(ResourceBundle `$bundle`, string|int `$index`, bool `$fallback` = `true`): ResourceBundle|array|string|int|null

Get the data from the bundle by index or string key.

### Parameters

`bundle`

  ResourceBundle object.

`index`

  Data index, must be string or integer.

`fallback`

  Whether locale should match exactly or fallback to parent locale is allowed.

### Return Values

Returns the data located at the index or `null` on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as ResourceBundle object.

### Errors/Exceptions

A TypeError is thrown if the offset type is invalid.

A ValueError is thrown if if `index` is a string and is empty or is a int and does not fit into a 32 bit integer type.

### Changelog

Version | Description
--- | ---
8.4.0 | A TypeError is thrown if the offset type is invalid. A ValueError is thrown if if `index` is a string and is empty or is a int and does not fit into a 32 bit integer type.

### Examples

Example #1 resourcebundle_get() example

`<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>`

Example #2 OO example

`<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>`

The above example will output:

    ?Hola, mundo!

### See Also

- resourcebundle_count() - Get number of elements in the bundle

# ResourceBundle::getErrorCode

# resourcebundle_get_error_code

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code

### Description

Object-oriented style

public ResourceBundle::getErrorCode(): int

Procedural style

resourcebundle_get_error_code(ResourceBundle `$bundle`): int

Get error code from the last function performed by the bundle object.

### Parameters

`bundle`

  ResourceBundle object.

### Return Values

Returns error code from last bundle object call.

### Examples

Example #1 resourcebundle_get_error_code() example

`<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
report_error("Bundle error");
}
?>`

Example #2 OO example

`<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
report_error("Bundle error");
}
?>`

### See Also

- resourcebundle_get_error_message() - Get bundle's last error message
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# ResourceBundle::getErrorMessage

# resourcebundle_get_error_message

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message

### Description

Object-oriented style

public ResourceBundle::getErrorMessage(): string

Procedural style

resourcebundle_get_error_message(ResourceBundle `$bundle`): string

Get error message from the last function performed by the bundle object.

### Parameters

`bundle`

  ResourceBundle object.

### Return Values

Returns error message from last bundle object's call.

### Examples

Example #1 resourcebundle_get_error_message() example

`<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
report_error("Bundle error: ".resourcebundle_get_error_message($r));
}
?>`

Example #2 OO example

`<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
report_error("Bundle error: ".ResourceBundle::getErrorMessage($r));
}
?>`

### See Also

- resourcebundle_get_error_code() - Get bundle's last error code
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure

# ResourceBundle::getLocales

# resourcebundle_locales

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

### Description

Object-oriented style

public static ResourceBundle::getLocales(string `$bundle`): array|false

Procedural style

resourcebundle_locales(string `$bundle`): array|false

Get available locales from ResourceBundle name.

### Parameters

`bundle`

  Path of ResourceBundle for which to get available locales, or empty string for default locales list.

### Return Values

Returns the list of locales supported by the bundle, or `false` on failure.

### Examples

Example #1 resourcebundle_locales() example

`<?php
$bundle = "/user/share/data/myapp";
echo join(PHP_EOL, resourcebundle_locales($bundle));
?>`

The above example will output something similar to:

    es
    root

Example #2 OO example

`<?php
$bundle = "/usr/share/data/myapp";
$r = new ResourceBundle( 'es', $bundle);
echo join("\n", $r->getLocales($bundle));
?>`

The above example will output something similar to:

    es
    root

### See Also

- resourcebundle_get() - Get data from the bundle

## Table of Contents

- ResourceBundle::count — Get number of elements in the bundle
- ResourceBundle::create — Create a resource bundle
- ResourceBundle::get — Get data from the bundle
- ResourceBundle::getErrorCode — Get bundle's last error code
- ResourceBundle::getErrorMessage — Get bundle's last error message
- ResourceBundle::getLocales — Get supported locales

# The Spoofchecker class

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

## Introduction

This class is provided because Unicode contains large number of characters and incorporates the varied writing systems of the world and their incorrect usage can expose programs or systems to possible security attacks using characters similarity.

Provided methods allow to check whether an individual string is likely an attempt at confusing the reader (`spoof detection`), such as "pаypаl" spelled with Cyrillic 'а' characters.

## Class synopsis

class Spoofchecker {
/* Constants */
public const int SINGLE_SCRIPT_CONFUSABLE;
public const int MIXED_SCRIPT_CONFUSABLE;
public const int WHOLE_SCRIPT_CONFUSABLE;
public const int ANY_CASE;
public const int SINGLE_SCRIPT;
public const int INVISIBLE;
public const int CHAR_LIMIT;
public const int ASCII;
public const int HIGHLY_RESTRICTIVE;
public const int MODERATELY_RESTRICTIVE;
public const int MINIMALLY_RESTRICTIVE;
public const int UNRESTRICTIVE;
public const int SINGLE_SCRIPT_RESTRICTIVE;
public const int MIXED_NUMBERS;
public const int HIDDEN_OVERLAY;
public const int IGNORE_SPACE;
public const int CASE_INSENSITIVE;
public const int ADD_CASE_MAPPINGS;
public const int SIMPLE_CASE_INSENSITIVE;
/* Methods */
public __construct()
public areConfusable(string `$string1`, string `$string2`, int `&$errorCode` = `null`): bool
public isSuspicious(string `$string`, int `&$errorCode` = `null`): bool
public setAllowedLocales(string `$locales`): void
public setChecks(int `$checks`): void
public setRestrictionLevel(int `$level`): void
}

## Predefined Constants

`Spoofchecker::SINGLE_SCRIPT_CONFUSABLE` int

`Spoofchecker::MIXED_SCRIPT_CONFUSABLE` int

`Spoofchecker::WHOLE_SCRIPT_CONFUSABLE` int

`Spoofchecker::ANY_CASE` int

`Spoofchecker::SINGLE_SCRIPT` int

`Spoofchecker::INVISIBLE` int

`Spoofchecker::CHAR_LIMIT` int

`Spoofchecker::ASCII` int

`Spoofchecker::HIGHLY_RESTRICTIVE` int

`Spoofchecker::MODERATELY_RESTRICTIVE` int

`Spoofchecker::MINIMALLY_RESTRICTIVE` int

`Spoofchecker::UNRESTRICTIVE` int

`Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE` int

`Spoofchecker::MIXED_NUMBERS` int

`Spoofchecker::HIDDEN_OVERLAY` int

`Spoofchecker::IGNORE_SPACE` int

`Spoofchecker::CASE_INSENSITIVE` int
  Enables case-insensitive matching
`Spoofchecker::ADD_CASE_MAPPINGS` int

  Adds all case mappings for each element in the set

`Spoofchecker::SIMPLE_CASE_INSENSITIVE` int
  Enables case-insensitive matching

## Changelog

Version | Description
--- | ---
8.4.0 | Added `Spoofchecker::IGNORE_SPACE`, `Spoofchecker::CASE_INSENSITIVE`, `Spoofchecker::ADD_CASE_MAPPINGS`, `Spoofchecker::SIMPLE_CASE_INSENSITIVE`.
8.4.0 | The class constants are now typed.
7.3.0 | Class constants used by Spoofchecker::setRestrictionLevel() such as `Spoofchecker::ASCII`, `Spoofchecker::HIGHLY_RESTRICTIVE`, `Spoofchecker::MODERATELY_RESTRICTIVE`, `Spoofchecker::MINIMALLY_RESTRICTIVE`, `Spoofchecker::UNRESTRICTIVE`, `Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE` has been added.

# Spoofchecker::areConfusable

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::areConfusable — Checks if given strings can be confused

### Description

public Spoofchecker::areConfusable(string `$string1`, string `$string2`, int `&$errorCode` = `null`): bool

Checks whether two given strings can easily be mistaken.

### Parameters

`string1`

  First string to check.

`string2`

  Second string to check.

`errorCode`

  This variable is set by-reference to int containing an error, if there was any.

### Return Values

Returns `true` if two given strings can be confused, `false` otherwise.

### Examples

Example #1 Spoofchecker::areConfusable() example

`<?php
$checker = new Spoofchecker();
$checker->areConfusable('google.com', 'goog1e.com'); // true
// Lower l can be confused with digit one
$checker->areConfusable('google.com', 'g00g1e.com'); // false
// Zero (0) cannot be easily confused with "o" letter`

# Spoofchecker::__construct

(No version information available, might only be in Git)

Spoofchecker::__construct — Constructor

### Description

public Spoofchecker::__construct()

Creates new instance of Spoofchecker.

### Parameters

This function has no parameters.

# Spoofchecker::isSuspicious

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

### Description

public Spoofchecker::isSuspicious(string `$string`, int `&$errorCode` = `null`): bool

Checks if given string contains any suspicious characters like letters which are almost identical visually, but are Unicode characters from different sets.

### Parameters

`string`

  String to test.

`errorCode`

  This variable is set by-reference to int containing an error, if there was any.

### Return Values

Returns `true` if there are suspicious characters, `false` otherwise.

### Examples

Example #1 Spoofchecker::isSuspicious() example

`<?php
$checker = new Spoofchecker();
$checker->isSuspicious('google.com'); // FALSE: only ASCII characters
$checker->isSuspicious('Рaypal.com'); // TRUE
// The first letter is from Cyrylic, not a regular latin "P"`

# Spoofchecker::setAllowedLocales

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

### Description

public Spoofchecker::setAllowedLocales(string `$locales`): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locales`

### Return Values

# Spoofchecker::setChecks

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::setChecks — Set the checks to run

### Description

public Spoofchecker::setChecks(int `$checks`): void

Sets the checks that will be performed by SpoofChecker::isSuspicious().

### Parameters

`checks`

  The checks that will be performed by SpoofChecker::isSuspicious(). A bitmask of `Spoofchecker::SINGLE_SCRIPT_CONFUSABLE`, `Spoofchecker::MIXED_SCRIPT_CONFUSABLE`, `Spoofchecker::WHOLE_SCRIPT_CONFUSABLE`, `Spoofchecker::ANY_CASE`, `Spoofchecker::SINGLE_SCRIPT`, `Spoofchecker::INVISIBLE`, or `Spoofchecker::CHAR_LIMIT`. Defaults to all checks as of ICU 58; prior to that version, `Spoofchecker::SINGLE_SCRIPT` was excluded.

### Return Values

No value is returned.

# Spoofchecker::setRestrictionLevel

(PHP 7 >= 7.3.0, PHP 8)

Spoofchecker::setRestrictionLevel — Set the restriction level

### Description

public Spoofchecker::setRestrictionLevel(int `$level`): void

Sets the restriction level of SpoofChecker::isSuspicious().

### Parameters

`level`

  The restriction level of SpoofChecker::isSuspicious(). One of `Spoofchecker::ASCII`, `Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE`, `Spoofchecker::HIGHLY_RESTRICTIVE`, `Spoofchecker::MODERATELY_RESTRICTIVE`, `Spoofchecker::MINIMALLY_RESTRICTIVE`, or `Spoofchecker::UNRESTRICTIVE`. Defaults to `Spoofchecker::HIGHLY_RESTRICTIVE`.

### Return Values

No value is returned.

## Table of Contents

- Spoofchecker::areConfusable — Checks if given strings can be confused
- Spoofchecker::__construct — Constructor
- Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
- Spoofchecker::setAllowedLocales — Locales to use when running checks
- Spoofchecker::setChecks — Set the checks to run
- Spoofchecker::setRestrictionLevel — Set the restriction level

# The Transliterator class

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

## Introduction

Transliterator provides transliteration of strings.

## Class synopsis

class Transliterator {
/* Constants */
public const int FORWARD;
public const int REVERSE;
/* Properties */
public readonly string $id;
/* Methods */
final private __construct()
public static create(string `$id`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator
public static createFromRules(string `$rules`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator
public createInverse(): ?Transliterator
public getErrorCode(): int
public getErrorMessage(): string
public static listIDs(): array|false
public transliterate(string `$string`, int `$start` = 0, int `$end` = -1): string|false
}

## Properties

id

## Predefined Constants

`Transliterator::FORWARD` int

`Transliterator::REVERSE` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
8.2.0 | The id property is now readonly.

# Transliterator::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::__construct — Private constructor to deny instantiation

### Description

final private Transliterator::__construct()

This method should not be called. Its only purpose is to deny instantiation with the new operator.

Use the factory methods Transliterator::create() or Transliterator::createFromRules() instead.

### Parameters

This function has no parameters.

### See Also

- Transliterator::create() - Create a transliterator
- Transliterator::createFromRules() - Create transliterator from rules

# Transliterator::create

# transliterator_create

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::create -- transliterator_create — Create a transliterator

### Description

Object-oriented style

public static Transliterator::create(string `$id`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator

Procedural style

transliterator_create(string `$id`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator

Opens a Transliterator by ID.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`id`

  The ID. A list of all registered transliterator IDs can be retrieved by using Transliterator::listIDs().

`direction`

  The direction, defaults to Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

### Return Values

Returns a Transliterator object on success, or `null` on failure.

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::__construct() - Private constructor to deny instantiation

# Transliterator::createFromRules

# transliterator_create_from_rules

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::createFromRules -- transliterator_create_from_rules — Create transliterator from rules

### Description

Object-oriented style

public static Transliterator::createFromRules(string `$rules`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator

Procedural style

transliterator_create_from_rules(string `$rules`, int `$direction` = `Transliterator::FORWARD`): ?Transliterator

Creates a Transliterator from rules.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`rules`

  The rules as defined in Transform Rules Syntax of UTS #35: Unicode LDML.

`direction`

  The direction, defaults to Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

### Return Values

Returns a Transliterator object on success, or `null` on failure.

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::create() - Create a transliterator

# Transliterator::createInverse

# transliterator_create_inverse

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

### Description

Object-oriented style

public Transliterator::createInverse(): ?Transliterator

Procedural style

transliterator_create_inverse(Transliterator `$transliterator`): ?Transliterator

Opens the inverse transliterator.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns a Transliterator object on success, or `null` on failure

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::create() - Create a transliterator

# Transliterator::getErrorCode

# transliterator_get_error_code

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

### Description

Object-oriented style

public Transliterator::getErrorCode(): int

Procedural style

transliterator_get_error_code(Transliterator `$transliterator`): int

Gets the last error code for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`transliterator`

### Return Values

The error code on success, or `false` if none exists, or on failure.

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::listIDs() - Get transliterator IDs

# Transliterator::getErrorMessage

# transliterator_get_error_message

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

### Description

Object-oriented style

public Transliterator::getErrorMessage(): string

Procedural style

transliterator_get_error_message(Transliterator `$transliterator`): string

Gets the last error message for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`transliterator`

### Return Values

The error message on success, or `false` if none exists, or on failure.

### See Also

- Transliterator::getErrorCode() - Get last error code
- Transliterator::listIDs() - Get transliterator IDs

# Transliterator::listIDs

# transliterator_list_ids

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

### Description

Object-oriented style

public static Transliterator::listIDs(): array|false

Procedural style

transliterator_list_ids(): array|false

Returns an array with the registered transliterator IDs.

### Parameters

This function has no parameters.

### Return Values

An array of registered transliterator IDs on success, or `false` on failure.

### Examples

Example #1 Retrieving the registered transliterator IDs

`<?php
print_r(Transliterator::listIDs());
?>`

The above example will output something similar to:

    Array
    (
        [0] => ASCII-Latin
        [1] => Accents-Any
        [2] => Amharic-Latin/BGN
        [3] => Any-Accents
        [4] => Any-Publishing
    ...
        [650] => Any-ps_Latn/BGN
        [651] => Any-tk/BGN
        [652] => Any-ch_FONIPA
        [653] => Any-cs_FONIPA
        [654] => Any-cy_FONIPA
    )

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::transliterate() - Transliterate a string

# Transliterator::transliterate

# transliterator_transliterate

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

### Description

Object-oriented style

public Transliterator::transliterate(string `$string`, int `$start` = 0, int `$end` = -1): string|false

Procedural style

transliterator_transliterate(
Transliterator|string `$transliterator`,
string `$string`,
int `$start` = 0,
int `$end` = -1
): string|false

Transforms a string or part thereof using an ICU transliterator.

### Parameters

`transliterator`

  In the procedural version, either a Transliterator or a string from which a Transliterator can be built.

`string`

  The string to be transformed.

`start`

  The start index (in UTF-16 code units) from which the string will start to be transformed, inclusive. Indexing starts at 0. The text before will be left as is.

`end`

  The end index (in UTF-16 code units) until which the string will be transformed, exclusive. Indexing starts at 0. The text after will be left as is.

### Return Values

The transformed string on success, or `false` on failure.

### Examples

Example #1 Converting escaped UTF-16 code units

`<?php
$s = "\u304A\u65E9\u3046\u3054\u3056\u3044\u307E\u3059";
echo transliterator_transliterate("Hex-Any/Java", $s), "\n";
//now the reverse operation with a supplementary character
$supplChar = html_entity_decode('&#x1D11E;');
echo mb_strlen($supplChar, "UTF-8"), "\n";
$encSupplChar = transliterator_transliterate("Any-Hex/Java", $supplChar);
//echoes two encoded UTF-16 code units
echo $encSupplChar, "\n";
//and back
echo transliterator_transliterate("Hex-Any/Java", $encSupplChar), "\n";
?>`

The above example will output something similar to:

    お早うございます
    1
    \uD834\uDD1E
    𝄞

### See Also

- Transliterator::getErrorMessage() - Get last error message
- Transliterator::__construct() - Private constructor to deny instantiation

## Table of Contents

- Transliterator::__construct — Private constructor to deny instantiation
- Transliterator::create — Create a transliterator
- Transliterator::createFromRules — Create transliterator from rules
- Transliterator::createInverse — Create an inverse transliterator
- Transliterator::getErrorCode — Get last error code
- Transliterator::getErrorMessage — Get last error message
- Transliterator::listIDs — Get transliterator IDs
- Transliterator::transliterate — Transliterate a string

# The IntlBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

A “break iterator” is an ICU object that exposes methods for locating boundaries in text (e.g. word or sentence boundaries). The PHP IntlBreakIterator serves as the base class for all types of ICU break iterators. Where extra functionality is available, the intl extension may expose the ICU break iterator with suitable subclasses, such as IntlRuleBasedBreakIterator or IntlCodePointBreakIterator.

This class implements IteratorAggregate. Traversing an IntlBreakIterator yields non-negative integer values representing the successive locations of the text boundaries, expressed as UTF-8 code units (byte) counts, taken from the beginning of the text (which has the location `0`). The keys yielded by the iterator simply form the sequence of natural numbers `{0, 1, 2, …}`.

## Class synopsis

class IntlBreakIterator implements IteratorAggregate {
/* Constants */
public const int DONE;
public const int WORD_NONE;
public const int WORD_NONE_LIMIT;
public const int WORD_NUMBER;
public const int WORD_NUMBER_LIMIT;
public const int WORD_LETTER;
public const int WORD_LETTER_LIMIT;
public const int WORD_KANA;
public const int WORD_KANA_LIMIT;
public const int WORD_IDEO;
public const int WORD_IDEO_LIMIT;
public const int LINE_SOFT;
public const int LINE_SOFT_LIMIT;
public const int LINE_HARD;
public const int LINE_HARD_LIMIT;
public const int SENTENCE_TERM;
public const int SENTENCE_TERM_LIMIT;
public const int SENTENCE_SEP;
public const int SENTENCE_SEP_LIMIT;
/* Methods */
private __construct()
public static createCharacterInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static createCodePointInstance(): IntlCodePointBreakIterator
public static createLineInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static createSentenceInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static createTitleInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static createWordInstance(?string `$locale` = `null`): ?IntlBreakIterator
public current(): int
public first(): int
public following(int `$offset`): int
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int `$type`): string|false
public getPartsIterator(string `$type` = `IntlPartsIterator::KEY_SEQUENTIAL`): IntlPartsIterator
public getText(): ?string
public isBoundary(int `$offset`): bool
public last(): int
public next(?int `$offset` = `null`): int
public preceding(int `$offset`): int
public previous(): int
public setText(string `$text`): bool
}

## Predefined Constants

`IntlBreakIterator::DONE` int

`IntlBreakIterator::WORD_NONE` int

`IntlBreakIterator::WORD_NONE_LIMIT` int

`IntlBreakIterator::WORD_NUMBER` int

`IntlBreakIterator::WORD_NUMBER_LIMIT` int

`IntlBreakIterator::WORD_LETTER` int

`IntlBreakIterator::WORD_LETTER_LIMIT` int

`IntlBreakIterator::WORD_KANA` int

`IntlBreakIterator::WORD_KANA_LIMIT` int

`IntlBreakIterator::WORD_IDEO` int

`IntlBreakIterator::WORD_IDEO_LIMIT` int

`IntlBreakIterator::LINE_SOFT` int

`IntlBreakIterator::LINE_SOFT_LIMIT` int

`IntlBreakIterator::LINE_HARD` int

`IntlBreakIterator::LINE_HARD_LIMIT` int

`IntlBreakIterator::SENTENCE_TERM` int

`IntlBreakIterator::SENTENCE_TERM_LIMIT` int

`IntlBreakIterator::SENTENCE_SEP` int

`IntlBreakIterator::SENTENCE_SEP_LIMIT` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.
8.0.0 | IntlBreakIterator implements IteratorAggregate now. Previously, Traversable was implemented instead.

# IntlBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::__construct — Private constructor for disallowing instantiation

### Description

private IntlBreakIterator::__construct()

IntlBreakIterator instances should be created by using one of the static factory methods.

### Parameters

This function has no parameters.

### Return Values

### See Also

- IntlBreakIterator::createCharacterInstance() - Create break iterator for boundaries of combining character sequences
- IntlBreakIterator::createCodePointInstance() - Create break iterator for boundaries of code points
- IntlBreakIterator::createLineInstance() - Create break iterator for logically possible line breaks
- IntlBreakIterator::createSentenceInstance() - Create break iterator for sentence breaks
- IntlBreakIterator::createTitleInstance() - Create break iterator for title-casing breaks
- IntlBreakIterator::createWordInstance() - Create break iterator for word breaks

# IntlBreakIterator::createCharacterInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences

### Description

public static IntlBreakIterator::createCharacterInstance(?string `$locale` = `null`): ?IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locale`

### Return Values

# IntlBreakIterator::createCodePointInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points

### Description

public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::createLineInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks

### Description

public static IntlBreakIterator::createLineInstance(?string `$locale` = `null`): ?IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locale`

### Return Values

# IntlBreakIterator::createSentenceInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks

### Description

public static IntlBreakIterator::createSentenceInstance(?string `$locale` = `null`): ?IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locale`

### Return Values

# IntlBreakIterator::createTitleInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks

### Description

public static IntlBreakIterator::createTitleInstance(?string `$locale` = `null`): ?IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locale`

### Return Values

# IntlBreakIterator::createWordInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createWordInstance — Create break iterator for word breaks

### Description

public static IntlBreakIterator::createWordInstance(?string `$locale` = `null`): ?IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`locale`

### Return Values

# IntlBreakIterator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::current — Get index of current position

### Description

public IntlBreakIterator::current(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::first

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::first — Set position to the first character in the text

### Description

public IntlBreakIterator::first(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::following

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset

### Description

public IntlBreakIterator::following(int `$offset`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`offset`

### Return Values

# IntlBreakIterator::getErrorCode

# intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getErrorCode -- intl_get_error_code — Get last error code on the object

### Description

Object-oriented style (method):

public IntlBreakIterator::getErrorCode(): int

Procedural style:

intl_get_error_code(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::getErrorMessage

# intl_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getErrorMessage -- intl_get_error_message — Get last error message on the object

### Description

Object-oriented style (method):

public IntlBreakIterator::getErrorMessage(): string

Procedural style:

intl_get_error_message(): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::getLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getLocale — Get the locale associated with the object

### Description

public IntlBreakIterator::getLocale(int `$type`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`type`

### Return Values

# IntlBreakIterator::getPartsIterator

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries

### Description

public IntlBreakIterator::getPartsIterator(string `$type` = `IntlPartsIterator::KEY_SEQUENTIAL`): IntlPartsIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`type`

  Optional key type. Possible values are:

  - `IntlPartsIterator::KEY_SEQUENTIAL` - The default. Sequentially increasing integers used as key.
  - `IntlPartsIterator::KEY_LEFT` - Byte offset left of current part used as key.
  - `IntlPartsIterator::KEY_RIGHT` - Byte offset right of current part used as key.

### Return Values

# IntlBreakIterator::getText

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getText — Get the text being scanned

### Description

public IntlBreakIterator::getText(): ?string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::isBoundary

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset

### Description

public IntlBreakIterator::isBoundary(int `$offset`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`offset`

### Return Values

# IntlBreakIterator::last

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::last — Set the iterator position to index beyond the last character

### Description

public IntlBreakIterator::last(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::next — Advance the iterator the next boundary

### Description

public IntlBreakIterator::next(?int `$offset` = `null`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`offset`

### Return Values

# IntlBreakIterator::preceding

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset

### Description

public IntlBreakIterator::preceding(int `$offset`): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`offset`

### Return Values

# IntlBreakIterator::previous

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current

### Description

public IntlBreakIterator::previous(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlBreakIterator::setText

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::setText — Set the text being scanned

### Description

public IntlBreakIterator::setText(string `$text`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`text`

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | This method now returns `false` on failure; previously it returns `null`.

## Table of Contents

- IntlBreakIterator::__construct — Private constructor for disallowing instantiation
- IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
- IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
- IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
- IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
- IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
- IntlBreakIterator::createWordInstance — Create break iterator for word breaks
- IntlBreakIterator::current — Get index of current position
- IntlBreakIterator::first — Set position to the first character in the text
- IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
- IntlBreakIterator::getErrorCode — Get last error code on the object
- IntlBreakIterator::getErrorMessage — Get last error message on the object
- IntlBreakIterator::getLocale — Get the locale associated with the object
- IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
- IntlBreakIterator::getText — Get the text being scanned
- IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset
- IntlBreakIterator::last — Set the iterator position to index beyond the last character
- IntlBreakIterator::next — Advance the iterator the next boundary
- IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
- IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
- IntlBreakIterator::setText — Set the text being scanned

# The IntlRuleBasedBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

A subclass of IntlBreakIterator that encapsulates ICU break iterators whose behavior is specified using a set of rules. This is the most common kind of break iterators.

These rules are described in the » ICU Boundary Analysis User Guide.

## Class synopsis

class IntlRuleBasedBreakIterator extends IntlBreakIterator {
/* Inherited constants */
public const int IntlBreakIterator::DONE;
public const int IntlBreakIterator::WORD_NONE;
public const int IntlBreakIterator::WORD_NONE_LIMIT;
public const int IntlBreakIterator::WORD_NUMBER;
public const int IntlBreakIterator::WORD_NUMBER_LIMIT;
public const int IntlBreakIterator::WORD_LETTER;
public const int IntlBreakIterator::WORD_LETTER_LIMIT;
public const int IntlBreakIterator::WORD_KANA;
public const int IntlBreakIterator::WORD_KANA_LIMIT;
public const int IntlBreakIterator::WORD_IDEO;
public const int IntlBreakIterator::WORD_IDEO_LIMIT;
public const int IntlBreakIterator::LINE_SOFT;
public const int IntlBreakIterator::LINE_SOFT_LIMIT;
public const int IntlBreakIterator::LINE_HARD;
public const int IntlBreakIterator::LINE_HARD_LIMIT;
public const int IntlBreakIterator::SENTENCE_TERM;
public const int IntlBreakIterator::SENTENCE_TERM_LIMIT;
public const int IntlBreakIterator::SENTENCE_SEP;
public const int IntlBreakIterator::SENTENCE_SEP_LIMIT;
/* Methods */
public __construct(string `$rules`, bool `$compiled` = `false`)
public getBinaryRules(): string|false
public getRules(): string|false
public getRuleStatus(): int
public getRuleStatusVec(): array|false
/* Inherited methods */
public static IntlBreakIterator::createCharacterInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator
public static IntlBreakIterator::createLineInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createTitleInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createWordInstance(?string `$locale` = `null`): ?IntlBreakIterator
public IntlBreakIterator::current(): int
public IntlBreakIterator::first(): int
public IntlBreakIterator::following(int `$offset`): int
public IntlBreakIterator::getErrorCode(): int
public IntlBreakIterator::getErrorMessage(): string
public IntlBreakIterator::getLocale(int `$type`): string|false
public IntlBreakIterator::getPartsIterator(string `$type` = `IntlPartsIterator::KEY_SEQUENTIAL`): IntlPartsIterator
public IntlBreakIterator::getText(): ?string
public IntlBreakIterator::isBoundary(int `$offset`): bool
public IntlBreakIterator::last(): int
public IntlBreakIterator::next(?int `$offset` = `null`): int
public IntlBreakIterator::preceding(int `$offset`): int
public IntlBreakIterator::previous(): int
public IntlBreakIterator::setText(string `$text`): bool
}

# IntlRuleBasedBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset

### Description

public IntlRuleBasedBreakIterator::__construct(string `$rules`, bool `$compiled` = `false`)

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`rules`

`compiled`

### Return Values

# IntlRuleBasedBreakIterator::getBinaryRules

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules

### Description

public IntlRuleBasedBreakIterator::getBinaryRules(): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlRuleBasedBreakIterator::getRules

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object

### Description

public IntlRuleBasedBreakIterator::getRules(): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlRuleBasedBreakIterator::getRuleStatus

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position

### Description

public IntlRuleBasedBreakIterator::getRuleStatus(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlRuleBasedBreakIterator::getRuleStatusVec

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

### Description

public IntlRuleBasedBreakIterator::getRuleStatusVec(): array|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
- IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
- IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
- IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
- IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

# The IntlCodePointBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

This break iterator identifies the boundaries between UTF-8 code points.

## Class synopsis

class IntlCodePointBreakIterator extends IntlBreakIterator {
/* Inherited constants */
public const int IntlBreakIterator::DONE;
public const int IntlBreakIterator::WORD_NONE;
public const int IntlBreakIterator::WORD_NONE_LIMIT;
public const int IntlBreakIterator::WORD_NUMBER;
public const int IntlBreakIterator::WORD_NUMBER_LIMIT;
public const int IntlBreakIterator::WORD_LETTER;
public const int IntlBreakIterator::WORD_LETTER_LIMIT;
public const int IntlBreakIterator::WORD_KANA;
public const int IntlBreakIterator::WORD_KANA_LIMIT;
public const int IntlBreakIterator::WORD_IDEO;
public const int IntlBreakIterator::WORD_IDEO_LIMIT;
public const int IntlBreakIterator::LINE_SOFT;
public const int IntlBreakIterator::LINE_SOFT_LIMIT;
public const int IntlBreakIterator::LINE_HARD;
public const int IntlBreakIterator::LINE_HARD_LIMIT;
public const int IntlBreakIterator::SENTENCE_TERM;
public const int IntlBreakIterator::SENTENCE_TERM_LIMIT;
public const int IntlBreakIterator::SENTENCE_SEP;
public const int IntlBreakIterator::SENTENCE_SEP_LIMIT;
/* Methods */
public getLastCodePoint(): int
/* Inherited methods */
public static IntlBreakIterator::createCharacterInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator
public static IntlBreakIterator::createLineInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createTitleInstance(?string `$locale` = `null`): ?IntlBreakIterator
public static IntlBreakIterator::createWordInstance(?string `$locale` = `null`): ?IntlBreakIterator
public IntlBreakIterator::current(): int
public IntlBreakIterator::first(): int
public IntlBreakIterator::following(int `$offset`): int
public IntlBreakIterator::getErrorCode(): int
public IntlBreakIterator::getErrorMessage(): string
public IntlBreakIterator::getLocale(int `$type`): string|false
public IntlBreakIterator::getPartsIterator(string `$type` = `IntlPartsIterator::KEY_SEQUENTIAL`): IntlPartsIterator
public IntlBreakIterator::getText(): ?string
public IntlBreakIterator::isBoundary(int `$offset`): bool
public IntlBreakIterator::last(): int
public IntlBreakIterator::next(?int `$offset` = `null`): int
public IntlBreakIterator::preceding(int `$offset`): int
public IntlBreakIterator::previous(): int
public IntlBreakIterator::setText(string `$text`): bool
}

# IntlCodePointBreakIterator::getLastCodePoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

### Description

public IntlCodePointBreakIterator::getLastCodePoint(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

# The IntlDatePatternGenerator class

(PHP 8 >= 8.1.0)

## Introduction

Generates localized date and/or time format pattern strings suitable for use in IntlDateFormatter.

## Class synopsis

class IntlDatePatternGenerator {
/* Methods */
public __construct(?string `$locale` = `null`)
public static create(?string `$locale` = `null`): ?IntlDatePatternGenerator
public getBestPattern(string `$skeleton`): string|false
}

# IntlDatePatternGenerator::create

# IntlDatePatternGenerator::__construct

(PHP 8 >= 8.1.0)

IntlDatePatternGenerator::create -- IntlDatePatternGenerator::__construct — Creates a new IntlDatePatternGenerator instance

### Description

public static IntlDatePatternGenerator::create(?string `$locale` = `null`): ?IntlDatePatternGenerator
public IntlDatePatternGenerator::__construct(?string `$locale` = `null`)

Creates a new IntlDatePatternGenerator instance.

### Parameters

`locale`

  The locale. If `null` is passed, uses the ini setting intl.default_locale.

### Return Values

Returns an IntlDatePatternGenerator instance on success, or `null` on failure.

# IntlDatePatternGenerator::getBestPattern

(PHP 8 >= 8.1.0)

IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format

### Description

public IntlDatePatternGenerator::getBestPattern(string `$skeleton`): string|false

Determines which date/time format is most suitable for a particular locale.

### Parameters

`skeleton`

  The skeleton.

### Return Values

Returns a format, accepted by DateTimeInterface::format() on success, or `false` on failure.

### Examples

Example #1 IntlDatePatternGenerator::getBestPattern() example

`<?php
$skeleton = 'YYYYMMdd';
$today = \DateTimeImmutable::createFromFormat('Y-m-d', '2021-04-24');
$patternGenerator = new \IntlDatePatternGenerator('de_DE');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'de: ', \IntlDateFormatter::formatObject($today, $pattern, 'de_DE'), "\n";
$patternGenerator = new \IntlDatePatternGenerator('en_US');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'en: ', \IntlDateFormatter::formatObject($today, $pattern, 'en_US');
?>`

The above example will output:

    de: 24.04.2021
    en: 04/24/2021

## Table of Contents

- IntlDatePatternGenerator::create — Creates a new IntlDatePatternGenerator instance
- IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format

# The IntlPartsIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

Objects of this class can be obtained from IntlBreakIterator objects. While the break iterators provide a sequence of boundary positions when iterated, IntlPartsIterator objects provide, as a convenience, the text fragments comprehended between two successive boundaries.

The keys may represent the offset of the left boundary, right boundary, or they may just the sequence of non-negative integers. See IntlBreakIterator::getPartsIterator().

## Class synopsis

class IntlPartsIterator extends IntlIterator {
/* Constants */
public const int KEY_SEQUENTIAL;
public const int KEY_LEFT;
public const int KEY_RIGHT;
/* Methods */
public getBreakIterator(): IntlBreakIterator
/* Inherited methods */
public IntlIterator::current(): mixed
public IntlIterator::key(): mixed
public IntlIterator::next(): void
public IntlIterator::rewind(): void
public IntlIterator::valid(): bool
}

## Predefined Constants

`IntlPartsIterator::KEY_SEQUENTIAL` int

`IntlPartsIterator::KEY_LEFT` int

`IntlPartsIterator::KEY_RIGHT` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# IntlPartsIterator::getBreakIterator

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

### Description

public IntlPartsIterator::getBreakIterator(): IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

# The UConverter class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

## Introduction

## Class synopsis

class UConverter {
/* Constants */
public const int REASON_UNASSIGNED;
public const int REASON_ILLEGAL;
public const int REASON_IRREGULAR;
public const int REASON_RESET;
public const int REASON_CLOSE;
public const int REASON_CLONE;
public const int UNSUPPORTED_CONVERTER;
public const int SBCS;
public const int DBCS;
public const int MBCS;
public const int LATIN_1;
public const int UTF8;
public const int UTF16_BigEndian;
public const int UTF16_LittleEndian;
public const int UTF32_BigEndian;
public const int UTF32_LittleEndian;
public const int EBCDIC_STATEFUL;
public const int ISO_2022;
public const int LMBCS_1;
public const int LMBCS_2;
public const int LMBCS_3;
public const int LMBCS_4;
public const int LMBCS_5;
public const int LMBCS_6;
public const int LMBCS_8;
public const int LMBCS_11;
public const int LMBCS_16;
public const int LMBCS_17;
public const int LMBCS_18;
public const int LMBCS_19;
public const int LMBCS_LAST;
public const int HZ;
public const int SCSU;
public const int ISCII;
public const int US_ASCII;
public const int UTF7;
public const int BOCU1;
public const int UTF16;
public const int UTF32;
public const int CESU8;
public const int IMAP_MAILBOX;
/* Methods */
public __construct(?string `$destination_encoding` = `null`, ?string `$source_encoding` = `null`)
public convert(string `$str`, bool `$reverse` = `false`): string|false
public fromUCallback(
int `$reason`,
array `$source`,
int `$codePoint`,
int `&$error`
): string|int|array|null
public static getAliases(string `$name`): array|false|null
public static getAvailable(): array
public getDestinationEncoding(): string|false|null
public getDestinationType(): int|false|null
public getErrorCode(): int
public getErrorMessage(): ?string
public getSourceEncoding(): string|false|null
public getSourceType(): int|false|null
public static getStandards(): ?array
public getSubstChars(): string|false|null
public static reasonText(int `$reason`): string
public setDestinationEncoding(string `$encoding`): bool
public setSourceEncoding(string `$encoding`): bool
public setSubstChars(string `$chars`): bool
public toUCallback(
int `$reason`,
string `$source`,
string `$codeUnits`,
int `&$error`
): string|int|array|null
public static transcode(
string `$str`,
string `$toEncoding`,
string `$fromEncoding`,
?array `$options` = `null`
): string|false
}

## Predefined Constants

`UConverter::REASON_UNASSIGNED` int

`UConverter::REASON_ILLEGAL` int

`UConverter::REASON_IRREGULAR` int

`UConverter::REASON_RESET` int

`UConverter::REASON_CLOSE` int

`UConverter::REASON_CLONE` int

`UConverter::UNSUPPORTED_CONVERTER` int

`UConverter::SBCS` int

`UConverter::DBCS` int

`UConverter::MBCS` int

`UConverter::LATIN_1` int

`UConverter::UTF8` int

`UConverter::UTF16_BigEndian` int

`UConverter::UTF16_LittleEndian` int

`UConverter::UTF32_BigEndian` int

`UConverter::UTF32_LittleEndian` int

`UConverter::EBCDIC_STATEFUL` int

`UConverter::ISO_2022` int

`UConverter::LMBCS_1` int

`UConverter::LMBCS_2` int

`UConverter::LMBCS_3` int

`UConverter::LMBCS_4` int

`UConverter::LMBCS_5` int

`UConverter::LMBCS_6` int

`UConverter::LMBCS_8` int

`UConverter::LMBCS_11` int

`UConverter::LMBCS_16` int

`UConverter::LMBCS_17` int

`UConverter::LMBCS_18` int

`UConverter::LMBCS_19` int

`UConverter::LMBCS_LAST` int

`UConverter::HZ` int

`UConverter::SCSU` int

`UConverter::ISCII` int

`UConverter::US_ASCII` int

`UConverter::UTF7` int

`UConverter::BOCU1` int

`UConverter::UTF16` int

`UConverter::UTF32` int

`UConverter::CESU8` int

`UConverter::IMAP_MAILBOX` int

## Changelog

Version | Description
--- | ---
8.4.0 | The class constants are now typed.

# UConverter::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::__construct — Create UConverter object

### Description

public UConverter::__construct(?string `$destination_encoding` = `null`, ?string `$source_encoding` = `null`)

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`destination_encoding`

`source_encoding`

### Return Values

# UConverter::convert

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::convert — Convert string from one charset to another

### Description

public UConverter::convert(string `$str`, bool `$reverse` = `false`): string|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`str`

`reverse`

### Return Values

# UConverter::fromUCallback

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::fromUCallback — Default "from" callback function

### Description

public UConverter::fromUCallback(
int `$reason`,
array `$source`,
int `$codePoint`,
int `&$error`
): string|int|array|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`reason`

`source`

`codePoint`

`error`

### Return Values

# UConverter::getAliases

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getAliases — Get the aliases of the given name

### Description

public static UConverter::getAliases(string `$name`): array|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`name`

### Return Values

# UConverter::getAvailable

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getAvailable — Get the available canonical converter names

### Description

public static UConverter::getAvailable(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getDestinationEncoding — Get the destination encoding

### Description

public UConverter::getDestinationEncoding(): string|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getDestinationType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getDestinationType — Get the destination converter type

### Description

public UConverter::getDestinationType(): int|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getErrorCode

# intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getErrorCode -- intl_get_error_code — Get last error code on the object

### Description

public UConverter::getErrorCode(): int

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getErrorMessage

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getErrorMessage — Get last error message on the object

### Description

public UConverter::getErrorMessage(): ?string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSourceEncoding — Get the source encoding

### Description

public UConverter::getSourceEncoding(): string|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getSourceType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSourceType — Get the source converter type

### Description

public UConverter::getSourceType(): int|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getStandards

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getStandards — Get standards associated to converter names

### Description

public static UConverter::getStandards(): ?array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::getSubstChars

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSubstChars — Get substitution chars

### Description

public UConverter::getSubstChars(): string|false|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# UConverter::reasonText

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::reasonText — Get string representation of the callback reason

### Description

public static UConverter::reasonText(int `$reason`): string

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`reason`

### Return Values

# UConverter::setDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setDestinationEncoding — Set the destination encoding

### Description

public UConverter::setDestinationEncoding(string `$encoding`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`encoding`

### Return Values

# UConverter::setSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setSourceEncoding — Set the source encoding

### Description

public UConverter::setSourceEncoding(string `$encoding`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`encoding`

### Return Values

# UConverter::setSubstChars

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setSubstChars — Set the substitution chars

### Description

public UConverter::setSubstChars(string `$chars`): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`chars`

### Return Values

# UConverter::toUCallback

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::toUCallback — Default "to" callback function

### Description

public UConverter::toUCallback(
int `$reason`,
string `$source`,
string `$codeUnits`,
int `&$error`
): string|int|array|null

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`reason`

`source`

`codeUnits`

`error`

### Return Values

# UConverter::transcode

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::transcode — Convert a string from one character encoding to another

### Description

public static UConverter::transcode(
string `$str`,
string `$toEncoding`,
string `$fromEncoding`,
?array `$options` = `null`
): string|false

Converts `str` from `fromEncoding` to `toEncoding`.

### Parameters

`str`

  The string to be converted.

`toEncoding`

  The desired encoding of the result.

`fromEncoding`

  The current encoding used to interpret `str`.

`options`

  An optional array, which may contain the following keys:

  - `'to_subst'` - the substitution character to use in place of any character of `str` which cannot be encoded in `toEncoding`. If specified, it must represent a single character in the target encoding.

### Return Values

Returns the converted string or `false` on failure.

### Examples

Example #1 Converting from UTF-8 to UTF-16 and back

`<?php
$utf8_string = "\x5A\x6F\xC3\xAB"; // 'Zoë' in UTF-8
$utf16_string = UConverter::transcode($utf8_string, 'UTF-16BE', 'UTF-8');
echo bin2hex($utf16_string), "\n";
$new_utf8_string = UConverter::transcode($utf16_string, 'UTF-8', 'UTF-16BE');
echo bin2hex($new_utf8_string), "\n";
?>`

The above example will output:

    005a006f00eb
    5a6fc3ab

Example #2 Invalid characters in input

If the input string contains a sequence of bytes which is not valid in the encoding specified by `fromEncoding`, they are replaced by Unicode code point U+FFFD (Replacement Character) before converting to `toEncoding`.

`<?php
$invalid_utf8_string = "\xC3"; // incomplete multi-byte UTF-8 sequence
$utf16_string = UConverter::transcode($invalid_utf8_string, 'UTF-16BE', 'UTF-8');
echo bin2hex($utf16_string), "\n";
?>`

The above example will output:

    fffd

Example #3 Characters which cannot be encoded

If the input string contains characters which cannot be represented in `toEncoding`, they are replaced with a single character. The default character to use depends on the encoding, and can be controlled using the `'to_subst'` option.

`<?php
$utf8_string = "\xE2\x82\xAC"; // € (Euro Sign) does not exist in ISO 8859-1
// Default replacement in ISO 8859-1 is "\x1A" (Substitute)
$iso8859_1_string = UConverter::transcode($utf8_string, 'ISO-8859-1', 'UTF-8');
echo bin2hex($iso8859_1_string), "\n";
// Specify a replacement of '?' ("\x3F") instead
$iso8859_1_string = UConverter::transcode(
$utf8_string, 'ISO-8859-1', 'UTF-8', ['to_subst' => '?']
);
echo bin2hex($iso8859_1_string), "\n";
// Since ISO 8859-1 cannot map U+FFFD, invalid input is also replaced by to_subst
$invalid_utf8_string = "\xC3"; // incomplete multi-byte UTF-8 sequence
$iso8859_1_string = UConverter::transcode(
$invalid_utf8_string, 'ISO-8859-1', 'UTF-8', ['to_subst' => '?']
);
echo bin2hex($iso8859_1_string), "\n";
?>`

The above example will output:

    1a
    3f
    3f

### See Also

- mb_convert_encoding() - Convert a string from one character encoding to another
- iconv() - Convert a string from one character encoding to another

## Table of Contents

- UConverter::__construct — Create UConverter object
- UConverter::convert — Convert string from one charset to another
- UConverter::fromUCallback — Default "from" callback function
- UConverter::getAliases — Get the aliases of the given name
- UConverter::getAvailable — Get the available canonical converter names
- UConverter::getDestinationEncoding — Get the destination encoding
- UConverter::getDestinationType — Get the destination converter type
- UConverter::getErrorCode — Get last error code on the object
- UConverter::getErrorMessage — Get last error message on the object
- UConverter::getSourceEncoding — Get the source encoding
- UConverter::getSourceType — Get the source converter type
- UConverter::getStandards — Get standards associated to converter names
- UConverter::getSubstChars — Get substitution chars
- UConverter::reasonText — Get string representation of the callback reason
- UConverter::setDestinationEncoding — Set the destination encoding
- UConverter::setSourceEncoding — Set the source encoding
- UConverter::setSubstChars — Set the substitution chars
- UConverter::toUCallback — Default "to" callback function
- UConverter::transcode — Convert a string from one character encoding to another

# Grapheme Functions

# grapheme_extract

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

### Description

Procedural style

grapheme_extract(
string `$haystack`,
int `$size`,
int `$type` = `GRAPHEME_EXTR_COUNT`,
int `$offset` = 0,
int `&$next` = `null`
): string|false

Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

### Parameters

`haystack`

  String to search.

`size`

  Maximum number items - based on the `type` - to return.

`type`

  Defines the type of units referred to by the `size` parameter:

  - GRAPHEME_EXTR_COUNT (default) -`size` is the number of default grapheme clusters to extract.
  - GRAPHEME_EXTR_MAXBYTES -`size` is the maximum number of bytes returned.
  - GRAPHEME_EXTR_MAXCHARS - `size` is the maximum number of UTF-8 characters returned.
`offset`

  Starting position in `haystack` in bytes - if given, it must be zero or a positive value that is less than or equal to the length of `haystack` in bytes, or a negative value that counts from the end of `haystack`. If `offset` does not point to the first byte of a UTF-8 character, the start position is moved to the next character boundary.

`next`

  Reference to a value that will be set to the next starting position. When the call returns, this may point to the first byte position past the end of the string.

### Return Values

A string starting at offset `offset` and ending on a default grapheme cluster boundary that conforms to the `size` and `type` specified, or `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.0 | Support for negative `offset`s has been added.

### Examples

Example #1 grapheme_extract() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print urlencode(grapheme_extract( $char_a_ring_nfd . $char_o_diaeresis_nfd, 1, GRAPHEME_EXTR_COUNT, 2));
?>`

The above example will output:

    o%CC%88

### See Also

- grapheme_substr() - Return part of a string
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_str_split

(PHP 8 >= 8.4.0)

grapheme_str_split — Split a string into an array

### Description

grapheme_str_split(string `$string`, int `$length` = 1): array|false

This function will return an array of strings, it is a version of str_split() with support for grapheme cluster byte characters. If the `length` parameter is specified, the string is broken down into chunks of the specified length in grapheme clusters (not bytes).

### Parameters

`string`

  The string to split into grapheme clusters or chunks. `string` must be valid UTF-8.

`length`

  Each element of the returned array will be composed of `length` grapheme clusters.

### Return Values

grapheme_str_split() returns an array of strings, or `false` on failure.

### Errors/Exceptions

If `length` is less than `1`, a ValueError will be thrown.

### See Also

- str_split() - Convert a string to an array
- mb_str_split() - Given a multibyte string, return an array of its characters
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_stripos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

### Description

Procedural style

grapheme_stripos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
string `$locale` = ""
): int|false

Find position (in grapheme units) of first occurrence of a case-insensitive string

### Parameters

`haystack`

  The string to look in. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`offset`

  The optional `offset` parameter allows you to specify where in `haystack` to start searching as an offset in grapheme units (not bytes or characters). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of `haystack` regardless of the value of `offset`.

`locale`
  Locale to use.

### Return Values

Returns the position as an integer. If `needle` is not found, grapheme_stripos() will return `false`.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.
7.1.0 | Support for negative `offset`s has been added.

### Examples

Example #1 grapheme_stripos() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"
print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);
?>`

The above example will output:

    2

### See Also

- grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
- grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
- grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_stristr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

### Description

Procedural style

grapheme_stristr(
string `$haystack`,
string `$needle`,
bool `$beforeNeedle` = `false`,
string `$locale` = ""
): string|false

Returns part of `haystack` string starting from and including the first occurrence of case-insensitive needle to the end of `haystack`.

### Parameters

`haystack`

  The input string. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`beforeNeedle`

  If `true`, grapheme_stristr() returns the part of the `haystack` before the first occurrence of the needle (excluding `needle`).

`locale`
  Locale to use.

### Return Values

Returns the portion of `haystack`, or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.

### Examples

Example #1 grapheme_stristr() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"
print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_O_diaeresis_nfd));
?>`

The above example will output:

    o%CC%88a%CC%8A

### See Also

- grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
- grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
- grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_strlen

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

### Description

Procedural style

grapheme_strlen(string `$string`): int|false|null

Get string length in grapheme units (not bytes or characters)

### Parameters

`string`

  The string being measured for length. It must be a valid UTF-8 string.

### Return Values

The length of the string on success, or `false` on failure.

### Examples

Example #1 grapheme_strlen() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);
?>`

The above example will output:

    6

### See Also

- » Unicode Text Segmentation: Grapheme Cluster Boundaries
- iconv_strlen() - Returns the character count of string
- mb_strlen() - Get string length
- strlen() - Get string length

# grapheme_strpos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

### Description

Procedural style

grapheme_strpos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
string `$locale` = ""
): int|false

Find position (in grapheme units) of first occurrence of a string

### Parameters

`haystack`

  The string to look in. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`offset`

  The optional `offset` parameter allows you to specify where in `haystack` to start searching as an offset in grapheme units (not bytes or characters). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of `haystack` regardless of the value of `offset`.

`locale`
  Locale to use.

### Return Values

Returns the position as an integer. If `needle` is not found, grapheme_strpos() will return `false`.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.
7.1.0 | Support for negative `offset`s has been added.

### Examples

Example #1 grapheme_strpos() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print grapheme_strpos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);
?>`

The above example will output:

    2

### See Also

- grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
- grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_strripos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

### Description

Procedural style

grapheme_strripos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
string `$locale` = ""
): int|false

Find position (in grapheme units) of last occurrence of a case-insensitive string

### Parameters

`haystack`

  The string to look in. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`offset`

  The optional `offset` parameter allows you to specify where in `haystack` to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of `haystack` regardless of the value of `offset`.

`locale`
  Locale to use.

### Return Values

Returns the position as an integer. If `needle` is not found, grapheme_strripos() will return `false`.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.

### Examples

Example #1 grapheme_strripos() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"
print grapheme_strripos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);
?>`

The above example will output:

    2

### See Also

- grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
- grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
- grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_strrpos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

### Description

Procedural style

grapheme_strrpos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
string `$locale` = ""
): int|false

Find position (in grapheme units) of last occurrence of a string

### Parameters

`haystack`

  The string to look in. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`offset`

  The optional `offset` parameter allows you to specify where in `haystack` to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of `haystack` regardless of the value of `offset`.

`locale`
  Locale to use.

### Return Values

Returns the position as an integer. If `needle` is not found, grapheme_strrpos() will return `false`.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.

### Examples

Example #1 grapheme_strrpos() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print grapheme_strrpos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);
?>`

The above example will output:

    2

### See Also

- grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
- grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_strstr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack

### Description

Procedural style

grapheme_strstr(
string `$haystack`,
string `$needle`,
bool `$beforeNeedle` = `false`,
string `$locale` = ""
): string|false

Returns part of haystack string from the first occurrence of needle to the end of haystack (including the needle).

### Parameters

`haystack`

  The input string. Must be valid UTF-8.

`needle`

  The string to look for. Must be valid UTF-8.

`beforeNeedle`

  If `true`, grapheme_strstr() returns the part of the `haystack` before the first occurrence of the `needle` (excluding the `needle`).

`locale`
  Locale to use.

### Return Values

Returns the portion of `haystack`, or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.

### Examples

Example #1 grapheme_strstr() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd));
?>`

The above example will output:

    o%CC%88a%CC%8A

### See Also

- grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
- grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

# grapheme_substr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

### Description

Procedural style

grapheme_substr(
string `$string`,
int `$offset`,
?int `$length` = `null`,
string `$locale` = ""
): string|false

Return part of a string

### Parameters

`string`

  The input string. Must be valid UTF-8.

`offset`

  Start position in default grapheme units. If `offset` is non-negative, the returned string will start at the `offset`'th position in `string`, counting from zero. If `offset` is negative, the returned string will start at the `offset`'th grapheme unit from the end of string.

`length`

  Length in grapheme units. If `length` is given and is positive, the string returned will contain at most `length` grapheme units beginning from `offset` (depending on the length of string). If `length` is given and is negative, then that many grapheme units will be omitted from the end of string (after the start position has been calculated when `offset` is negative). If `offset` denotes a position beyond this truncation, an empty string will be returned.

`locale`
  Locale to use.

### Return Values

Returns the extracted part of `string`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.5.0 | The optional parameter `locale` has been added.
8.0.0 | The function now consistently clamps out-of-bounds offsets to the string boundary. Previously, `false` was returned instead of the empty string in some cases.

### Examples

Example #1 grapheme_substr() example

`<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
print urlencode(grapheme_substr( "ao" . $char_a_ring_nfd . "bc" . $char_o_diaeresis_nfd . "O", 2, -1 ));
?>`

The above example will output:

    a%CC%8Abco%CC%88

### See Also

- grapheme_extract() - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
- » Unicode Text Segmentation: Grapheme Cluster Boundaries

## Table of Contents

- grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
- grapheme_str_split — Split a string into an array
- grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
- grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
- grapheme_strlen — Get string length in grapheme units
- grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
- grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
- grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
- grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack
- grapheme_substr — Return part of a string

# IDN Functions

# idn_to_ascii

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_ascii — Convert domain name to IDNA ASCII form

### Description

Procedural style

idn_to_ascii(
string `$domain`,
int `$flags` = `IDNA_DEFAULT`,
int `$variant` = `INTL_IDNA_VARIANT_UTS46`,
array `&$idna_info` = `null`
): string|false

This function converts a Unicode domain name to an IDNA ASCII-compatible format in lowercase.

### Parameters

`domain`

  The domain to convert, which must be UTF-8 encoded.

`flags`

  Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

`variant`

  Either `INTL_IDNA_VARIANT_2003` (deprecated as of PHP 7.2.0) for IDNA 2003 or `INTL_IDNA_VARIANT_UTS46` (only available as of ICU 4.6) for UTS #46.

`idna_info`

  This parameter can be used only if `INTL_IDNA_VARIANT_UTS46` was used for `variant`. In that case, it will be filled with an array with the keys `'result'`, the possibly illegal result of the transformation, `'isTransitionalDifferent'`, a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and `'errors'`, which is an int representing a bitset of the error constants IDNA_ERROR_*.

### Return Values

The domain name encoded in ASCII-compatible form, or `false` on failure

### Changelog

Version | Description
--- | ---
7.4.0 | The default value of `variant` is now `INTL_IDNA_VARIANT_UTS46` instead of the deprecated `INTL_IDNA_VARIANT_2003`.
7.2.0 | `INTL_IDNA_VARIANT_2003` has been deprecated; use `INTL_IDNA_VARIANT_UTS46` instead.

### Examples

Example #1 idn_to_ascii() example

`<?php
echo idn_to_ascii('täst.de');
?>`

The above example will output:

    xn--tst-qla.de

Example #2 All-ASCII domain names are just converted to lowercase

`<?php
var_dump(idn_to_ascii('Example.com'));
?>`

The above example will output:

    string(11) "example.com"

### See Also

- idn_to_utf8() - Convert domain name from IDNA ASCII to Unicode

# idn_to_utf8

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode

### Description

Procedural style

idn_to_utf8(
string `$domain`,
int `$flags` = `IDNA_DEFAULT`,
int `$variant` = `INTL_IDNA_VARIANT_UTS46`,
array `&$idna_info` = `null`
): string|false

This function converts a Unicode domain name from an IDNA ASCII-compatible format to plain Unicode, encoded in UTF-8.

### Parameters

`domain`

  Domain to convert in an IDNA ASCII-compatible format.

`flags`

  Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

`variant`

  Either `INTL_IDNA_VARIANT_2003` (deprecated as of PHP 7.2.0) for IDNA 2003 or `INTL_IDNA_VARIANT_UTS46` (only available as of ICU 4.6) for UTS #46.

`idna_info`

  This parameter can be used only if `INTL_IDNA_VARIANT_UTS46` was used for `variant`. In that case, it will be filled with an array with the keys `'result'`, the possibly illegal result of the transformation, `'isTransitionalDifferent'`, a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and `'errors'`, which is an int representing a bitset of the error constants IDNA_ERROR_*.

### Return Values

The domain name in Unicode, encoded in UTF-8, or `false` on failure

### Changelog

Version | Description
--- | ---
7.4.0 | The default value of `variant` is now `INTL_IDNA_VARIANT_UTS46` instead of the deprecated `INTL_IDNA_VARIANT_2003`.
7.2.0 | `INTL_IDNA_VARIANT_2003` has been deprecated; use `INTL_IDNA_VARIANT_UTS46` instead.

### Examples

Example #1 idn_to_utf8() example

`<?php
echo idn_to_utf8('xn--tst-qla.de');
?>`

The above example will output:

    täst.de

### See Also

- idn_to_ascii() - Convert domain name to IDNA ASCII form

## Table of Contents

- idn_to_ascii — Convert domain name to IDNA ASCII form
- idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode

# IntlChar

(PHP 7, PHP 8)

## Introduction

IntlChar provides access to a number of utility methods that can be used to access information about Unicode characters.

The methods and constants adhere closely to the names and behavior used by the underlying ICU library.

## Class synopsis

class IntlChar {
/* Constants */
public const string UNICODE_VERSION;
public const int CODEPOINT_MIN;
public const int CODEPOINT_MAX;
public const float NO_NUMERIC_VALUE;
public const int PROPERTY_ALPHABETIC;
public const int PROPERTY_BINARY_START;
public const int PROPERTY_ASCII_HEX_DIGIT;
public const int PROPERTY_BIDI_CONTROL;
public const int PROPERTY_BIDI_MIRRORED;
public const int PROPERTY_DASH;
public const int PROPERTY_DEFAULT_IGNORABLE_CODE_POINT;
public const int PROPERTY_DEPRECATED;
public const int PROPERTY_DIACRITIC;
public const int PROPERTY_EXTENDER;
public const int PROPERTY_FULL_COMPOSITION_EXCLUSION;
public const int PROPERTY_GRAPHEME_BASE;
public const int PROPERTY_GRAPHEME_EXTEND;
public const int PROPERTY_GRAPHEME_LINK;
public const int PROPERTY_HEX_DIGIT;
public const int PROPERTY_HYPHEN;
public const int PROPERTY_ID_CONTINUE;
public const int PROPERTY_ID_START;
public const int PROPERTY_IDEOGRAPHIC;
public const int PROPERTY_IDS_BINARY_OPERATOR;
public const int PROPERTY_IDS_TRINARY_OPERATOR;
public const int PROPERTY_IDS_UNARY_OPERATOR;
public const int PROPERTY_ID_COMPAT_MATH_START;
public const int PROPERTY_ID_COMPAT_MATH_CONTINUE;
public const int PROPERTY_JOIN_CONTROL;
public const int PROPERTY_LOGICAL_ORDER_EXCEPTION;
public const int PROPERTY_LOWERCASE;
public const int PROPERTY_MATH;
public const int PROPERTY_NONCHARACTER_CODE_POINT;
public const int PROPERTY_QUOTATION_MARK;
public const int PROPERTY_RADICAL;
public const int PROPERTY_SOFT_DOTTED;
public const int PROPERTY_TERMINAL_PUNCTUATION;
public const int PROPERTY_UNIFIED_IDEOGRAPH;
public const int PROPERTY_UPPERCASE;
public const int PROPERTY_WHITE_SPACE;
public const int PROPERTY_XID_CONTINUE;
public const int PROPERTY_XID_START;
public const int PROPERTY_CASE_SENSITIVE;
public const int PROPERTY_S_TERM;
public const int PROPERTY_VARIATION_SELECTOR;
public const int PROPERTY_NFD_INERT;
public const int PROPERTY_NFKD_INERT;
public const int PROPERTY_NFC_INERT;
public const int PROPERTY_NFKC_INERT;
public const int PROPERTY_SEGMENT_STARTER;
public const int PROPERTY_PATTERN_SYNTAX;
public const int PROPERTY_PATTERN_WHITE_SPACE;
public const int PROPERTY_POSIX_ALNUM;
public const int PROPERTY_POSIX_BLANK;
public const int PROPERTY_POSIX_GRAPH;
public const int PROPERTY_POSIX_PRINT;
public const int PROPERTY_POSIX_XDIGIT;
public const int PROPERTY_CASED;
public const int PROPERTY_CASE_IGNORABLE;
public const int PROPERTY_CHANGES_WHEN_LOWERCASED;
public const int PROPERTY_CHANGES_WHEN_UPPERCASED;
public const int PROPERTY_CHANGES_WHEN_TITLECASED;
public const int PROPERTY_CHANGES_WHEN_CASEFOLDED;
public const int PROPERTY_CHANGES_WHEN_CASEMAPPED;
public const int PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED;
public const int PROPERTY_BINARY_LIMIT;
public const int PROPERTY_BIDI_CLASS;
public const int PROPERTY_INT_START;
public const int PROPERTY_BLOCK;
public const int PROPERTY_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_DECOMPOSITION_TYPE;
public const int PROPERTY_EAST_ASIAN_WIDTH;
public const int PROPERTY_GENERAL_CATEGORY;
public const int PROPERTY_JOINING_GROUP;
public const int PROPERTY_JOINING_TYPE;
public const int PROPERTY_LINE_BREAK;
public const int PROPERTY_NUMERIC_TYPE;
public const int PROPERTY_SCRIPT;
public const int PROPERTY_HANGUL_SYLLABLE_TYPE;
public const int PROPERTY_NFD_QUICK_CHECK;
public const int PROPERTY_NFKD_QUICK_CHECK;
public const int PROPERTY_NFC_QUICK_CHECK;
public const int PROPERTY_NFKC_QUICK_CHECK;
public const int PROPERTY_LEAD_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_GRAPHEME_CLUSTER_BREAK;
public const int PROPERTY_SENTENCE_BREAK;
public const int PROPERTY_WORD_BREAK;
public const int PROPERTY_BIDI_PAIRED_BRACKET_TYPE;
public const int PROPERTY_INT_LIMIT;
public const int PROPERTY_GENERAL_CATEGORY_MASK;
public const int PROPERTY_MASK_START;
public const int PROPERTY_MASK_LIMIT;
public const int PROPERTY_NUMERIC_VALUE;
public const int PROPERTY_DOUBLE_START;
public const int PROPERTY_DOUBLE_LIMIT;
public const int PROPERTY_AGE;
public const int PROPERTY_STRING_START;
public const int PROPERTY_BIDI_MIRRORING_GLYPH;
public const int PROPERTY_CASE_FOLDING;
public const int PROPERTY_ISO_COMMENT;
public const int PROPERTY_LOWERCASE_MAPPING;
public const int PROPERTY_NAME;
public const int PROPERTY_SIMPLE_CASE_FOLDING;
public const int PROPERTY_SIMPLE_LOWERCASE_MAPPING;
public const int PROPERTY_SIMPLE_TITLECASE_MAPPING;
public const int PROPERTY_SIMPLE_UPPERCASE_MAPPING;
public const int PROPERTY_TITLECASE_MAPPING;
public const int PROPERTY_UNICODE_1_NAME;
public const int PROPERTY_UPPERCASE_MAPPING;
public const int PROPERTY_BIDI_PAIRED_BRACKET;
public const int PROPERTY_STRING_LIMIT;
public const int PROPERTY_SCRIPT_EXTENSIONS;
public const int PROPERTY_OTHER_PROPERTY_START;
public const int PROPERTY_OTHER_PROPERTY_LIMIT;
public const int PROPERTY_INVALID_CODE;
public const int CHAR_CATEGORY_UNASSIGNED;
public const int CHAR_CATEGORY_GENERAL_OTHER_TYPES;
public const int CHAR_CATEGORY_UPPERCASE_LETTER;
public const int CHAR_CATEGORY_LOWERCASE_LETTER;
public const int CHAR_CATEGORY_TITLECASE_LETTER;
public const int CHAR_CATEGORY_MODIFIER_LETTER;
public const int CHAR_CATEGORY_OTHER_LETTER;
public const int CHAR_CATEGORY_NON_SPACING_MARK;
public const int CHAR_CATEGORY_ENCLOSING_MARK;
public const int CHAR_CATEGORY_COMBINING_SPACING_MARK;
public const int CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER;
public const int CHAR_CATEGORY_LETTER_NUMBER;
public const int CHAR_CATEGORY_OTHER_NUMBER;
public const int CHAR_CATEGORY_SPACE_SEPARATOR;
public const int CHAR_CATEGORY_LINE_SEPARATOR;
public const int CHAR_CATEGORY_PARAGRAPH_SEPARATOR;
public const int CHAR_CATEGORY_CONTROL_CHAR;
public const int CHAR_CATEGORY_FORMAT_CHAR;
public const int CHAR_CATEGORY_PRIVATE_USE_CHAR;
public const int CHAR_CATEGORY_SURROGATE;
public const int CHAR_CATEGORY_DASH_PUNCTUATION;
public const int CHAR_CATEGORY_START_PUNCTUATION;
public const int CHAR_CATEGORY_END_PUNCTUATION;
public const int CHAR_CATEGORY_CONNECTOR_PUNCTUATION;
public const int CHAR_CATEGORY_OTHER_PUNCTUATION;
public const int CHAR_CATEGORY_MATH_SYMBOL;
public const int CHAR_CATEGORY_CURRENCY_SYMBOL;
public const int CHAR_CATEGORY_MODIFIER_SYMBOL;
public const int CHAR_CATEGORY_OTHER_SYMBOL;
public const int CHAR_CATEGORY_INITIAL_PUNCTUATION;
public const int CHAR_CATEGORY_FINAL_PUNCTUATION;
public const int CHAR_CATEGORY_CHAR_CATEGORY_COUNT;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR;
public const int CHAR_DIRECTION_ARABIC_NUMBER;
public const int CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR;
public const int CHAR_DIRECTION_BLOCK_SEPARATOR;
public const int CHAR_DIRECTION_SEGMENT_SEPARATOR;
public const int CHAR_DIRECTION_WHITE_SPACE_NEUTRAL;
public const int CHAR_DIRECTION_OTHER_NEUTRAL;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE;
public const int CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT;
public const int CHAR_DIRECTION_DIR_NON_SPACING_MARK;
public const int CHAR_DIRECTION_BOUNDARY_NEUTRAL;
public const int CHAR_DIRECTION_FIRST_STRONG_ISOLATE;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE;
public const int CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE;
public const int CHAR_DIRECTION_CHAR_DIRECTION_COUNT;
public const int BLOCK_CODE_NO_BLOCK;
public const int BLOCK_CODE_BASIC_LATIN;
public const int BLOCK_CODE_LATIN_1_SUPPLEMENT;
public const int BLOCK_CODE_LATIN_EXTENDED_A;
public const int BLOCK_CODE_LATIN_EXTENDED_B;
public const int BLOCK_CODE_IPA_EXTENSIONS;
public const int BLOCK_CODE_SPACING_MODIFIER_LETTERS;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS;
public const int BLOCK_CODE_GREEK;
public const int BLOCK_CODE_CYRILLIC;
public const int BLOCK_CODE_ARMENIAN;
public const int BLOCK_CODE_HEBREW;
public const int BLOCK_CODE_ARABIC;
public const int BLOCK_CODE_SYRIAC;
public const int BLOCK_CODE_THAANA;
public const int BLOCK_CODE_DEVANAGARI;
public const int BLOCK_CODE_BENGALI;
public const int BLOCK_CODE_GURMUKHI;
public const int BLOCK_CODE_GUJARATI;
public const int BLOCK_CODE_ORIYA;
public const int BLOCK_CODE_TAMIL;
public const int BLOCK_CODE_TELUGU;
public const int BLOCK_CODE_KANNADA;
public const int BLOCK_CODE_MALAYALAM;
public const int BLOCK_CODE_SINHALA;
public const int BLOCK_CODE_THAI;
public const int BLOCK_CODE_LAO;
public const int BLOCK_CODE_TIBETAN;
public const int BLOCK_CODE_MYANMAR;
public const int BLOCK_CODE_GEORGIAN;
public const int BLOCK_CODE_HANGUL_JAMO;
public const int BLOCK_CODE_ETHIOPIC;
public const int BLOCK_CODE_CHEROKEE;
public const int BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS;
public const int BLOCK_CODE_OGHAM;
public const int BLOCK_CODE_RUNIC;
public const int BLOCK_CODE_KHMER;
public const int BLOCK_CODE_MONGOLIAN;
public const int BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL;
public const int BLOCK_CODE_GREEK_EXTENDED;
public const int BLOCK_CODE_GENERAL_PUNCTUATION;
public const int BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS;
public const int BLOCK_CODE_CURRENCY_SYMBOLS;
public const int BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS;
public const int BLOCK_CODE_LETTERLIKE_SYMBOLS;
public const int BLOCK_CODE_NUMBER_FORMS;
public const int BLOCK_CODE_ARROWS;
public const int BLOCK_CODE_MATHEMATICAL_OPERATORS;
public const int BLOCK_CODE_MISCELLANEOUS_TECHNICAL;
public const int BLOCK_CODE_CONTROL_PICTURES;
public const int BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION;
public const int BLOCK_CODE_ENCLOSED_ALPHANUMERICS;
public const int BLOCK_CODE_BOX_DRAWING;
public const int BLOCK_CODE_BLOCK_ELEMENTS;
public const int BLOCK_CODE_GEOMETRIC_SHAPES;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS;
public const int BLOCK_CODE_DINGBATS;
public const int BLOCK_CODE_BRAILLE_PATTERNS;
public const int BLOCK_CODE_CJK_RADICALS_SUPPLEMENT;
public const int BLOCK_CODE_KANGXI_RADICALS;
public const int BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS;
public const int BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION;
public const int BLOCK_CODE_HIRAGANA;
public const int BLOCK_CODE_KATAKANA;
public const int BLOCK_CODE_BOPOMOFO;
public const int BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO;
public const int BLOCK_CODE_KANBUN;
public const int BLOCK_CODE_BOPOMOFO_EXTENDED;
public const int BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS;
public const int BLOCK_CODE_CJK_COMPATIBILITY;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS;
public const int BLOCK_CODE_YI_SYLLABLES;
public const int BLOCK_CODE_YI_RADICALS;
public const int BLOCK_CODE_HANGUL_SYLLABLES;
public const int BLOCK_CODE_HIGH_SURROGATES;
public const int BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES;
public const int BLOCK_CODE_LOW_SURROGATES;
public const int BLOCK_CODE_PRIVATE_USE_AREA;
public const int BLOCK_CODE_PRIVATE_USE;
public const int BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS;
public const int BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS;
public const int BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A;
public const int BLOCK_CODE_COMBINING_HALF_MARKS;
public const int BLOCK_CODE_CJK_COMPATIBILITY_FORMS;
public const int BLOCK_CODE_SMALL_FORM_VARIANTS;
public const int BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B;
public const int BLOCK_CODE_SPECIALS;
public const int BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS;
public const int BLOCK_CODE_OLD_ITALIC;
public const int BLOCK_CODE_GOTHIC;
public const int BLOCK_CODE_DESERET;
public const int BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS;
public const int BLOCK_CODE_MUSICAL_SYMBOLS;
public const int BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B;
public const int BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT;
public const int BLOCK_CODE_TAGS;
public const int BLOCK_CODE_CYRILLIC_SUPPLEMENT;
public const int BLOCK_CODE_CYRILLIC_SUPPLEMENTARY;
public const int BLOCK_CODE_TAGALOG;
public const int BLOCK_CODE_HANUNOO;
public const int BLOCK_CODE_BUHID;
public const int BLOCK_CODE_TAGBANWA;
public const int BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_A;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_B;
public const int BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B;
public const int BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS;
public const int BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS;
public const int BLOCK_CODE_VARIATION_SELECTORS;
public const int BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A;
public const int BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B;
public const int BLOCK_CODE_LIMBU;
public const int BLOCK_CODE_TAI_LE;
public const int BLOCK_CODE_KHMER_SYMBOLS;
public const int BLOCK_CODE_PHONETIC_EXTENSIONS;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS;
public const int BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS;
public const int BLOCK_CODE_LINEAR_B_SYLLABARY;
public const int BLOCK_CODE_LINEAR_B_IDEOGRAMS;
public const int BLOCK_CODE_AEGEAN_NUMBERS;
public const int BLOCK_CODE_UGARITIC;
public const int BLOCK_CODE_SHAVIAN;
public const int BLOCK_CODE_OSMANYA;
public const int BLOCK_CODE_CYPRIOT_SYLLABARY;
public const int BLOCK_CODE_TAI_XUAN_JING_SYMBOLS;
public const int BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT;
public const int BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION;
public const int BLOCK_CODE_ANCIENT_GREEK_NUMBERS;
public const int BLOCK_CODE_ARABIC_SUPPLEMENT;
public const int BLOCK_CODE_BUGINESE;
public const int BLOCK_CODE_CJK_STROKES;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT;
public const int BLOCK_CODE_COPTIC;
public const int BLOCK_CODE_ETHIOPIC_EXTENDED;
public const int BLOCK_CODE_ETHIOPIC_SUPPLEMENT;
public const int BLOCK_CODE_GEORGIAN_SUPPLEMENT;
public const int BLOCK_CODE_GLAGOLITIC;
public const int BLOCK_CODE_KHAROSHTHI;
public const int BLOCK_CODE_MODIFIER_TONE_LETTERS;
public const int BLOCK_CODE_NEW_TAI_LUE;
public const int BLOCK_CODE_OLD_PERSIAN;
public const int BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT;
public const int BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION;
public const int BLOCK_CODE_SYLOTI_NAGRI;
public const int BLOCK_CODE_TIFINAGH;
public const int BLOCK_CODE_VERTICAL_FORMS;
public const int BLOCK_CODE_NKO;
public const int BLOCK_CODE_BALINESE;
public const int BLOCK_CODE_LATIN_EXTENDED_C;
public const int BLOCK_CODE_LATIN_EXTENDED_D;
public const int BLOCK_CODE_PHAGS_PA;
public const int BLOCK_CODE_PHOENICIAN;
public const int BLOCK_CODE_CUNEIFORM;
public const int BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION;
public const int BLOCK_CODE_COUNTING_ROD_NUMERALS;
public const int BLOCK_CODE_SUNDANESE;
public const int BLOCK_CODE_LEPCHA;
public const int BLOCK_CODE_OL_CHIKI;
public const int BLOCK_CODE_CYRILLIC_EXTENDED_A;
public const int BLOCK_CODE_VAI;
public const int BLOCK_CODE_CYRILLIC_EXTENDED_B;
public const int BLOCK_CODE_SAURASHTRA;
public const int BLOCK_CODE_KAYAH_LI;
public const int BLOCK_CODE_REJANG;
public const int BLOCK_CODE_CHAM;
public const int BLOCK_CODE_ANCIENT_SYMBOLS;
public const int BLOCK_CODE_PHAISTOS_DISC;
public const int BLOCK_CODE_LYCIAN;
public const int BLOCK_CODE_CARIAN;
public const int BLOCK_CODE_LYDIAN;
public const int BLOCK_CODE_MAHJONG_TILES;
public const int BLOCK_CODE_DOMINO_TILES;
public const int BLOCK_CODE_SAMARITAN;
public const int BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED;
public const int BLOCK_CODE_TAI_THAM;
public const int BLOCK_CODE_VEDIC_EXTENSIONS;
public const int BLOCK_CODE_LISU;
public const int BLOCK_CODE_BAMUM;
public const int BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS;
public const int BLOCK_CODE_DEVANAGARI_EXTENDED;
public const int BLOCK_CODE_HANGUL_JAMO_EXTENDED_A;
public const int BLOCK_CODE_JAVANESE;
public const int BLOCK_CODE_MYANMAR_EXTENDED_A;
public const int BLOCK_CODE_TAI_VIET;
public const int BLOCK_CODE_MEETEI_MAYEK;
public const int BLOCK_CODE_HANGUL_JAMO_EXTENDED_B;
public const int BLOCK_CODE_IMPERIAL_ARAMAIC;
public const int BLOCK_CODE_OLD_SOUTH_ARABIAN;
public const int BLOCK_CODE_AVESTAN;
public const int BLOCK_CODE_INSCRIPTIONAL_PARTHIAN;
public const int BLOCK_CODE_INSCRIPTIONAL_PAHLAVI;
public const int BLOCK_CODE_OLD_TURKIC;
public const int BLOCK_CODE_RUMI_NUMERAL_SYMBOLS;
public const int BLOCK_CODE_KAITHI;
public const int BLOCK_CODE_EGYPTIAN_HIEROGLYPHS;
public const int BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT;
public const int BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C;
public const int BLOCK_CODE_MANDAIC;
public const int BLOCK_CODE_BATAK;
public const int BLOCK_CODE_ETHIOPIC_EXTENDED_A;
public const int BLOCK_CODE_BRAHMI;
public const int BLOCK_CODE_BAMUM_SUPPLEMENT;
public const int BLOCK_CODE_KANA_SUPPLEMENT;
public const int BLOCK_CODE_PLAYING_CARDS;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS;
public const int BLOCK_CODE_EMOTICONS;
public const int BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS;
public const int BLOCK_CODE_ALCHEMICAL_SYMBOLS;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D;
public const int BLOCK_CODE_ARABIC_EXTENDED_A;
public const int BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS;
public const int BLOCK_CODE_CHAKMA;
public const int BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS;
public const int BLOCK_CODE_MEROITIC_CURSIVE;
public const int BLOCK_CODE_MEROITIC_HIEROGLYPHS;
public const int BLOCK_CODE_MIAO;
public const int BLOCK_CODE_SHARADA;
public const int BLOCK_CODE_SORA_SOMPENG;
public const int BLOCK_CODE_SUNDANESE_SUPPLEMENT;
public const int BLOCK_CODE_TAKRI;
public const int BLOCK_CODE_BASSA_VAH;
public const int BLOCK_CODE_CAUCASIAN_ALBANIAN;
public const int BLOCK_CODE_COPTIC_EPACT_NUMBERS;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_EXTENDED;
public const int BLOCK_CODE_DUPLOYAN;
public const int BLOCK_CODE_ELBASAN;
public const int BLOCK_CODE_GEOMETRIC_SHAPES_EXTENDED;
public const int BLOCK_CODE_GRANTHA;
public const int BLOCK_CODE_KHOJKI;
public const int BLOCK_CODE_KHUDAWADI;
public const int BLOCK_CODE_LATIN_EXTENDED_E;
public const int BLOCK_CODE_LINEAR_A;
public const int BLOCK_CODE_MAHAJANI;
public const int BLOCK_CODE_MANICHAEAN;
public const int BLOCK_CODE_MENDE_KIKAKUI;
public const int BLOCK_CODE_MODI;
public const int BLOCK_CODE_MRO;
public const int BLOCK_CODE_MYANMAR_EXTENDED_B;
public const int BLOCK_CODE_NABATAEAN;
public const int BLOCK_CODE_OLD_NORTH_ARABIAN;
public const int BLOCK_CODE_OLD_PERMIC;
public const int BLOCK_CODE_ORNAMENTAL_DINGBATS;
public const int BLOCK_CODE_PAHAWH_HMONG;
public const int BLOCK_CODE_PALMYRENE;
public const int BLOCK_CODE_PAU_CIN_HAU;
public const int BLOCK_CODE_PSALTER_PAHLAVI;
public const int BLOCK_CODE_SHORTHAND_FORMAT_CONTROLS;
public const int BLOCK_CODE_SIDDHAM;
public const int BLOCK_CODE_SINHALA_ARCHAIC_NUMBERS;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_C;
public const int BLOCK_CODE_TIRHUTA;
public const int BLOCK_CODE_WARANG_CITI;
public const int BLOCK_CODE_COUNT;
public const int BLOCK_CODE_INVALID_CODE;
public const int BPT_NONE;
public const int BPT_OPEN;
public const int BPT_CLOSE;
public const int BPT_COUNT;
public const int EA_NEUTRAL;
public const int EA_AMBIGUOUS;
public const int EA_HALFWIDTH;
public const int EA_FULLWIDTH;
public const int EA_NARROW;
public const int EA_WIDE;
public const int EA_COUNT;
public const int UNICODE_CHAR_NAME;
public const int UNICODE_10_CHAR_NAME;
public const int EXTENDED_CHAR_NAME;
public const int CHAR_NAME_ALIAS;
public const int CHAR_NAME_CHOICE_COUNT;
public const int SHORT_PROPERTY_NAME;
public const int LONG_PROPERTY_NAME;
public const int PROPERTY_NAME_CHOICE_COUNT;
public const int DT_NONE;
public const int DT_CANONICAL;
public const int DT_COMPAT;
public const int DT_CIRCLE;
public const int DT_FINAL;
public const int DT_FONT;
public const int DT_FRACTION;
public const int DT_INITIAL;
public const int DT_ISOLATED;
public const int DT_MEDIAL;
public const int DT_NARROW;
public const int DT_NOBREAK;
public const int DT_SMALL;
public const int DT_SQUARE;
public const int DT_SUB;
public const int DT_SUPER;
public const int DT_VERTICAL;
public const int DT_WIDE;
public const int DT_COUNT;
public const int JT_NON_JOINING;
public const int JT_JOIN_CAUSING;
public const int JT_DUAL_JOINING;
public const int JT_LEFT_JOINING;
public const int JT_RIGHT_JOINING;
public const int JT_TRANSPARENT;
public const int JT_COUNT;
public const int JG_NO_JOINING_GROUP;
public const int JG_AIN;
public const int JG_ALAPH;
public const int JG_ALEF;
public const int JG_BEH;
public const int JG_BETH;
public const int JG_DAL;
public const int JG_DALATH_RISH;
public const int JG_E;
public const int JG_FEH;
public const int JG_FINAL_SEMKATH;
public const int JG_GAF;
public const int JG_GAMAL;
public const int JG_HAH;
public const int JG_TEH_MARBUTA_GOAL;
public const int JG_HAMZA_ON_HEH_GOAL;
public const int JG_HE;
public const int JG_HEH;
public const int JG_HEH_GOAL;
public const int JG_HETH;
public const int JG_KAF;
public const int JG_KAPH;
public const int JG_KNOTTED_HEH;
public const int JG_LAM;
public const int JG_LAMADH;
public const int JG_MEEM;
public const int JG_MIM;
public const int JG_NOON;
public const int JG_NUN;
public const int JG_PE;
public const int JG_QAF;
public const int JG_QAPH;
public const int JG_REH;
public const int JG_REVERSED_PE;
public const int JG_SAD;
public const int JG_SADHE;
public const int JG_SEEN;
public const int JG_SEMKATH;
public const int JG_SHIN;
public const int JG_SWASH_KAF;
public const int JG_SYRIAC_WAW;
public const int JG_TAH;
public const int JG_TAW;
public const int JG_TEH_MARBUTA;
public const int JG_TETH;
public const int JG_WAW;
public const int JG_YEH;
public const int JG_YEH_BARREE;
public const int JG_YEH_WITH_TAIL;
public const int JG_YUDH;
public const int JG_YUDH_HE;
public const int JG_ZAIN;
public const int JG_FE;
public const int JG_KHAPH;
public const int JG_ZHAIN;
public const int JG_BURUSHASKI_YEH_BARREE;
public const int JG_FARSI_YEH;
public const int JG_NYA;
public const int JG_ROHINGYA_YEH;
public const int JG_MANICHAEAN_ALEPH;
public const int JG_MANICHAEAN_AYIN;
public const int JG_MANICHAEAN_BETH;
public const int JG_MANICHAEAN_DALETH;
public const int JG_MANICHAEAN_DHAMEDH;
public const int JG_MANICHAEAN_FIVE;
public const int JG_MANICHAEAN_GIMEL;
public const int JG_MANICHAEAN_HETH;
public const int JG_MANICHAEAN_HUNDRED;
public const int JG_MANICHAEAN_KAPH;
public const int JG_MANICHAEAN_LAMEDH;
public const int JG_MANICHAEAN_MEM;
public const int JG_MANICHAEAN_NUN;
public const int JG_MANICHAEAN_ONE;
public const int JG_MANICHAEAN_PE;
public const int JG_MANICHAEAN_QOPH;
public const int JG_MANICHAEAN_RESH;
public const int JG_MANICHAEAN_SADHE;
public const int JG_MANICHAEAN_SAMEKH;
public const int JG_MANICHAEAN_TAW;
public const int JG_MANICHAEAN_TEN;
public const int JG_MANICHAEAN_TETH;
public const int JG_MANICHAEAN_THAMEDH;
public const int JG_MANICHAEAN_TWENTY;
public const int JG_MANICHAEAN_WAW;
public const int JG_MANICHAEAN_YODH;
public const int JG_MANICHAEAN_ZAYIN;
public const int JG_STRAIGHT_WAW;
public const int JG_COUNT;
public const int GCB_OTHER;
public const int GCB_CONTROL;
public const int GCB_CR;
public const int GCB_EXTEND;
public const int GCB_L;
public const int GCB_LF;
public const int GCB_LV;
public const int GCB_LVT;
public const int GCB_T;
public const int GCB_V;
public const int GCB_SPACING_MARK;
public const int GCB_PREPEND;
public const int GCB_REGIONAL_INDICATOR;
public const int GCB_COUNT;
public const int WB_OTHER;
public const int WB_ALETTER;
public const int WB_FORMAT;
public const int WB_KATAKANA;
public const int WB_MIDLETTER;
public const int WB_MIDNUM;
public const int WB_NUMERIC;
public const int WB_EXTENDNUMLET;
public const int WB_CR;
public const int WB_EXTEND;
public const int WB_LF;
public const int WB_MIDNUMLET;
public const int WB_NEWLINE;
public const int WB_REGIONAL_INDICATOR;
public const int WB_HEBREW_LETTER;
public const int WB_SINGLE_QUOTE;
public const int WB_DOUBLE_QUOTE;
public const int WB_COUNT;
public const int SB_OTHER;
public const int SB_ATERM;
public const int SB_CLOSE;
public const int SB_FORMAT;
public const int SB_LOWER;
public const int SB_NUMERIC;
public const int SB_OLETTER;
public const int SB_SEP;
public const int SB_SP;
public const int SB_STERM;
public const int SB_UPPER;
public const int SB_CR;
public const int SB_EXTEND;
public const int SB_LF;
public const int SB_SCONTINUE;
public const int SB_COUNT;
public const int LB_UNKNOWN;
public const int LB_AMBIGUOUS;
public const int LB_ALPHABETIC;
public const int LB_BREAK_BOTH;
public const int LB_BREAK_AFTER;
public const int LB_BREAK_BEFORE;
public const int LB_MANDATORY_BREAK;
public const int LB_CONTINGENT_BREAK;
public const int LB_CLOSE_PUNCTUATION;
public const int LB_COMBINING_MARK;
public const int LB_CARRIAGE_RETURN;
public const int LB_EXCLAMATION;
public const int LB_GLUE;
public const int LB_HYPHEN;
public const int LB_IDEOGRAPHIC;
public const int LB_INSEPARABLE;
public const int LB_INSEPERABLE;
public const int LB_INFIX_NUMERIC;
public const int LB_LINE_FEED;
public const int LB_NONSTARTER;
public const int LB_NUMERIC;
public const int LB_OPEN_PUNCTUATION;
public const int LB_POSTFIX_NUMERIC;
public const int LB_PREFIX_NUMERIC;
public const int LB_QUOTATION;
public const int LB_COMPLEX_CONTEXT;
public const int LB_SURROGATE;
public const int LB_SPACE;
public const int LB_BREAK_SYMBOLS;
public const int LB_ZWSPACE;
public const int LB_NEXT_LINE;
public const int LB_WORD_JOINER;
public const int LB_H2;
public const int LB_H3;
public const int LB_JL;
public const int LB_JT;
public const int LB_JV;
public const int LB_CLOSE_PARENTHESIS;
public const int LB_CONDITIONAL_JAPANESE_STARTER;
public const int LB_HEBREW_LETTER;
public const int LB_REGIONAL_INDICATOR;
public const int LB_COUNT;
public const int NT_NONE;
public const int NT_DECIMAL;
public const int NT_DIGIT;
public const int NT_NUMERIC;
public const int NT_COUNT;
public const int HST_NOT_APPLICABLE;
public const int HST_LEADING_JAMO;
public const int HST_VOWEL_JAMO;
public const int HST_TRAILING_JAMO;
public const int HST_LV_SYLLABLE;
public const int HST_LVT_SYLLABLE;
public const int HST_COUNT;
public const int FOLD_CASE_DEFAULT;
public const int FOLD_CASE_EXCLUDE_SPECIAL_I;
/* Methods */
public static charAge(int|string `$codepoint`): ?array
public static charDigitValue(int|string `$codepoint`): ?int
public static charDirection(int|string `$codepoint`): ?int
public static charFromName(string `$name`, int `$type` = `IntlChar::UNICODE_CHAR_NAME`): ?int
public static charMirror(int|string `$codepoint`): int|string|null
public static charName(int|string `$codepoint`, int `$type` = `IntlChar::UNICODE_CHAR_NAME`): ?string
public static charType(int|string `$codepoint`): ?int
public static chr(int|string `$codepoint`): ?string
public static digit(int|string `$codepoint`, int `$base` = 10): int|false|null
public static enumCharNames(
int|string `$start`,
int|string `$end`,
callable `$callback`,
int `$type` = `IntlChar::UNICODE_CHAR_NAME`
): bool
public static enumCharTypes(callable `$callback`): void
public static foldCase(int|string `$codepoint`, int `$options` = `IntlChar::FOLD_CASE_DEFAULT`): int|string|null
public static forDigit(int `$digit`, int `$base` = 10): int
public static getBidiPairedBracket(int|string `$codepoint`): int|string|null
public static getBlockCode(int|string `$codepoint`): ?int
public static getCombiningClass(int|string `$codepoint`): ?int
public static getFC_NFKC_Closure(int|string `$codepoint`): string|false|null
public static getIntPropertyMaxValue(int `$property`): int
public static getIntPropertyMinValue(int `$property`): int
public static getIntPropertyValue(int|string `$codepoint`, int `$property`): ?int
public static getNumericValue(int|string `$codepoint`): ?float
public static getPropertyEnum(string `$alias`): int
public static getPropertyName(int `$property`, int `$type` = `IntlChar::LONG_PROPERTY_NAME`): string|false
public static getPropertyValueEnum(int `$property`, string `$name`): int
public static getPropertyValueName(int `$property`, int `$value`, int `$type` = `IntlChar::LONG_PROPERTY_NAME`): string|false
public static getUnicodeVersion(): array
public static hasBinaryProperty(int|string `$codepoint`, int `$property`): ?bool
public static isalnum(int|string `$codepoint`): ?bool
public static isalpha(int|string `$codepoint`): ?bool
public static isbase(int|string `$codepoint`): ?bool
public static isblank(int|string `$codepoint`): ?bool
public static iscntrl(int|string `$codepoint`): ?bool
public static isdefined(int|string `$codepoint`): ?bool
public static isdigit(int|string `$codepoint`): ?bool
public static isgraph(int|string `$codepoint`): ?bool
public static isIDIgnorable(int|string `$codepoint`): ?bool
public static isIDPart(int|string `$codepoint`): ?bool
public static isIDStart(int|string `$codepoint`): ?bool
public static isISOControl(int|string `$codepoint`): ?bool
public static isJavaIDPart(int|string `$codepoint`): ?bool
public static isJavaIDStart(int|string `$codepoint`): ?bool
public static isJavaSpaceChar(int|string `$codepoint`): ?bool
public static islower(int|string `$codepoint`): ?bool
public static isMirrored(int|string `$codepoint`): ?bool
public static isprint(int|string `$codepoint`): ?bool
public static ispunct(int|string `$codepoint`): ?bool
public static isspace(int|string `$codepoint`): ?bool
public static istitle(int|string `$codepoint`): ?bool
public static isUAlphabetic(int|string `$codepoint`): ?bool
public static isULowercase(int|string `$codepoint`): ?bool
public static isupper(int|string `$codepoint`): ?bool
public static isUUppercase(int|string `$codepoint`): ?bool
public static isUWhiteSpace(int|string `$codepoint`): ?bool
public static isWhitespace(int|string `$codepoint`): ?bool
public static isxdigit(int|string `$codepoint`): ?bool
public static ord(int|string `$character`): ?int
public static tolower(int|string `$codepoint`): int|string|null
public static totitle(int|string `$codepoint`): int|string|null
public static toupper(int|string `$codepoint`): int|string|null
}

## Predefined Constants

`IntlChar::UNICODE_VERSION` string

`IntlChar::CODEPOINT_MIN` int

`IntlChar::CODEPOINT_MAX` int

`IntlChar::NO_NUMERIC_VALUE` int

  Special value that is returned by IntlChar::getNumericValue() when no numeric value is defined for a code point.

`IntlChar::PROPERTY_ALPHABETIC` int

`IntlChar::PROPERTY_BINARY_START` int

`IntlChar::PROPERTY_ASCII_HEX_DIGIT` int

`IntlChar::PROPERTY_BIDI_CONTROL` int

`IntlChar::PROPERTY_BIDI_MIRRORED` int

`IntlChar::PROPERTY_DASH` int

`IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT` int

`IntlChar::PROPERTY_DEPRECATED` int

`IntlChar::PROPERTY_DIACRITIC` int

`IntlChar::PROPERTY_EXTENDER` int

`IntlChar::PROPERTY_FULL_COMPOSITION_EXCLUSION` int

`IntlChar::PROPERTY_GRAPHEME_BASE` int

`IntlChar::PROPERTY_GRAPHEME_EXTEND` int

`IntlChar::PROPERTY_GRAPHEME_LINK` int

`IntlChar::PROPERTY_HEX_DIGIT` int

`IntlChar::PROPERTY_HYPHEN` int

`IntlChar::PROPERTY_ID_CONTINUE` int

`IntlChar::PROPERTY_ID_START` int

`IntlChar::PROPERTY_IDEOGRAPHIC` int

`IntlChar::PROPERTY_IDS_BINARY_OPERATOR` int

`IntlChar::PROPERTY_IDS_TRINARY_OPERATOR` int

`IntlChar::PROPERTY_IDS_UNARY_OPERATOR` int
  For programmatic determination of Ideographic Description Sequences. Available as of PHP 8.4.0.
`IntlChar::PROPERTY_ID_COMPAT_MATH_START` int
  Used in mathematical identifier profile in UAX 31. Available as of PHP 8.4.0.
`IntlChar::PROPERTY_ID_COMPAT_MATH_CONTINUE` int
  Used in mathematical identifier profile in UAX 31. Available as of PHP 8.4.0.
`IntlChar::PROPERTY_JOIN_CONTROL` int

`IntlChar::PROPERTY_LOGICAL_ORDER_EXCEPTION` int

`IntlChar::PROPERTY_LOWERCASE` int

`IntlChar::PROPERTY_MATH` int

`IntlChar::PROPERTY_NONCHARACTER_CODE_POINT` int

`IntlChar::PROPERTY_QUOTATION_MARK` int

`IntlChar::PROPERTY_RADICAL` int

`IntlChar::PROPERTY_SOFT_DOTTED` int

`IntlChar::PROPERTY_TERMINAL_PUNCTUATION` int

`IntlChar::PROPERTY_UNIFIED_IDEOGRAPH` int

`IntlChar::PROPERTY_UPPERCASE` int

`IntlChar::PROPERTY_WHITE_SPACE` int

`IntlChar::PROPERTY_XID_CONTINUE` int

`IntlChar::PROPERTY_XID_START` int

`IntlChar::PROPERTY_CASE_SENSITIVE` int

`IntlChar::PROPERTY_S_TERM` int

`IntlChar::PROPERTY_VARIATION_SELECTOR` int

`IntlChar::PROPERTY_NFD_INERT` int

`IntlChar::PROPERTY_NFKD_INERT` int

`IntlChar::PROPERTY_NFC_INERT` int

`IntlChar::PROPERTY_NFKC_INERT` int

`IntlChar::PROPERTY_SEGMENT_STARTER` int

`IntlChar::PROPERTY_PATTERN_SYNTAX` int

`IntlChar::PROPERTY_PATTERN_WHITE_SPACE` int

`IntlChar::PROPERTY_POSIX_ALNUM` int

`IntlChar::PROPERTY_POSIX_BLANK` int

`IntlChar::PROPERTY_POSIX_GRAPH` int

`IntlChar::PROPERTY_POSIX_PRINT` int

`IntlChar::PROPERTY_POSIX_XDIGIT` int

`IntlChar::PROPERTY_CASED` int

`IntlChar::PROPERTY_CASE_IGNORABLE` int

`IntlChar::PROPERTY_CHANGES_WHEN_LOWERCASED` int

`IntlChar::PROPERTY_CHANGES_WHEN_UPPERCASED` int

`IntlChar::PROPERTY_CHANGES_WHEN_TITLECASED` int

`IntlChar::PROPERTY_CHANGES_WHEN_CASEFOLDED` int

`IntlChar::PROPERTY_CHANGES_WHEN_CASEMAPPED` int

`IntlChar::PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED` int

`IntlChar::PROPERTY_BINARY_LIMIT` int

`IntlChar::PROPERTY_BIDI_CLASS` int

`IntlChar::PROPERTY_INT_START` int

`IntlChar::PROPERTY_BLOCK` int

`IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS` int

`IntlChar::PROPERTY_DECOMPOSITION_TYPE` int

`IntlChar::PROPERTY_EAST_ASIAN_WIDTH` int

`IntlChar::PROPERTY_GENERAL_CATEGORY` int

`IntlChar::PROPERTY_JOINING_GROUP` int

`IntlChar::PROPERTY_JOINING_TYPE` int

`IntlChar::PROPERTY_LINE_BREAK` int

`IntlChar::PROPERTY_NUMERIC_TYPE` int

`IntlChar::PROPERTY_SCRIPT` int

`IntlChar::PROPERTY_HANGUL_SYLLABLE_TYPE` int

`IntlChar::PROPERTY_NFD_QUICK_CHECK` int

`IntlChar::PROPERTY_NFKD_QUICK_CHECK` int

`IntlChar::PROPERTY_NFC_QUICK_CHECK` int

`IntlChar::PROPERTY_NFKC_QUICK_CHECK` int

`IntlChar::PROPERTY_LEAD_CANONICAL_COMBINING_CLASS` int

`IntlChar::PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS` int

`IntlChar::PROPERTY_GRAPHEME_CLUSTER_BREAK` int

`IntlChar::PROPERTY_SENTENCE_BREAK` int

`IntlChar::PROPERTY_WORD_BREAK` int

`IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE` int

`IntlChar::PROPERTY_INT_LIMIT` int

`IntlChar::PROPERTY_GENERAL_CATEGORY_MASK` int

`IntlChar::PROPERTY_MASK_START` int

`IntlChar::PROPERTY_MASK_LIMIT` int

`IntlChar::PROPERTY_NUMERIC_VALUE` int

`IntlChar::PROPERTY_DOUBLE_START` int

`IntlChar::PROPERTY_DOUBLE_LIMIT` int

`IntlChar::PROPERTY_AGE` int

`IntlChar::PROPERTY_STRING_START` int

`IntlChar::PROPERTY_BIDI_MIRRORING_GLYPH` int

`IntlChar::PROPERTY_CASE_FOLDING` int

`IntlChar::PROPERTY_ISO_COMMENT` int

`IntlChar::PROPERTY_LOWERCASE_MAPPING` int

`IntlChar::PROPERTY_NAME` int

`IntlChar::PROPERTY_SIMPLE_CASE_FOLDING` int

`IntlChar::PROPERTY_SIMPLE_LOWERCASE_MAPPING` int

`IntlChar::PROPERTY_SIMPLE_TITLECASE_MAPPING` int

`IntlChar::PROPERTY_SIMPLE_UPPERCASE_MAPPING` int

`IntlChar::PROPERTY_TITLECASE_MAPPING` int

`IntlChar::PROPERTY_UNICODE_1_NAME` int

`IntlChar::PROPERTY_UPPERCASE_MAPPING` int

`IntlChar::PROPERTY_BIDI_PAIRED_BRACKET` int

`IntlChar::PROPERTY_STRING_LIMIT` int

`IntlChar::PROPERTY_SCRIPT_EXTENSIONS` int

`IntlChar::PROPERTY_OTHER_PROPERTY_START` int

`IntlChar::PROPERTY_OTHER_PROPERTY_LIMIT` int

`IntlChar::PROPERTY_INVALID_CODE` int

`IntlChar::CHAR_CATEGORY_UNASSIGNED` int

`IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES` int

`IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER` int

`IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER` int

`IntlChar::CHAR_CATEGORY_TITLECASE_LETTER` int

`IntlChar::CHAR_CATEGORY_MODIFIER_LETTER` int

`IntlChar::CHAR_CATEGORY_OTHER_LETTER` int

`IntlChar::CHAR_CATEGORY_NON_SPACING_MARK` int

`IntlChar::CHAR_CATEGORY_ENCLOSING_MARK` int

`IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK` int

`IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER` int

`IntlChar::CHAR_CATEGORY_LETTER_NUMBER` int

`IntlChar::CHAR_CATEGORY_OTHER_NUMBER` int

`IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR` int

`IntlChar::CHAR_CATEGORY_LINE_SEPARATOR` int

`IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR` int

`IntlChar::CHAR_CATEGORY_CONTROL_CHAR` int

`IntlChar::CHAR_CATEGORY_FORMAT_CHAR` int

`IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR` int

`IntlChar::CHAR_CATEGORY_SURROGATE` int

`IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_START_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_END_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_MATH_SYMBOL` int

`IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL` int

`IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL` int

`IntlChar::CHAR_CATEGORY_OTHER_SYMBOL` int

`IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION` int

`IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT` int

`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT` int

`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT` int

`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER` int

`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR` int

`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR` int

`IntlChar::CHAR_DIRECTION_ARABIC_NUMBER` int

`IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR` int

`IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR` int

`IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR` int

`IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL` int

`IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL` int

`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING` int

`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE` int

`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC` int

`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING` int

`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE` int

`IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT` int

`IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK` int

`IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL` int

`IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE` int

`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE` int

`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE` int

`IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE` int

`IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT` int

`IntlChar::BLOCK_CODE_NO_BLOCK` int

`IntlChar::BLOCK_CODE_BASIC_LATIN` int

`IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_A` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_B` int

`IntlChar::BLOCK_CODE_IPA_EXTENSIONS` int

`IntlChar::BLOCK_CODE_SPACING_MODIFIER_LETTERS` int

`IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS` int

`IntlChar::BLOCK_CODE_GREEK` int

`IntlChar::BLOCK_CODE_CYRILLIC` int

`IntlChar::BLOCK_CODE_ARMENIAN` int

`IntlChar::BLOCK_CODE_HEBREW` int

`IntlChar::BLOCK_CODE_ARABIC` int

`IntlChar::BLOCK_CODE_SYRIAC` int

`IntlChar::BLOCK_CODE_THAANA` int

`IntlChar::BLOCK_CODE_DEVANAGARI` int

`IntlChar::BLOCK_CODE_BENGALI` int

`IntlChar::BLOCK_CODE_GURMUKHI` int

`IntlChar::BLOCK_CODE_GUJARATI` int

`IntlChar::BLOCK_CODE_ORIYA` int

`IntlChar::BLOCK_CODE_TAMIL` int

`IntlChar::BLOCK_CODE_TELUGU` int

`IntlChar::BLOCK_CODE_KANNADA` int

`IntlChar::BLOCK_CODE_MALAYALAM` int

`IntlChar::BLOCK_CODE_SINHALA` int

`IntlChar::BLOCK_CODE_THAI` int

`IntlChar::BLOCK_CODE_LAO` int

`IntlChar::BLOCK_CODE_TIBETAN` int

`IntlChar::BLOCK_CODE_MYANMAR` int

`IntlChar::BLOCK_CODE_GEORGIAN` int

`IntlChar::BLOCK_CODE_HANGUL_JAMO` int

`IntlChar::BLOCK_CODE_ETHIOPIC` int

`IntlChar::BLOCK_CODE_CHEROKEE` int

`IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS` int

`IntlChar::BLOCK_CODE_OGHAM` int

`IntlChar::BLOCK_CODE_RUNIC` int

`IntlChar::BLOCK_CODE_KHMER` int

`IntlChar::BLOCK_CODE_MONGOLIAN` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL` int

`IntlChar::BLOCK_CODE_GREEK_EXTENDED` int

`IntlChar::BLOCK_CODE_GENERAL_PUNCTUATION` int

`IntlChar::BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS` int

`IntlChar::BLOCK_CODE_CURRENCY_SYMBOLS` int

`IntlChar::BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS` int

`IntlChar::BLOCK_CODE_LETTERLIKE_SYMBOLS` int

`IntlChar::BLOCK_CODE_NUMBER_FORMS` int

`IntlChar::BLOCK_CODE_ARROWS` int

`IntlChar::BLOCK_CODE_MATHEMATICAL_OPERATORS` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_TECHNICAL` int

`IntlChar::BLOCK_CODE_CONTROL_PICTURES` int

`IntlChar::BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION` int

`IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERICS` int

`IntlChar::BLOCK_CODE_BOX_DRAWING` int

`IntlChar::BLOCK_CODE_BLOCK_ELEMENTS` int

`IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS` int

`IntlChar::BLOCK_CODE_DINGBATS` int

`IntlChar::BLOCK_CODE_BRAILLE_PATTERNS` int

`IntlChar::BLOCK_CODE_CJK_RADICALS_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_KANGXI_RADICALS` int

`IntlChar::BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS` int

`IntlChar::BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION` int

`IntlChar::BLOCK_CODE_HIRAGANA` int

`IntlChar::BLOCK_CODE_KATAKANA` int

`IntlChar::BLOCK_CODE_BOPOMOFO` int

`IntlChar::BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO` int

`IntlChar::BLOCK_CODE_KANBUN` int

`IntlChar::BLOCK_CODE_BOPOMOFO_EXTENDED` int

`IntlChar::BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS` int

`IntlChar::BLOCK_CODE_CJK_COMPATIBILITY` int

`IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A` int

`IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS` int

`IntlChar::BLOCK_CODE_YI_SYLLABLES` int

`IntlChar::BLOCK_CODE_YI_RADICALS` int

`IntlChar::BLOCK_CODE_HANGUL_SYLLABLES` int

`IntlChar::BLOCK_CODE_HIGH_SURROGATES` int

`IntlChar::BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES` int

`IntlChar::BLOCK_CODE_LOW_SURROGATES` int

`IntlChar::BLOCK_CODE_PRIVATE_USE_AREA` int

`IntlChar::BLOCK_CODE_PRIVATE_USE` int

`IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS` int

`IntlChar::BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS` int

`IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A` int

`IntlChar::BLOCK_CODE_COMBINING_HALF_MARKS` int

`IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_FORMS` int

`IntlChar::BLOCK_CODE_SMALL_FORM_VARIANTS` int

`IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B` int

`IntlChar::BLOCK_CODE_SPECIALS` int

`IntlChar::BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS` int

`IntlChar::BLOCK_CODE_OLD_ITALIC` int

`IntlChar::BLOCK_CODE_GOTHIC` int

`IntlChar::BLOCK_CODE_DESERET` int

`IntlChar::BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS` int

`IntlChar::BLOCK_CODE_MUSICAL_SYMBOLS` int

`IntlChar::BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS` int

`IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B` int

`IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_TAGS` int

`IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENTARY` int

`IntlChar::BLOCK_CODE_TAGALOG` int

`IntlChar::BLOCK_CODE_HANUNOO` int

`IntlChar::BLOCK_CODE_BUHID` int

`IntlChar::BLOCK_CODE_TAGBANWA` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A` int

`IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_A` int

`IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_B` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B` int

`IntlChar::BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS` int

`IntlChar::BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS` int

`IntlChar::BLOCK_CODE_VARIATION_SELECTORS` int

`IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A` int

`IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B` int

`IntlChar::BLOCK_CODE_LIMBU` int

`IntlChar::BLOCK_CODE_TAI_LE` int

`IntlChar::BLOCK_CODE_KHMER_SYMBOLS` int

`IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS` int

`IntlChar::BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS` int

`IntlChar::BLOCK_CODE_LINEAR_B_SYLLABARY` int

`IntlChar::BLOCK_CODE_LINEAR_B_IDEOGRAMS` int

`IntlChar::BLOCK_CODE_AEGEAN_NUMBERS` int

`IntlChar::BLOCK_CODE_UGARITIC` int

`IntlChar::BLOCK_CODE_SHAVIAN` int

`IntlChar::BLOCK_CODE_OSMANYA` int

`IntlChar::BLOCK_CODE_CYPRIOT_SYLLABARY` int

`IntlChar::BLOCK_CODE_TAI_XUAN_JING_SYMBOLS` int

`IntlChar::BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION` int

`IntlChar::BLOCK_CODE_ANCIENT_GREEK_NUMBERS` int

`IntlChar::BLOCK_CODE_ARABIC_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_BUGINESE` int

`IntlChar::BLOCK_CODE_CJK_STROKES` int

`IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_COPTIC` int

`IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED` int

`IntlChar::BLOCK_CODE_ETHIOPIC_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_GEORGIAN_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_GLAGOLITIC` int

`IntlChar::BLOCK_CODE_KHAROSHTHI` int

`IntlChar::BLOCK_CODE_MODIFIER_TONE_LETTERS` int

`IntlChar::BLOCK_CODE_NEW_TAI_LUE` int

`IntlChar::BLOCK_CODE_OLD_PERSIAN` int

`IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION` int

`IntlChar::BLOCK_CODE_SYLOTI_NAGRI` int

`IntlChar::BLOCK_CODE_TIFINAGH` int

`IntlChar::BLOCK_CODE_VERTICAL_FORMS` int

`IntlChar::BLOCK_CODE_NKO` int

`IntlChar::BLOCK_CODE_BALINESE` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_C` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_D` int

`IntlChar::BLOCK_CODE_PHAGS_PA` int

`IntlChar::BLOCK_CODE_PHOENICIAN` int

`IntlChar::BLOCK_CODE_CUNEIFORM` int

`IntlChar::BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION` int

`IntlChar::BLOCK_CODE_COUNTING_ROD_NUMERALS` int

`IntlChar::BLOCK_CODE_SUNDANESE` int

`IntlChar::BLOCK_CODE_LEPCHA` int

`IntlChar::BLOCK_CODE_OL_CHIKI` int

`IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_A` int

`IntlChar::BLOCK_CODE_VAI` int

`IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_B` int

`IntlChar::BLOCK_CODE_SAURASHTRA` int

`IntlChar::BLOCK_CODE_KAYAH_LI` int

`IntlChar::BLOCK_CODE_REJANG` int

`IntlChar::BLOCK_CODE_CHAM` int

`IntlChar::BLOCK_CODE_ANCIENT_SYMBOLS` int

`IntlChar::BLOCK_CODE_PHAISTOS_DISC` int

`IntlChar::BLOCK_CODE_LYCIAN` int

`IntlChar::BLOCK_CODE_CARIAN` int

`IntlChar::BLOCK_CODE_LYDIAN` int

`IntlChar::BLOCK_CODE_MAHJONG_TILES` int

`IntlChar::BLOCK_CODE_DOMINO_TILES` int

`IntlChar::BLOCK_CODE_SAMARITAN` int

`IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED` int

`IntlChar::BLOCK_CODE_TAI_THAM` int

`IntlChar::BLOCK_CODE_VEDIC_EXTENSIONS` int

`IntlChar::BLOCK_CODE_LISU` int

`IntlChar::BLOCK_CODE_BAMUM` int

`IntlChar::BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS` int

`IntlChar::BLOCK_CODE_DEVANAGARI_EXTENDED` int

`IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_A` int

`IntlChar::BLOCK_CODE_JAVANESE` int

`IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_A` int

`IntlChar::BLOCK_CODE_TAI_VIET` int

`IntlChar::BLOCK_CODE_MEETEI_MAYEK` int

`IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_B` int

`IntlChar::BLOCK_CODE_IMPERIAL_ARAMAIC` int

`IntlChar::BLOCK_CODE_OLD_SOUTH_ARABIAN` int

`IntlChar::BLOCK_CODE_AVESTAN` int

`IntlChar::BLOCK_CODE_INSCRIPTIONAL_PARTHIAN` int

`IntlChar::BLOCK_CODE_INSCRIPTIONAL_PAHLAVI` int

`IntlChar::BLOCK_CODE_OLD_TURKIC` int

`IntlChar::BLOCK_CODE_RUMI_NUMERAL_SYMBOLS` int

`IntlChar::BLOCK_CODE_KAITHI` int

`IntlChar::BLOCK_CODE_EGYPTIAN_HIEROGLYPHS` int

`IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C` int

`IntlChar::BLOCK_CODE_MANDAIC` int

`IntlChar::BLOCK_CODE_BATAK` int

`IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED_A` int

`IntlChar::BLOCK_CODE_BRAHMI` int

`IntlChar::BLOCK_CODE_BAMUM_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_KANA_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_PLAYING_CARDS` int

`IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS` int

`IntlChar::BLOCK_CODE_EMOTICONS` int

`IntlChar::BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS` int

`IntlChar::BLOCK_CODE_ALCHEMICAL_SYMBOLS` int

`IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D` int

`IntlChar::BLOCK_CODE_ARABIC_EXTENDED_A` int

`IntlChar::BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS` int

`IntlChar::BLOCK_CODE_CHAKMA` int

`IntlChar::BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS` int

`IntlChar::BLOCK_CODE_MEROITIC_CURSIVE` int

`IntlChar::BLOCK_CODE_MEROITIC_HIEROGLYPHS` int

`IntlChar::BLOCK_CODE_MIAO` int

`IntlChar::BLOCK_CODE_SHARADA` int

`IntlChar::BLOCK_CODE_SORA_SOMPENG` int

`IntlChar::BLOCK_CODE_SUNDANESE_SUPPLEMENT` int

`IntlChar::BLOCK_CODE_TAKRI` int

`IntlChar::BLOCK_CODE_BASSA_VAH` int

`IntlChar::BLOCK_CODE_CAUCASIAN_ALBANIAN` int

`IntlChar::BLOCK_CODE_COPTIC_EPACT_NUMBERS` int

`IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_EXTENDED` int

`IntlChar::BLOCK_CODE_DUPLOYAN` int

`IntlChar::BLOCK_CODE_ELBASAN` int

`IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES_EXTENDED` int

`IntlChar::BLOCK_CODE_GRANTHA` int

`IntlChar::BLOCK_CODE_KHOJKI` int

`IntlChar::BLOCK_CODE_KHUDAWADI` int

`IntlChar::BLOCK_CODE_LATIN_EXTENDED_E` int

`IntlChar::BLOCK_CODE_LINEAR_A` int

`IntlChar::BLOCK_CODE_MAHAJANI` int

`IntlChar::BLOCK_CODE_MANICHAEAN` int

`IntlChar::BLOCK_CODE_MENDE_KIKAKUI` int

`IntlChar::BLOCK_CODE_MODI` int

`IntlChar::BLOCK_CODE_MRO` int

`IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_B` int

`IntlChar::BLOCK_CODE_NABATAEAN` int

`IntlChar::BLOCK_CODE_OLD_NORTH_ARABIAN` int

`IntlChar::BLOCK_CODE_OLD_PERMIC` int

`IntlChar::BLOCK_CODE_ORNAMENTAL_DINGBATS` int

`IntlChar::BLOCK_CODE_PAHAWH_HMONG` int

`IntlChar::BLOCK_CODE_PALMYRENE` int

`IntlChar::BLOCK_CODE_PAU_CIN_HAU` int

`IntlChar::BLOCK_CODE_PSALTER_PAHLAVI` int

`IntlChar::BLOCK_CODE_SHORTHAND_FORMAT_CONTROLS` int

`IntlChar::BLOCK_CODE_SIDDHAM` int

`IntlChar::BLOCK_CODE_SINHALA_ARCHAIC_NUMBERS` int

`IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_C` int

`IntlChar::BLOCK_CODE_TIRHUTA` int

`IntlChar::BLOCK_CODE_WARANG_CITI` int

`IntlChar::BLOCK_CODE_COUNT` int

`IntlChar::BLOCK_CODE_INVALID_CODE` int

`IntlChar::BPT_NONE` int

`IntlChar::BPT_OPEN` int

`IntlChar::BPT_CLOSE` int

`IntlChar::BPT_COUNT` int

`IntlChar::EA_NEUTRAL` int

`IntlChar::EA_AMBIGUOUS` int

`IntlChar::EA_HALFWIDTH` int

`IntlChar::EA_FULLWIDTH` int

`IntlChar::EA_NARROW` int

`IntlChar::EA_WIDE` int

`IntlChar::EA_COUNT` int

`IntlChar::UNICODE_CHAR_NAME` int

`IntlChar::UNICODE_10_CHAR_NAME` int

`IntlChar::EXTENDED_CHAR_NAME` int

`IntlChar::CHAR_NAME_ALIAS` int

`IntlChar::CHAR_NAME_CHOICE_COUNT` int

`IntlChar::SHORT_PROPERTY_NAME` int

`IntlChar::LONG_PROPERTY_NAME` int

`IntlChar::PROPERTY_NAME_CHOICE_COUNT` int

`IntlChar::DT_NONE` int

`IntlChar::DT_CANONICAL` int

`IntlChar::DT_COMPAT` int

`IntlChar::DT_CIRCLE` int

`IntlChar::DT_FINAL` int

`IntlChar::DT_FONT` int

`IntlChar::DT_FRACTION` int

`IntlChar::DT_INITIAL` int

`IntlChar::DT_ISOLATED` int

`IntlChar::DT_MEDIAL` int

`IntlChar::DT_NARROW` int

`IntlChar::DT_NOBREAK` int

`IntlChar::DT_SMALL` int

`IntlChar::DT_SQUARE` int

`IntlChar::DT_SUB` int

`IntlChar::DT_SUPER` int

`IntlChar::DT_VERTICAL` int

`IntlChar::DT_WIDE` int

`IntlChar::DT_COUNT` int

`IntlChar::JT_NON_JOINING` int

`IntlChar::JT_JOIN_CAUSING` int

`IntlChar::JT_DUAL_JOINING` int

`IntlChar::JT_LEFT_JOINING` int

`IntlChar::JT_RIGHT_JOINING` int

`IntlChar::JT_TRANSPARENT` int

`IntlChar::JT_COUNT` int

`IntlChar::JG_NO_JOINING_GROUP` int

`IntlChar::JG_AIN` int

`IntlChar::JG_ALAPH` int

`IntlChar::JG_ALEF` int

`IntlChar::JG_BEH` int

`IntlChar::JG_BETH` int

`IntlChar::JG_DAL` int

`IntlChar::JG_DALATH_RISH` int

`IntlChar::JG_E` int

`IntlChar::JG_FEH` int

`IntlChar::JG_FINAL_SEMKATH` int

`IntlChar::JG_GAF` int

`IntlChar::JG_GAMAL` int

`IntlChar::JG_HAH` int

`IntlChar::JG_TEH_MARBUTA_GOAL` int

`IntlChar::JG_HAMZA_ON_HEH_GOAL` int

`IntlChar::JG_HE` int

`IntlChar::JG_HEH` int

`IntlChar::JG_HEH_GOAL` int

`IntlChar::JG_HETH` int

`IntlChar::JG_KAF` int

`IntlChar::JG_KAPH` int

`IntlChar::JG_KNOTTED_HEH` int

`IntlChar::JG_LAM` int

`IntlChar::JG_LAMADH` int

`IntlChar::JG_MEEM` int

`IntlChar::JG_MIM` int

`IntlChar::JG_NOON` int

`IntlChar::JG_NUN` int

`IntlChar::JG_PE` int

`IntlChar::JG_QAF` int

`IntlChar::JG_QAPH` int

`IntlChar::JG_REH` int

`IntlChar::JG_REVERSED_PE` int

`IntlChar::JG_SAD` int

`IntlChar::JG_SADHE` int

`IntlChar::JG_SEEN` int

`IntlChar::JG_SEMKATH` int

`IntlChar::JG_SHIN` int

`IntlChar::JG_SWASH_KAF` int

`IntlChar::JG_SYRIAC_WAW` int

`IntlChar::JG_TAH` int

`IntlChar::JG_TAW` int

`IntlChar::JG_TEH_MARBUTA` int

`IntlChar::JG_TETH` int

`IntlChar::JG_WAW` int

`IntlChar::JG_YEH` int

`IntlChar::JG_YEH_BARREE` int

`IntlChar::JG_YEH_WITH_TAIL` int

`IntlChar::JG_YUDH` int

`IntlChar::JG_YUDH_HE` int

`IntlChar::JG_ZAIN` int

`IntlChar::JG_FE` int

`IntlChar::JG_KHAPH` int

`IntlChar::JG_ZHAIN` int

`IntlChar::JG_BURUSHASKI_YEH_BARREE` int

`IntlChar::JG_FARSI_YEH` int

`IntlChar::JG_NYA` int

`IntlChar::JG_ROHINGYA_YEH` int

`IntlChar::JG_MANICHAEAN_ALEPH` int

`IntlChar::JG_MANICHAEAN_AYIN` int

`IntlChar::JG_MANICHAEAN_BETH` int

`IntlChar::JG_MANICHAEAN_DALETH` int

`IntlChar::JG_MANICHAEAN_DHAMEDH` int

`IntlChar::JG_MANICHAEAN_FIVE` int

`IntlChar::JG_MANICHAEAN_GIMEL` int

`IntlChar::JG_MANICHAEAN_HETH` int

`IntlChar::JG_MANICHAEAN_HUNDRED` int

`IntlChar::JG_MANICHAEAN_KAPH` int

`IntlChar::JG_MANICHAEAN_LAMEDH` int

`IntlChar::JG_MANICHAEAN_MEM` int

`IntlChar::JG_MANICHAEAN_NUN` int

`IntlChar::JG_MANICHAEAN_ONE` int

`IntlChar::JG_MANICHAEAN_PE` int

`IntlChar::JG_MANICHAEAN_QOPH` int

`IntlChar::JG_MANICHAEAN_RESH` int

`IntlChar::JG_MANICHAEAN_SADHE` int

`IntlChar::JG_MANICHAEAN_SAMEKH` int

`IntlChar::JG_MANICHAEAN_TAW` int

`IntlChar::JG_MANICHAEAN_TEN` int

`IntlChar::JG_MANICHAEAN_TETH` int

`IntlChar::JG_MANICHAEAN_THAMEDH` int

`IntlChar::JG_MANICHAEAN_TWENTY` int

`IntlChar::JG_MANICHAEAN_WAW` int

`IntlChar::JG_MANICHAEAN_YODH` int

`IntlChar::JG_MANICHAEAN_ZAYIN` int

`IntlChar::JG_STRAIGHT_WAW` int

`IntlChar::JG_COUNT` int

`IntlChar::GCB_OTHER` int

`IntlChar::GCB_CONTROL` int

`IntlChar::GCB_CR` int

`IntlChar::GCB_EXTEND` int

`IntlChar::GCB_L` int

`IntlChar::GCB_LF` int

`IntlChar::GCB_LV` int

`IntlChar::GCB_LVT` int

`IntlChar::GCB_T` int

`IntlChar::GCB_V` int

`IntlChar::GCB_SPACING_MARK` int

`IntlChar::GCB_PREPEND` int

`IntlChar::GCB_REGIONAL_INDICATOR` int

`IntlChar::GCB_COUNT` int

`IntlChar::WB_OTHER` int

`IntlChar::WB_ALETTER` int

`IntlChar::WB_FORMAT` int

`IntlChar::WB_KATAKANA` int

`IntlChar::WB_MIDLETTER` int

`IntlChar::WB_MIDNUM` int

`IntlChar::WB_NUMERIC` int

`IntlChar::WB_EXTENDNUMLET` int

`IntlChar::WB_CR` int

`IntlChar::WB_EXTEND` int

`IntlChar::WB_LF` int

`IntlChar::WB_MIDNUMLET` int

`IntlChar::WB_NEWLINE` int

`IntlChar::WB_REGIONAL_INDICATOR` int

`IntlChar::WB_HEBREW_LETTER` int

`IntlChar::WB_SINGLE_QUOTE` int

`IntlChar::WB_DOUBLE_QUOTE` int

`IntlChar::WB_COUNT` int

`IntlChar::SB_OTHER` int

`IntlChar::SB_ATERM` int

`IntlChar::SB_CLOSE` int

`IntlChar::SB_FORMAT` int

`IntlChar::SB_LOWER` int

`IntlChar::SB_NUMERIC` int

`IntlChar::SB_OLETTER` int

`IntlChar::SB_SEP` int

`IntlChar::SB_SP` int

`IntlChar::SB_STERM` int

`IntlChar::SB_UPPER` int

`IntlChar::SB_CR` int

`IntlChar::SB_EXTEND` int

`IntlChar::SB_LF` int

`IntlChar::SB_SCONTINUE` int

`IntlChar::SB_COUNT` int

`IntlChar::LB_UNKNOWN` int

`IntlChar::LB_AMBIGUOUS` int

`IntlChar::LB_ALPHABETIC` int

`IntlChar::LB_BREAK_BOTH` int

`IntlChar::LB_BREAK_AFTER` int

`IntlChar::LB_BREAK_BEFORE` int

`IntlChar::LB_MANDATORY_BREAK` int

`IntlChar::LB_CONTINGENT_BREAK` int

`IntlChar::LB_CLOSE_PUNCTUATION` int

`IntlChar::LB_COMBINING_MARK` int

`IntlChar::LB_CARRIAGE_RETURN` int

`IntlChar::LB_EXCLAMATION` int

`IntlChar::LB_GLUE` int

`IntlChar::LB_HYPHEN` int

`IntlChar::LB_IDEOGRAPHIC` int

`IntlChar::LB_INSEPARABLE` int

`IntlChar::LB_INSEPERABLE` int

`IntlChar::LB_INFIX_NUMERIC` int

`IntlChar::LB_LINE_FEED` int

`IntlChar::LB_NONSTARTER` int

`IntlChar::LB_NUMERIC` int

`IntlChar::LB_OPEN_PUNCTUATION` int

`IntlChar::LB_POSTFIX_NUMERIC` int

`IntlChar::LB_PREFIX_NUMERIC` int

`IntlChar::LB_QUOTATION` int

`IntlChar::LB_COMPLEX_CONTEXT` int

`IntlChar::LB_SURROGATE` int

`IntlChar::LB_SPACE` int

`IntlChar::LB_BREAK_SYMBOLS` int

`IntlChar::LB_ZWSPACE` int

`IntlChar::LB_NEXT_LINE` int

`IntlChar::LB_WORD_JOINER` int

`IntlChar::LB_H2` int

`IntlChar::LB_H3` int

`IntlChar::LB_JL` int

`IntlChar::LB_JT` int

`IntlChar::LB_JV` int

`IntlChar::LB_CLOSE_PARENTHESIS` int

`IntlChar::LB_CONDITIONAL_JAPANESE_STARTER` int

`IntlChar::LB_HEBREW_LETTER` int

`IntlChar::LB_REGIONAL_INDICATOR` int

`IntlChar::LB_COUNT` int

`IntlChar::NT_NONE` int

`IntlChar::NT_DECIMAL` int

`IntlChar::NT_DIGIT` int

`IntlChar::NT_NUMERIC` int

`IntlChar::NT_COUNT` int

`IntlChar::HST_NOT_APPLICABLE` int

`IntlChar::HST_LEADING_JAMO` int

`IntlChar::HST_VOWEL_JAMO` int

`IntlChar::HST_TRAILING_JAMO` int

`IntlChar::HST_LV_SYLLABLE` int

`IntlChar::HST_LVT_SYLLABLE` int

`IntlChar::HST_COUNT` int

`IntlChar::FOLD_CASE_DEFAULT` int

`IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I` int

## Changelog

Version | Description
--- | ---
8.4.0 | Added `IntlChar::PROPERTY_IDS_UNARY_OPERATOR`, `IntlChar::PROPERTY_ID_COMPAT_MATH_START`, `IntlChar::PROPERTY_ID_COMPAT_MATH_CONTINUE`.
8.4.0 | The class constants are now typed.
7.0.6 | The `IntlChar::NO_NUMERIC_VALUE` constant was added.

# IntlChar::charAge

(PHP 7, PHP 8)

IntlChar::charAge — Get the "age" of the code point

### Description

public static IntlChar::charAge(int|string `$codepoint`): ?array

Gets the "age" of the code point.

The "age" is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character. This can be useful to avoid emitting code points to receiving processes that do not accept newer characters.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

The Unicode version number, as an array. For example, version 1.3.31.2 would be represented as `[1, 3, 31, 2]`. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charage("\u{2603}"));
var_dump(IntlChar::charage("\u{1F576}"));
?>`

The above example will output:

    array(4) {
      [0]=>
      int(1)
      [1]=>
      int(1)
      [2]=>
      int(0)
      [3]=>
      int(0)
    }
    array(4) {
      [0]=>
      int(7)
      [1]=>
      int(0)
      [2]=>
      int(0)
      [3]=>
      int(0)
    }

### See Also

- IntlChar::getUnicodeVersion() - Get the Unicode version
- IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
- IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point

# IntlChar::charDigitValue

(PHP 7, PHP 8)

IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character

### Description

public static IntlChar::charDigitValue(int|string `$codepoint`): ?int

Returns the decimal digit value of a decimal digit character.

Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

The decimal digit value of `codepoint`, or `-1` if it is not a decimal digit character. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charDigitValue("1"));
var_dump(IntlChar::charDigitValue("\u{0662}"));
var_dump(IntlChar::charDigitValue("\u{0E53}"));
?>`

The above example will output:

    int(1)
    int(2)
    int(3)

### See Also

- IntlChar::getNumericValue() - Get the numeric value for a Unicode code point

# IntlChar::charDirection

(PHP 7, PHP 8)

IntlChar::charDirection — Get bidirectional category value for a code point

### Description

public static IntlChar::charDirection(int|string `$codepoint`): ?int

Returns the bidirectional category value for the code point, which is used in the » Unicode bidirectional algorithm (UAX #9).

> Note:

> Some unassigned code points have bidi values of R or AL because they are in blocks that are reserved for Right-To-Left scripts.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

The bidirectional category value; one of the following constants:

- `IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT`
- `IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT`
- `IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER`
- `IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR`
- `IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR`
- `IntlChar::CHAR_DIRECTION_ARABIC_NUMBER`
- `IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR`
- `IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR`
- `IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR`
- `IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL`
- `IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL`
- `IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING`
- `IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE`
- `IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC`
- `IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING`
- `IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE`
- `IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT`
- `IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK`
- `IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL`
- `IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE`
- `IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE`
- `IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE`
- `IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE`
- `IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT`

Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charDirection("A") === IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT);
var_dump(IntlChar::charDirection("\u{05E9}") === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::charDirection("+") === IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR);
var_dump(IntlChar::charDirection(".") === IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR);
?>`

The above example will output:

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

# IntlChar::charFromName

(PHP 7, PHP 8)

IntlChar::charFromName — Find Unicode character by name and return its code point value

### Description

public static IntlChar::charFromName(string `$name`, int `$type` = `IntlChar::UNICODE_CHAR_NAME`): ?int

Finds a Unicode character by its name and returns its code point value.

The name is matched exactly and completely. If the name does not correspond to a code point, `null` is returned.

A Unicode 1.0 name is matched only if it differs from the modern name. Unicode names are all uppercase. Extended names are lowercase followed by an uppercase hexadecimal number, and within angle brackets.

### Parameters

`name`

  Full name of the Unicode character.

`type`

  Which set of names to use for the lookup. Can be any of these constants:

  - `IntlChar::UNICODE_CHAR_NAME` (default)
  - `IntlChar::UNICODE_10_CHAR_NAME`
  - `IntlChar::EXTENDED_CHAR_NAME`
  - `IntlChar::CHAR_NAME_ALIAS`
  - `IntlChar::CHAR_NAME_CHOICE_COUNT`

### Return Values

The Unicode value of the code point with the given name (as an int), or `null` if there is no such code point.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charFromName("LATIN CAPITAL LETTER A"));
var_dump(IntlChar::charFromName("SNOWMAN"));
var_dump(IntlChar::charFromName("RECYCLING SYMBOL FOR TYPE-1 PLASTICS"));
var_dump(IntlChar::charFromName("A RANDOM STRING WHICH DOESN'T CORRESPOND TO ANY UNICODE CHARACTER"));
?>`

The above example will output:

    int(65)
    int(9731)
    int(9843)
    NULL

### See Also

- IntlChar::charName() - Retrieve the name of a Unicode character
- IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

# IntlChar::charMirror

(PHP 7, PHP 8)

IntlChar::charMirror — Get the "mirror-image" character for a code point

### Description

public static IntlChar::charMirror(int|string `$codepoint`): int|string|null

Maps the specified character to a "mirror-image" character.

For characters with the Bidi_Mirrored property, implementations sometimes need a "poor man's" mapping to another Unicode character (code point) such that the default glyph may serve as the mirror-image of the default glyph of the specified character. This is useful for text conversion to and from codepages with visual order, and for displays without glyph selection capabilities.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns another Unicode code point that may serve as a mirror-image substitute, or `codepoint` itself if there is no such mapping or `codepoint` does not have the Bidi_Mirrored property.

The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charMirror("A"));
var_dump(IntlChar::charMirror("<"));
var_dump(IntlChar::charMirror("("));
?>`

The above example will output:

    string(1) "A"
    string(1) ">"
    string(2) ")"

### See Also

- IntlChar::isMirrored() - Check if code point has the Bidi_Mirrored property
- `IntlChar::PROPERTY_BIDI_MIRRORED`

# IntlChar::charName

(PHP 7, PHP 8)

IntlChar::charName — Retrieve the name of a Unicode character

### Description

public static IntlChar::charName(int|string `$codepoint`, int `$type` = `IntlChar::UNICODE_CHAR_NAME`): ?string

Retrieves the name of a Unicode character.

Depending on `type`, the resulting character name is the "modern" name or the name that was defined in Unicode version 1.0. The name contains only "invariant" characters like A-Z, 0-9, space, and '-'. Unicode 1.0 names are only retrieved if they are different from the modern names and if ICU contains the data for them.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

`type`

  Which set of names to use for the lookup. Can be any of these constants:

  - `IntlChar::UNICODE_CHAR_NAME` (default)
  - `IntlChar::UNICODE_10_CHAR_NAME`
  - `IntlChar::EXTENDED_CHAR_NAME`
  - `IntlChar::CHAR_NAME_ALIAS`
  - `IntlChar::CHAR_NAME_CHOICE_COUNT`

### Return Values

The corresponding name, or an empty string if there is no name for this character, or `null` if there is no such code point.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charName("."));
var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME));
var_dump(IntlChar::charName("\u{2603}"));
var_dump(IntlChar::charName("\u{0000}"));
?>`

The above example will output:

    string(9) "FULL STOP"
    string(9) "FULL STOP"
    string(7) "SNOWMAN"
    string(0) ""

### See Also

- IntlChar::charFromName() - Find Unicode character by name and return its code point value
- IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

# IntlChar::charType

(PHP 7, PHP 8)

IntlChar::charType — Get the general category value for a code point

### Description

public static IntlChar::charType(int|string `$codepoint`): ?int

Returns the general category value for the code point.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the general category type, which may be one of the following constants:

- `IntlChar::CHAR_CATEGORY_UNASSIGNED`
- `IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES`
- `IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER`
- `IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER`
- `IntlChar::CHAR_CATEGORY_TITLECASE_LETTER`
- `IntlChar::CHAR_CATEGORY_MODIFIER_LETTER`
- `IntlChar::CHAR_CATEGORY_OTHER_LETTER`
- `IntlChar::CHAR_CATEGORY_NON_SPACING_MARK`
- `IntlChar::CHAR_CATEGORY_ENCLOSING_MARK`
- `IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK`
- `IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER`
- `IntlChar::CHAR_CATEGORY_LETTER_NUMBER`
- `IntlChar::CHAR_CATEGORY_OTHER_NUMBER`
- `IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR`
- `IntlChar::CHAR_CATEGORY_LINE_SEPARATOR`
- `IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR`
- `IntlChar::CHAR_CATEGORY_CONTROL_CHAR`
- `IntlChar::CHAR_CATEGORY_FORMAT_CHAR`
- `IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR`
- `IntlChar::CHAR_CATEGORY_SURROGATE`
- `IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_START_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_END_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_MATH_SYMBOL`
- `IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL`
- `IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL`
- `IntlChar::CHAR_CATEGORY_OTHER_SYMBOL`
- `IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION`
- `IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT`

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::charType("A") === IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER);
var_dump(IntlChar::charType(".") === IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION);
var_dump(IntlChar::charType("\t") === IntlChar::CHAR_CATEGORY_CONTROL_CHAR);
var_dump(IntlChar::charType("\u{2603}") === IntlChar::CHAR_CATEGORY_OTHER_SYMBOL);
var_dump(IntlChar::charType("multiple chars") === null);
?>`

The above example will output:

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

# IntlChar::chr

(PHP 7, PHP 8)

IntlChar::chr — Return Unicode character by code point value

### Description

public static IntlChar::chr(int|string `$codepoint`): ?string

Returns a string containing the character specified by the Unicode code point value.

This method complements IntlChar::ord().

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

A string containing the single character specified by the Unicode code point value, or `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
$values = ["A", 63, 123, 9731];
foreach ($values as $value) {
var_dump(IntlChar::chr($value));
}
?>`

The above example will output:

    string(1) "A"
    string(1) "?"
    string(1) "{"
    string(3) "☃"

### See Also

- IntlChar::ord() - Return Unicode code point value of character
- mb_chr() - Return character by Unicode code point value
- chr() - Generate a single-byte string from a number

# IntlChar::digit

(PHP 7, PHP 8)

IntlChar::digit — Get the decimal digit value of a code point for a given radix

### Description

public static IntlChar::digit(int|string `$codepoint`, int `$base` = 10): int|false|null

Returns the decimal digit value of the code point in the specified radix.

If the radix is not in the range `2<=radix<=36` or if the value of `codepoint` is not a valid digit in the specified radix, `false` is returned. A character is a valid digit if at least one of the following is true:

- The character has a decimal digit value. Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal. In this case the value is the character's decimal digit value.
- The character is one of the uppercase Latin letters 'A' through 'Z'. In this case the value is c-'A'+10.
- The character is one of the lowercase Latin letters 'a' through 'z'. In this case the value is ch-'a'+10.
- Latin letters from both the ASCII range (0061..007A, 0041..005A) as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) are recognized.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

`base`

  The radix (defaults to `10`).

### Return Values

Returns the numeric value represented by the character in the specified radix, or `false` if there is no value or if the value exceeds the radix. Returns `null` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::digit("0"));
var_dump(IntlChar::digit("3"));
var_dump(IntlChar::digit("A"));
var_dump(IntlChar::digit("A", 16));
?>`

The above example will output:

    int(0)
    int(3)
    bool(false)
    int(10)

### See Also

- IntlChar::forDigit() - Get character representation for a given digit and radix
- IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
- IntlChar::isdigit() - Check if code point is a digit character
- `IntlChar::PROPERTY_NUMERIC_TYPE`

# IntlChar::enumCharNames

(PHP 7, PHP 8)

IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range

### Description

public static IntlChar::enumCharNames(
int|string `$start`,
int|string `$end`,
callable `$callback`,
int `$type` = `IntlChar::UNICODE_CHAR_NAME`
): bool

Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name.

For Unicode 1.0 names, only those are enumerated that differ from the modern names.

### Parameters

`start`

  The first code point in the enumeration range.

`end`

  One more than the last code point in the enumeration range (the first one after the range).

`callback`

  The function that is to be called for each character name. The following three arguments will be passed into it:

  - int `$codepoint` - The numeric code point value
  - int `$nameChoice` - The same value as the `type` parameter below
  - string `$name` - The name of the character
`type`

  Selector for which kind of names to enumerate. Can be any of these constants:

  - `IntlChar::UNICODE_CHAR_NAME` (default)
  - `IntlChar::UNICODE_10_CHAR_NAME`
  - `IntlChar::EXTENDED_CHAR_NAME`
  - `IntlChar::CHAR_NAME_ALIAS`
  - `IntlChar::CHAR_NAME_CHOICE_COUNT`

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | This method now returns `false` on failure; previously it returns `null`.

### Examples

Example #1 Enumerating over a sample range of code points

`<?php
IntlChar::enumCharNames(0x2600, 0x2610, function($codepoint, $nameChoice, $name) {
printf("U+%04x %s\n", $codepoint, $name);
});
?>`

The above example will output:

    U+2600 BLACK SUN WITH RAYS
    U+2601 CLOUD
    U+2602 UMBRELLA
    U+2603 SNOWMAN
    U+2604 COMET
    U+2605 BLACK STAR
    U+2606 WHITE STAR
    U+2607 LIGHTNING
    U+2608 THUNDERSTORM
    U+2609 SUN
    U+260a ASCENDING NODE
    U+260b DESCENDING NODE
    U+260c CONJUNCTION
    U+260d OPPOSITION
    U+260e BLACK TELEPHONE
    U+260f WHITE TELEPHONE

### See Also

- IntlChar::charName() - Retrieve the name of a Unicode character
- IntlChar::charFromName() - Find Unicode character by name and return its code point value

# IntlChar::enumCharTypes

(PHP 7, PHP 8)

IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories

### Description

public static IntlChar::enumCharTypes(callable `$callback`): void

Enumerates efficiently all code points with their Unicode general categories. This is useful for building data structures, for enumerating all assigned code points, etc.

For each contiguous range of code points with a given general category ("character type"), the `callback` function is called. Adjacent ranges have different types. The Unicode Standard guarantees that the numeric value of the type is 0..31.

### Parameters

`callback`

  The function that is to be called for each contiguous range of code points with the same general category. The following three arguments will be passed into it:

  - int `$start` - The starting code point of the range
  - int `$end` - The ending code point of the range
  - int `$name` - The category type (one of the `IntlChar::CHAR_CATEGORY_*` constants)

### Return Values

No value is returned.

### Examples

Example #1 Enumerating over a sample range of code points

`<?php
IntlChar::enumCharTypes(function($start, $end, $type) {
printf("U+%04x through U+%04x are in category %d\n", $start, $end, $type);
});
?>`

The above example will output:

    U+0000 through U+0020 are in category 15
    U+0020 through U+0021 are in category 12
    U+0021 through U+0024 are in category 23
    U+0024 through U+0025 are in category 25
    U+0025 through U+0028 are in category 23
    U+0028 through U+0029 are in category 20
    U+0029 through U+002a are in category 21
    U+002a through U+002b are in category 23
    U+002b through U+002c are in category 24
    U+002c through U+002d are in category 23
    U+002d through U+002e are in category 19
    U+002e through U+0030 are in category 23
    U+0030 through U+003a are in category 9
    ...

# IntlChar::foldCase

(PHP 7, PHP 8)

IntlChar::foldCase — Perform case folding on a code point

### Description

public static IntlChar::foldCase(int|string `$codepoint`, int `$options` = `IntlChar::FOLD_CASE_DEFAULT`): int|string|null

The given character is mapped to its case folding equivalent; if the character has no case folding equivalent, the character itself is returned.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

`options`

  Either `IntlChar::FOLD_CASE_DEFAULT` (default) or `IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I`.

### Return Values

Returns the Simple_Case_Folding of the code point, if any; otherwise the code point itself on success, or `null` on failure.

# IntlChar::forDigit

(PHP 7, PHP 8)

IntlChar::forDigit — Get character representation for a given digit and radix

### Description

public static IntlChar::forDigit(int `$digit`, int `$base` = 10): int

Determines the character representation for a specific digit in the specified radix.

If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character (`U+0000`) is returned.

The radix argument is valid if it is greater than or equal to `2` and less than or equal to `36`. The digit argument is valid if `0 <= digit < radix`.

If the digit is less than `10`, then '0' + digit is returned. Otherwise, the value 'a' + digit - 10 is returned.

### Parameters

`digit`

  The number to convert to a character.

`base`

  The radix (defaults to `10`).

### Return Values

The character representation (as a int) of the specified digit in the specified radix.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::forDigit(0));
var_dump(IntlChar::forDigit(3));
var_dump(IntlChar::forDigit(3, 10));
var_dump(IntlChar::forDigit(10));
var_dump(IntlChar::forDigit(10, 16));
?>`

The above example will output:

    int(48)
    int(51)
    int(51)
    int(0)
    int(97)

### See Also

- IntlChar::digit() - Get the decimal digit value of a code point for a given radix
- IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
- IntlChar::isdigit() - Check if code point is a digit character
- `IntlChar::PROPERTY_NUMERIC_TYPE`

# IntlChar::getBidiPairedBracket

(PHP 7, PHP 8)

IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point

### Description

public static IntlChar::getBidiPairedBracket(int|string `$codepoint`): int|string|null

Maps the specified character to its paired bracket character.

For `IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE !== IntlChar::BPT_NONE`, this is the same as IntlChar::charMirror(). Otherwise `codepoint` itself is returned.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the paired bracket code point, or `codepoint` itself if there is no such mapping. Returns `null` on failure.

The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::getBidiPairedBracket(91));
var_dump(IntlChar::getBidiPairedBracket('['));
?>`

The above example will output:

    int(93)
    string(1) "]"

### Notes

> Note:

> This method is available as of ICU version 52.

### See Also

- IntlChar::charMirror() - Get the "mirror-image" character for a code point
- `IntlChar::PROPERTY_BIDI_PAIRED_BRACKET`
- `IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE`

# IntlChar::getBlockCode

(PHP 7, PHP 8)

IntlChar::getBlockCode — Get the Unicode allocation block containing a code point

### Description

public static IntlChar::getBlockCode(int|string `$codepoint`): ?int

Returns the Unicode allocation block that contains the character.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the block value for `codepoint`. See the `IntlChar::BLOCK_CODE_*` constants for possible return values. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::getBlockCode("A") === IntlChar::BLOCK_CODE_BASIC_LATIN);
var_dump(IntlChar::getBlockCode("Φ") === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getBlockCode("\u{2603}") === IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS);
?>`

The above example will output:

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

# IntlChar::getCombiningClass

(PHP 7, PHP 8)

IntlChar::getCombiningClass — Get the combining class of a code point

### Description

public static IntlChar::getCombiningClass(int|string `$codepoint`): ?int

Returns the combining class of the code point.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the combining class of the character. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::getCombiningClass("A"));
var_dump(IntlChar::getCombiningClass("\u{0334}"));
var_dump(IntlChar::getCombiningClass("\u{0358}"));
?>`

The above example will output:

    int(0)
    int(1)
    int(232)

# IntlChar::getFC_NFKC_Closure

(PHP 7, PHP 8)

IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point

### Description

public static IntlChar::getFC_NFKC_Closure(int|string `$codepoint`): string|false|null

Gets the FC_NFKC_Closure property string for a character.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the FC_NFKC_Closure property string for the `codepoint`, or an empty string if there is none. Returns `null` or `false` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::getFC_NFKC_Closure("\u{2121}"));
var_dump(IntlChar::getFC_NFKC_Closure("\u{1D2D}"));
?>`

The above example will output:

    string(3) "tel"
    string(2) "æ"

# IntlChar::getIntPropertyMaxValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property

### Description

public static IntlChar::getIntPropertyMaxValue(int `$property`): int

Gets the maximum value for an enumerated/integer/binary Unicode property.

### Parameters

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

### Return Values

The maximum value returned by IntlChar::getIntPropertyValue() for a Unicode property. `<=0` if the property selector is out of range.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMaxValue(999999999)); // Some made-up value
?>`

The above example will output:

    int(22)
    int(166)
    int(1)
    int(-1)

### See Also

- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
- IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
- IntlChar::getUnicodeVersion() - Get the Unicode version

# IntlChar::getIntPropertyMinValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property

### Description

public static IntlChar::getIntPropertyMinValue(int `$property`): int

Gets the minimum value for an enumerated/integer/binary Unicode property.

### Parameters

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

### Return Values

The minimum value returned by IntlChar::getIntPropertyValue() for a Unicode property. `0` if the property selector is out of range.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMinValue(999999999)); // Some made-up value
?>`

The above example will output:

    int(0)
    int(0)
    int(0)
    int(0)

### See Also

- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
- IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
- IntlChar::getUnicodeVersion() - Get the Unicode version

# IntlChar::getIntPropertyValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point

### Description

public static IntlChar::getIntPropertyValue(int|string `$codepoint`, int `$property`): ?int

Gets the property value for an enumerated or integer Unicode property for a code point. Also returns binary and mask property values.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

### Return Values

Returns the numeric value that is directly the property value or, for enumerated properties, corresponds to the numeric value of the enumerated constant of the respective property value enumeration type. Returns `null` on failure.

Returns `0` or `1` (for `false`/`true`) for binary Unicode properties.

Returns a bit-mask for mask properties.

Returns `0` if `property` is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getIntPropertyValue("A", IntlChar::PROPERTY_ALPHABETIC) === 1);
var_dump(IntlChar::getIntPropertyValue("[", IntlChar::PROPERTY_BIDI_MIRRORED) === 1);
var_dump(IntlChar::getIntPropertyValue("Φ", IntlChar::PROPERTY_BLOCK) === IntlChar::BLOCK_CODE_GREEK);
?>`

The above example will output:

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

### See Also

- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
- IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
- IntlChar::getUnicodeVersion() - Get the Unicode version

# IntlChar::getNumericValue

(PHP 7, PHP 8)

IntlChar::getNumericValue — Get the numeric value for a Unicode code point

### Description

public static IntlChar::getNumericValue(int|string `$codepoint`): ?float

Gets the numeric value for a Unicode code point as defined in the Unicode Character Database.

For characters without any numeric values in the Unicode Character Database, this function will return `IntlChar::NO_NUMERIC_VALUE`.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Numeric value of `codepoint`, or `IntlChar::NO_NUMERIC_VALUE` if none is defined. This constant was added in PHP 7.0.6, prior to this version the literal value (float)`-123456789` may be used instead. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::getNumericValue("4"));
var_dump(IntlChar::getNumericValue("x"));
var_dump(IntlChar::getNumericValue("\u{216C}"));
?>`

The above example will output:

    float(4)
    float(-123456789)
    float(50)

# IntlChar::getPropertyEnum

(PHP 7, PHP 8)

IntlChar::getPropertyEnum — Get the property constant value for a given property name

### Description

public static IntlChar::getPropertyEnum(string `$alias`): int

Returns the property constant value for a given property name, as specified in the Unicode database file PropertyAliases.txt. Short, long, and any other variants are recognized.

In addition, this function maps the synthetic names "gcm" / "General_Category_Mask" to the property `IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`. These names are not in PropertyAliases.txt.

This function complements IntlChar::getPropertyName().

### Parameters

`alias`

  The property name to be matched. The name is compared using "loose matching" as described in PropertyAliases.txt.

### Return Values

Returns an `IntlChar::PROPERTY_` constant value, or `IntlChar::PROPERTY_INVALID_CODE` if the given name does not match any property.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getPropertyEnum('Bidi_Class') === IntlChar::PROPERTY_BIDI_CLASS);
var_dump(IntlChar::getPropertyEnum('script') === IntlChar::PROPERTY_SCRIPT);
var_dump(IntlChar::getPropertyEnum('IDEOGRAPHIC') === IntlChar::PROPERTY_IDEOGRAPHIC);
var_dump(IntlChar::getPropertyEnum('Some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
?>`

The above example will output:

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

### See Also

- IntlChar::getPropertyName() - Get the Unicode name for a property

# IntlChar::getPropertyName

(PHP 7, PHP 8)

IntlChar::getPropertyName — Get the Unicode name for a property

### Description

public static IntlChar::getPropertyName(int `$property`, int `$type` = `IntlChar::LONG_PROPERTY_NAME`): string|false

Returns the Unicode name for a given property, as given in the Unicode database file PropertyAliases.txt.

In addition, this function maps the property `IntlChar::PROPERTY_GENERAL_CATEGORY_MASK` to the synthetic names "gcm" / "General_Category_Mask". These names are not in PropertyAliases.txt.

This function complements IntlChar::getPropertyEnum().

### Parameters

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

  `IntlChar::PROPERTY_INVALID_CODE` should not be used. Also, if `property` is out of range, `false` is returned.

`type`

  Selector for which name to get. If out of range, `false` is returned.

  All properties have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to `IntlChar::LONG_PROPERTY_NAME`.

### Return Values

Returns the name, or `false` if either the `property` or the `type` is out of range.

If a given `type` returns `false`, then all larger values of `type` will return `false`, with one exception: if `false` is returned for `IntlChar::SHORT_PROPERTY_NAME`, then `IntlChar::LONG_PROPERTY_NAME` (and higher) may still return a non-`false` value.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME + 1));
?>`

The above example will output:

    string(10) "Bidi_Class"
    string(2) "bc"
    string(10) "Bidi_Class"
    bool(false)

### See Also

- IntlChar::getPropertyEnum() - Get the property constant value for a given property name

# IntlChar::getPropertyValueEnum

(PHP 7, PHP 8)

IntlChar::getPropertyValueEnum — Get the property value for a given value name

### Description

public static IntlChar::getPropertyValueEnum(int `$property`, string `$name`): int

Returns the property value integer for a given value name, as specified in the Unicode database file PropertyValueAliases.txt. Short, long, and any other variants are recognized.

> Note:

> Some of the names in PropertyValueAliases.txt will only be recognized with `IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`, not `IntlChar::PROPERTY_GENERAL_CATEGORY`. These include:

> - "C" / "Other"
> - "L" / "Letter"
> - "LC" / "Cased_Letter"
> - "M" / "Mark"
> - "N" / "Number"
> - "P" / "Punctuation"
> - "S" / "Symbol"
> - "Z" / "Separator"

### Parameters

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

  If out of range, or this method doesn't work with the given value, `IntlChar::PROPERTY_INVALID_CODE` is returned.

`name`

  The value name to be matched. The name is compared using "loose matching" as described in PropertyValueAliases.txt.

### Return Values

Returns the corresponding value integer, or `IntlChar::PROPERTY_INVALID_CODE` if the given name does not match any value of the given property, or if the property is invalid.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BLOCK, 'greek') === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'RIGHT_TO_LEFT') === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
var_dump(IntlChar::getPropertyValueEnum(123456789, 'RIGHT_TO_LEFT') === IntlChar::PROPERTY_INVALID_CODE);
?>`

The above example will output:

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

# IntlChar::getPropertyValueName

(PHP 7, PHP 8)

IntlChar::getPropertyValueName — Get the Unicode name for a property value

### Description

public static IntlChar::getPropertyValueName(int `$property`, int `$value`, int `$type` = `IntlChar::LONG_PROPERTY_NAME`): string|false

Returns the Unicode name for a given property value, as given in the Unicode database file PropertyValueAliases.txt.

> Note:

> Some of the names in PropertyValueAliases.txt can only be retrieved using `IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`, not `IntlChar::PROPERTY_GENERAL_CATEGORY`. These include:

> - "C" / "Other"
> - "L" / "Letter"
> - "LC" / "Cased_Letter"
> - "M" / "Mark"
> - "N" / "Number"
> - "P" / "Punctuation"
> - "S" / "Symbol"
> - "Z" / "Separator"

### Parameters

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

  If out of range, or this method doesn't work with the given value, `false` is returned.

`value`

  Selector for a value for the given property. If out of range, `false` is returned.

  In general, valid values range from `0` up to some maximum. There are a couple exceptions:

  - `IntlChar::PROPERTY_BLOCK` values begin at the non-zero value `IntlChar::BLOCK_CODE_BASIC_LATIN`
  - `IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS` values are not contiguous and range from 0..240.
`type`

  Selector for which name to get. If out of range, `false` is returned.

  All values have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to `IntlChar::LONG_PROPERTY_NAME`.

### Return Values

Returns the name, or `false` if either the `property` or the `type` is out of range. Returns `null` on failure.

If a given `type` returns `false`, then all larger values of `type` will return `false`, with one exception: if `false` is returned for `IntlChar::SHORT_PROPERTY_NAME`, then `IntlChar::LONG_PROPERTY_NAME` (and higher) may still return a non-`false` value.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME + 1));
?>`

The above example will output:

    string(16) "Greek_And_Coptic"
    string(5) "Greek"
    string(16) "Greek_And_Coptic"
    bool(false)

# IntlChar::getUnicodeVersion

(PHP 7, PHP 8)

IntlChar::getUnicodeVersion — Get the Unicode version

### Description

public static IntlChar::getUnicodeVersion(): array

Gets the Unicode version information.

The version array is filled in with the version information for the Unicode standard that is currently used by ICU. For example, Unicode version 3.1.1 is represented as an array with the values `[3, 1, 1, 0]`.

### Parameters

This function has no parameters.

### Return Values

An array containing the Unicode version number.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::getUnicodeVersion());
?>`

The above example will output:

    array(4) {
      [0]=>
      int(7)
      [1]=>
      int(0)
      [2]=>
      int(0)
      [3]=>
      int(0)
    }

### See Also

- IntlChar::charAge() - Get the "age" of the code point

# IntlChar::hasBinaryProperty

(PHP 7, PHP 8)

IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point

### Description

public static IntlChar::hasBinaryProperty(int|string `$codepoint`, int `$property`): ?bool

Checks a binary Unicode property for a code point.

Unicode, especially in version 3.2, defines many more properties than the original set in UnicodeData.txt.

The properties APIs are intended to reflect Unicode properties as defined in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). For details about the properties see » http://www.unicode.org/ucd/. For names of Unicode properties see the UCD file PropertyAliases.txt.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

`property`

  The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants).

### Return Values

Returns `true` or `false` according to the binary Unicode property value for `codepoint`. Also `false` if `property` is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point. Returns `null` on failure.

### Examples

Example #1 Testing different properties

`<?php
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_BIDI_MIRRORED));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_BIDI_MIRRORED));
?>`

The above example will output:

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

### See Also

- IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
- IntlChar::getUnicodeVersion() - Get the Unicode version

# IntlChar::isalnum

(PHP 7, PHP 8)

IntlChar::isalnum — Check if code point is an alphanumeric character

### Description

public static IntlChar::isalnum(int|string `$codepoint`): ?bool

Determines whether the specified code point is an alphanumeric character (letter or digit). `true` for characters with general categories "L" (letters) and "Nd" (decimal digit numbers).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is an alphanumeric character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isalnum("A"));
var_dump(IntlChar::isalnum("1"));
var_dump(IntlChar::isalnum("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isdigit() - Check if code point is a digit character
- ctype_alnum() - Check for alphanumeric character(s)

# IntlChar::isalpha

(PHP 7, PHP 8)

IntlChar::isalpha — Check if code point is a letter character

### Description

public static IntlChar::isalpha(int|string `$codepoint`): ?bool

Determines whether the specified code point is a letter character. `true` for general categories "L" (letters).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a letter character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isalpha("A"));
var_dump(IntlChar::isalpha("1"));
var_dump(IntlChar::isalpha("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalnum() - Check if code point is an alphanumeric character
- IntlChar::isdigit() - Check if code point is a digit character
- ctype_alpha() - Check for alphabetic character(s)

# IntlChar::isbase

(PHP 7, PHP 8)

IntlChar::isbase — Check if code point is a base character

### Description

public static IntlChar::isbase(int|string `$codepoint`): ?bool

Determines whether the specified code point is a base character. `true` for general categories "L" (letters), "N" (numbers), "Mc" (spacing combining marks), and "Me" (enclosing marks).

> Note:

> This is different from the Unicode definition in chapter 3.5, conformance clause D13, which defines base characters to be all characters (not Cn) that do not graphically combine with preceding characters (M) and that are neither control (Cc) or format (Cf) characters.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a base character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isbase("A"));
var_dump(IntlChar::isbase("1"));
var_dump(IntlChar::isbase("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isdigit() - Check if code point is a digit character

# IntlChar::isblank

(PHP 7, PHP 8)

IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character

### Description

public static IntlChar::isblank(int|string `$codepoint`): ?bool

Determines whether the specified code point is a "blank" or "horizontal space", a character that visibly separates words on a line.

The following are equivalent definitions:

- `true` for Unicode White_Space characters except for "vertical space controls" where "vertical space controls" are the following characters: U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS)
- `true` for U+0009 (TAB) and characters with general category "Zs" (space separators) except Zero Width Space (ZWSP, U+200B).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is either a "blank" or "horizontal space" character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isblank("A"));
var_dump(IntlChar::isblank(" "));
var_dump(IntlChar::isblank("\t"));
?>`

The above example will output:

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

### See Also

- IntlChar::isspace() - Check if code point is a space character
- IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
- IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property
- IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU

# IntlChar::iscntrl

(PHP 7, PHP 8)

IntlChar::iscntrl — Check if code point is a control character

### Description

public static IntlChar::iscntrl(int|string `$codepoint`): ?bool

Determines whether the specified code point is a control character.

A control character is one of the following:

- ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f)
- `IntlChar::CHAR_CATEGORY_CONTROL_CHAR` (Cc)
- `IntlChar::CHAR_CATEGORY_FORMAT_CHAR` (Cf)
- `IntlChar::CHAR_CATEGORY_LINE_SEPARATOR` (Zl)
- `IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR` (Zp)

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a control character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::iscntrl("A"));
var_dump(IntlChar::iscntrl(" "));
var_dump(IntlChar::iscntrl("\n"));
var_dump(IntlChar::iscntrl("\u{200e}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isprint() - Check if code point is a printable character
- `IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`
- ctype_cntrl() - Check for control character(s)

# IntlChar::isdefined

(PHP 7, PHP 8)

IntlChar::isdefined — Check whether the code point is defined

### Description

public static IntlChar::isdefined(int|string `$codepoint`): ?bool

Determines whether the specified code point is "defined", which usually means that it is assigned a character.

`true` for general categories other than "Cn" (other, not assigned).

> Note:

> Note that non-character code points (e.g., U+FDD0) are not "defined" (they are Cn), but surrogate code points are "defined" (Cs).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a defined character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isdefined("A"));
var_dump(IntlChar::isdefined(" "));
var_dump(IntlChar::isdefined("\u{FDD0}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isdigit() - Check if code point is a digit character
- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isalnum() - Check if code point is an alphanumeric character
- IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
- IntlChar::islower() - Check if code point is a lowercase letter
- IntlChar::istitle() - Check if code point is a titlecase letter

# IntlChar::isdigit

(PHP 7, PHP 8)

IntlChar::isdigit — Check if code point is a digit character

### Description

public static IntlChar::isdigit(int|string `$codepoint`): ?bool

Determines whether the specified code point is a digit character.

`true` for characters with general category "Nd" (decimal digit numbers). Beginning with Unicode 4, this is the same as testing for the Numeric_Type of Decimal.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a digit character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isdigit("A"));
var_dump(IntlChar::isdigit("1"));
var_dump(IntlChar::isdigit("\t"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isalnum() - Check if code point is an alphanumeric character
- IntlChar::isxdigit() - Check if code point is a hexadecimal digit
- ctype_digit() - Check for numeric character(s)

# IntlChar::isgraph

(PHP 7, PHP 8)

IntlChar::isgraph — Check if code point is a graphic character

### Description

public static IntlChar::isgraph(int|string `$codepoint`): ?bool

Determines whether the specified code point is a "graphic" character (printable, excluding spaces).

`true` for all characters except those with general categories "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates), "Cn" (unassigned), and "Z" (separators).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a "graphic" character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isgraph("A"));
var_dump(IntlChar::isgraph("1"));
var_dump(IntlChar::isgraph("\u{2603}"));
var_dump(IntlChar::isgraph("\n"));
?>`

The above example will output:

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

### See Also

- ctype_graph() - Check for any printable character(s) except space

# IntlChar::isIDIgnorable

(PHP 7, PHP 8)

IntlChar::isIDIgnorable — Check if code point is an ignorable character

### Description

public static IntlChar::isIDIgnorable(int|string `$codepoint`): ?bool

Determines if the specified character should be regarded as an ignorable character in an identifier.

`true` for characters with general category "Cf" (format controls) as well as non-whitespace ISO controls (U+0000..U+0008, U+000E..U+001B, U+007F..U+009F).

> Note:

> Note that Unicode just recommends to ignore Cf (format controls).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is ignorable in identifiers, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isIDIgnorable("A"));
var_dump(IntlChar::isIDIgnorable(" "));
var_dump(IntlChar::isIDIgnorable("\u{007F}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
- IntlChar::isIDPart() - Check if code point is permissible in an identifier
- `IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`

# IntlChar::isIDPart

(PHP 7, PHP 8)

IntlChar::isIDPart — Check if code point is permissible in an identifier

### Description

public static IntlChar::isIDPart(int|string `$codepoint`): ?bool

Determines if the specified character is permissible in an identifier.

`true` for characters with general categories "L" (letters), "Nl" (letter numbers), "Nd" (decimal digits), "Mc" and "Mn" (combining marks), "Pc" (connecting punctuation), and u_isIDIgnorable(c).

> Note:

> This is almost the same as Unicode's ID_Continue (`IntlChar::PROPERTY_ID_CONTINUE`) except that Unicode recommends to ignore Cf which is less than IntlChar::isIDIgnorable().

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is the code point may occur in an identifier, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isIDPart("A"));
var_dump(IntlChar::isIDPart("$"));
var_dump(IntlChar::isIDPart("\n"));
var_dump(IntlChar::isIDPart("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isIDIgnorable() - Check if code point is an ignorable character
- IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
- `IntlChar::PROPERTY_ID_CONTINUE`

# IntlChar::isIDStart

(PHP 7, PHP 8)

IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier

### Description

public static IntlChar::isIDStart(int|string `$codepoint`): ?bool

Determines if the specified character is permissible as the first character in an identifier according to Unicode (The Unicode Standard, Version 3.0, chapter 5.16 Identifiers).

`true` for characters with general categories "L" (letters) and "Nl" (letter numbers).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` may start an identifier, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isIDStart("A"));
var_dump(IntlChar::isIDStart("$"));
var_dump(IntlChar::isIDStart("\n"));
var_dump(IntlChar::isIDStart("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isIDPart() - Check if code point is permissible in an identifier
- `IntlChar::PROPERTY_ID_START`

# IntlChar::isISOControl

(PHP 7, PHP 8)

IntlChar::isISOControl — Check if code point is an ISO control code

### Description

public static IntlChar::isISOControl(int|string `$codepoint`): ?bool

Determines whether the specified code point is an ISO control code.

`true` for U+0000..U+001f and U+007f..U+009f (general category "Cc").

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is an ISO control code, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isISOControl(" "));
var_dump(IntlChar::isISOControl("\n"));
var_dump(IntlChar::isISOControl("\u{200e}"));
?>`

The above example will output:

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

### See Also

- IntlChar::iscntrl() - Check if code point is a control character

# IntlChar::isJavaIDPart

(PHP 7, PHP 8)

IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier

### Description

public static IntlChar::isJavaIDPart(int|string `$codepoint`): ?bool

Determines if the specified character is permissible in a Java identifier.

In addition to IntlChar::isIDPart(), `true` for characters with general category "Sc" (currency symbols).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` may occur in a Java identifier, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isJavaIDPart("A"));
var_dump(IntlChar::isJavaIDPart("$"));
var_dump(IntlChar::isJavaIDPart("\n"));
var_dump(IntlChar::isJavaIDPart("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isIDIgnorable() - Check if code point is an ignorable character
- IntlChar::isIDPart() - Check if code point is permissible in an identifier
- IntlChar::isJavaIDStart() - Check if code point is permissible as the first character in a Java identifier
- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::isdigit() - Check if code point is a digit character

# IntlChar::isJavaIDStart

(PHP 7, PHP 8)

IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier

### Description

public static IntlChar::isJavaIDStart(int|string `$codepoint`): ?bool

Determines if the specified character is permissible as the start of a Java identifier.

In addition to IntlChar::isIDStart(), `true` for characters with general categories "Sc" (currency symbols) and "Pc" (connecting punctuation).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` may start a Java identifier, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isJavaIDStart("A"));
var_dump(IntlChar::isJavaIDStart("$"));
var_dump(IntlChar::isJavaIDStart("\n"));
var_dump(IntlChar::isJavaIDStart("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
- IntlChar::isJavaIDPart() - Check if code point is permissible in a Java identifier
- IntlChar::isalpha() - Check if code point is a letter character

# IntlChar::isJavaSpaceChar

(PHP 7, PHP 8)

IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java

### Description

public static IntlChar::isJavaSpaceChar(int|string `$codepoint`): ?bool

Determine if the specified code point is a space character according to Java.

`true` for characters with general categories "Z" (separators), which does not include control codes (e.g., TAB or Line Feed).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a space character according to Java, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isJavaSpaceChar("A"));
var_dump(IntlChar::isJavaSpaceChar(" "));
var_dump(IntlChar::isJavaSpaceChar("\n"));
var_dump(IntlChar::isJavaSpaceChar("\t"));
var_dump(IntlChar::isJavaSpaceChar("\u{00A0}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isspace() - Check if code point is a space character
- IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
- IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

# IntlChar::islower

(PHP 7, PHP 8)

IntlChar::islower — Check if code point is a lowercase letter

### Description

public static IntlChar::islower(int|string `$codepoint`): ?bool

Determines whether the specified code point has the general category "Ll" (lowercase letter).

> Note:

> This misses some characters that are also lowercase but have a different general category value. In order to include those, use IntlChar::isULowercase().

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is an Ll lowercase letter, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::islower("A"));
var_dump(IntlChar::islower("a"));
var_dump(IntlChar::islower("Φ"));
var_dump(IntlChar::islower("φ"));
var_dump(IntlChar::islower("1"));
?>`

The above example will output:

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

### See Also

- IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
- IntlChar::istitle() - Check if code point is a titlecase letter
- IntlChar::tolower() - Make Unicode character lowercase
- IntlChar::toupper() - Make Unicode character uppercase
- `IntlChar::PROPERTY_LOWERCASE`
- ctype_lower() - Check for lowercase character(s)

# IntlChar::isMirrored

(PHP 7, PHP 8)

IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property

### Description

public static IntlChar::isMirrored(int|string `$codepoint`): ?bool

Determines whether the code point has the Bidi_Mirrored property.

This property is set for characters that are commonly used in Right-To-Left contexts and need to be displayed with a "mirrored" glyph.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` has the Bidi_Mirrored property, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isMirrored("A"));
var_dump(IntlChar::isMirrored("<"));
var_dump(IntlChar::isMirrored("("));
?>`

The above example will output:

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

### See Also

- IntlChar::charMirror() - Get the "mirror-image" character for a code point
- `IntlChar::PROPERTY_BIDI_MIRRORED`

# IntlChar::isprint

(PHP 7, PHP 8)

IntlChar::isprint — Check if code point is a printable character

### Description

public static IntlChar::isprint(int|string `$codepoint`): ?bool

Determines whether the specified code point is a printable character.

`true` for general categories other than "C" (controls).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a printable character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isprint("A"));
var_dump(IntlChar::isprint(" "));
var_dump(IntlChar::isprint("\n"));
var_dump(IntlChar::isprint("\u{200e}"));
?>`

The above example will output:

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

### See Also

- IntlChar::iscntrl() - Check if code point is a control character
- `IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`
- ctype_print() - Check for printable character(s)

# IntlChar::ispunct

(PHP 7, PHP 8)

IntlChar::ispunct — Check if code point is punctuation character

### Description

public static IntlChar::ispunct(int|string `$codepoint`): ?bool

Determines whether the specified code point is a punctuation character.

`true` for characters with general categories "P" (punctuation).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a punctuation character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::ispunct("."));
var_dump(IntlChar::ispunct(","));
var_dump(IntlChar::ispunct("\n"));
var_dump(IntlChar::ispunct("$"));`

The above example will output:

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

### See Also

- ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

# IntlChar::isspace

(PHP 7, PHP 8)

IntlChar::isspace — Check if code point is a space character

### Description

public static IntlChar::isspace(int|string `$codepoint`): ?bool

Determines if the specified character is a space character or not.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a space character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isspace("A"));
var_dump(IntlChar::isspace(" "));
var_dump(IntlChar::isspace("\n"));
var_dump(IntlChar::isspace("\t"));
var_dump(IntlChar::isspace("\u{00A0}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
- IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
- IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property
- ctype_space() - Check for whitespace character(s)

# IntlChar::istitle

(PHP 7, PHP 8)

IntlChar::istitle — Check if code point is a titlecase letter

### Description

public static IntlChar::istitle(int|string `$codepoint`): ?bool

Determines whether the specified code point is a titlecase letter.

`true` for general category "Lt" (titlecase letter).

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a titlecase letter, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
// Latin Capital Letter Dz with Caron U+01C4
var_dump(IntlChar::istitle("Ǆ"));
// Latin Capital Letter D with Small Letter Z with Caron U+01C5
var_dump(IntlChar::istitle("ǅ"));
// Latin Small Letter Dz with Caron U+01C6
var_dump(IntlChar::istitle("ǆ"));
// Greek Capital Letter Alpha with Prosgegrammeni U+1FBC
var_dump(IntlChar::istitle("ᾼ"));
// Greek Small Letter Alpha with Ypogegrammeni U+1FB3
var_dump(IntlChar::istitle("ᾳ"));
// Greek Capital Letter Alpha U+0391
var_dump(IntlChar::istitle("Α"));
?>`

The above example will output:

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

### See Also

- IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
- IntlChar::islower() - Check if code point is a lowercase letter
- IntlChar::totitle() - Make Unicode character titlecase

# IntlChar::isUAlphabetic

(PHP 7, PHP 8)

IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property

### Description

public static IntlChar::isUAlphabetic(int|string `$codepoint`): ?bool

Check if a code point has the Alphabetic Unicode property.

This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_ALPHABETIC)`

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` has the Alphabetic Unicode property, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isUAlphabetic("A"));
var_dump(IntlChar::isUAlphabetic("1"));
var_dump(IntlChar::isUAlphabetic("\u{2603}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isalpha() - Check if code point is a letter character
- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- `IntlChar::PROPERTY_ALPHABETIC`

# IntlChar::isULowercase

(PHP 7, PHP 8)

IntlChar::isULowercase — Check if code point has the Lowercase Unicode property

### Description

public static IntlChar::isULowercase(int|string `$codepoint`): ?bool

Check if a code point has the Lowercase Unicode property.

This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_LOWERCASE)`

> Note:

> This is different than IntlChar::islower() and will return `true` for more characters.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` has the Lowercase Unicode property, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isULowercase("A"));
var_dump(IntlChar::isULowercase("a"));
var_dump(IntlChar::isULowercase("Φ"));
var_dump(IntlChar::isULowercase("φ"));
var_dump(IntlChar::isULowercase("1"));
?>`

The above example will output:

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

### See Also

- IntlChar::islower() - Check if code point is a lowercase letter
- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- `IntlChar::PROPERTY_LOWERCASE`

# IntlChar::isupper

(PHP 7, PHP 8)

IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)

### Description

public static IntlChar::isupper(int|string `$codepoint`): ?bool

Determines whether the specified code point has the general category "Lu" (uppercase letter).

> Note:

> This misses some characters that are also uppercase but have a different general category value. In order to include those, use IntlChar::isUUppercase().

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is an Lu uppercase letter, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isupper("A"));
var_dump(IntlChar::isupper("a"));
var_dump(IntlChar::isupper("Φ"));
var_dump(IntlChar::isupper("φ"));
var_dump(IntlChar::isupper("1"));
?>`

The above example will output:

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

### See Also

- IntlChar::islower() - Check if code point is a lowercase letter
- IntlChar::istitle() - Check if code point is a titlecase letter
- IntlChar::tolower() - Make Unicode character lowercase
- IntlChar::toupper() - Make Unicode character uppercase
- `IntlChar::PROPERTY_UPPERCASE`
- ctype_upper() - Check for uppercase character(s)

# IntlChar::isUUppercase

(PHP 7, PHP 8)

IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property

### Description

public static IntlChar::isUUppercase(int|string `$codepoint`): ?bool

Check if a code point has the Uppercase Unicode property.

This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_UPPERCASE)`

> Note:

> This is different than IntlChar::isupper() and will return `true` for more characters.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` has the Uppercase Unicode property, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isUUppercase("A"));
var_dump(IntlChar::isUUppercase("a"));
var_dump(IntlChar::isUUppercase("Φ"));
var_dump(IntlChar::isUUppercase("φ"));
var_dump(IntlChar::isUUppercase("1"));
?>`

The above example will output:

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

### See Also

- IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- `IntlChar::PROPERTY_UPPERCASE`

# IntlChar::isUWhiteSpace

(PHP 7, PHP 8)

IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property

### Description

public static IntlChar::isUWhiteSpace(int|string `$codepoint`): ?bool

Check if a code point has the White_Space Unicode property.

This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_WHITE_SPACE)`

> Note:

> This is different from both IntlChar::isspace() and IntlChar::isWhitespace().

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` has the White_Space Unicode property, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isUWhiteSpace("A"));
var_dump(IntlChar::isUWhiteSpace(" "));
var_dump(IntlChar::isUWhiteSpace("\n"));
var_dump(IntlChar::isUWhiteSpace("\t"));
var_dump(IntlChar::isUWhiteSpace("\u{00A0}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isspace() - Check if code point is a space character
- IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
- IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
- IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
- `IntlChar::PROPERTY_WHITE_SPACE`

# IntlChar::isWhitespace

(PHP 7, PHP 8)

IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU

### Description

public static IntlChar::isWhitespace(int|string `$codepoint`): ?bool

Determines if the specified code point is a whitespace character according to ICU.

A character is considered to be a ICU whitespace character if and only if it satisfies one of the following criteria:

- It is a Unicode Separator character (categories "Z" = "Zs" or "Zl" or "Zp"), but is not also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP).
- It is U+0009 HORIZONTAL TABULATION.
- It is U+000A LINE FEED.
- It is U+000B VERTICAL TABULATION.
- It is U+000C FORM FEED.
- It is U+000D CARRIAGE RETURN.
- It is U+001C FILE SEPARATOR.
- It is U+001D GROUP SEPARATOR.
- It is U+001E RECORD SEPARATOR.
- It is U+001F UNIT SEPARATOR.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a whitespace character according to ICU, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::iswhitespace("A"));
var_dump(IntlChar::iswhitespace(" "));
var_dump(IntlChar::iswhitespace("\n"));
var_dump(IntlChar::iswhitespace("\t"));
var_dump(IntlChar::iswhitespace("\u{00A0}"));
?>`

The above example will output:

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

### See Also

- IntlChar::isspace() - Check if code point is a space character
- IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
- IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

# IntlChar::isxdigit

(PHP 7, PHP 8)

IntlChar::isxdigit — Check if code point is a hexadecimal digit

### Description

public static IntlChar::isxdigit(int|string `$codepoint`): ?bool

Determines whether the specified code point is a hexadecimal digit.

`true` for characters with general category "Nd" (decimal digit numbers) as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. (That is, for letters with code points 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.)

This is equivalent to `IntlChar::digit($codepoint, 16) >= 0`.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns `true` if `codepoint` is a hexadecimal character, `false` if not. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::isxdigit("A"));
var_dump(IntlChar::isxdigit("1"));
var_dump(IntlChar::isxdigit("\u{2603}"));
?>`

The above example will output:

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

### Notes

> Note:

> In order to narrow the definition of hexadecimal digits to only ASCII characters use:

> `<?php
> $isASCIIHexadecimal = IntlChar::ord($codepoint) <= 0x7F && IntlChar::isxdigit($codepoint);
> ?>`

### See Also

- IntlChar::isdigit() - Check if code point is a digit character
- ctype_xdigit() - Check for character(s) representing a hexadecimal digit

# IntlChar::ord

(PHP 7, PHP 8)

IntlChar::ord — Return Unicode code point value of character

### Description

public static IntlChar::ord(int|string `$character`): ?int

Returns the Unicode code point value of the given character.

This function complements IntlChar::chr().

### Parameters

`character`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the Unicode code point value as an integer.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::ord("A"));
var_dump(IntlChar::ord(" "));
var_dump(IntlChar::ord("\u{2603}"));
?>`

The above example will output:

    int(65)
    int(32)
    int(9731)

### See Also

- IntlChar::chr() - Return Unicode character by code point value
- mb_ord() - Get Unicode code point of character
- ord() - Convert the first byte of a string to a value between 0 and 255

# IntlChar::tolower

(PHP 7, PHP 8)

IntlChar::tolower — Make Unicode character lowercase

### Description

public static IntlChar::tolower(int|string `$codepoint`): int|string|null

The given character is mapped to its lowercase equivalent. If the character has no lowercase equivalent, the original character itself is returned.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the Simple_Lowercase_Mapping of the code point, if any; otherwise the code point itself. Returns `null` on failure.

The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::tolower("A"));
var_dump(IntlChar::tolower("a"));
var_dump(IntlChar::tolower("Φ"));
var_dump(IntlChar::tolower("φ"));
var_dump(IntlChar::tolower("1"));
var_dump(IntlChar::tolower(ord("A")));
var_dump(IntlChar::tolower(ord("a")));
?>`

The above example will output:

    string(1) "a"
    string(1) "a"
    string(2) "φ"
    string(2) "φ"
    string(1) "1"
    int(97)
    int(97)

### See Also

- IntlChar::totitle() - Make Unicode character titlecase
- IntlChar::toupper() - Make Unicode character uppercase
- mb_strtolower() - Make a string lowercase

# IntlChar::totitle

(PHP 7, PHP 8)

IntlChar::totitle — Make Unicode character titlecase

### Description

public static IntlChar::totitle(int|string `$codepoint`): int|string|null

The given character is mapped to its titlecase equivalent. If the character has no titlecase equivalent, the original character itself is returned.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the Simple_Titlecase_Mapping of the code point, if any; otherwise the code point itself. Returns `null` on failure.

The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::totitle("Ǆ"));
var_dump(IntlChar::totitle("ǆ"));
var_dump(IntlChar::totitle("Φ"));
var_dump(IntlChar::totitle("φ"));
var_dump(IntlChar::totitle("1"));
var_dump(IntlChar::totitle("ᾳ"));
var_dump(IntlChar::totitle(ord("A")));
?>`

The above example will output:

    string(1) "ǅ"
    string(1) "ǅ"
    string(2) "Φ"
    string(2) "φ"
    string(1) "1"
    string(1) "ᾼ"
    int(65)

### See Also

- IntlChar::tolower() - Make Unicode character lowercase
- IntlChar::toupper() - Make Unicode character uppercase
- IntlChar::istitle() - Check if code point is a titlecase letter
- mb_convert_case() - Perform case folding on a string

# IntlChar::toupper

(PHP 7, PHP 8)

IntlChar::toupper — Make Unicode character uppercase

### Description

public static IntlChar::toupper(int|string `$codepoint`): int|string|null

The given character is mapped to its uppercase equivalent. If the character has no uppercase equivalent, the character itself is returned.

### Parameters

`codepoint`

  The int codepoint value (e.g. `0x2603` for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)

### Return Values

Returns the Simple_Uppercase_Mapping of the code point, if any; otherwise the code point itself.

The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns `null` on failure.

### Examples

Example #1 Testing different code points

`<?php
var_dump(IntlChar::toupper("A"));
var_dump(IntlChar::toupper("a"));
var_dump(IntlChar::toupper("Φ"));
var_dump(IntlChar::toupper("φ"));
var_dump(IntlChar::toupper("1"));
var_dump(IntlChar::toupper(ord("A")));
var_dump(IntlChar::toupper(ord("a")));
?>`

The above example will output:

    string(1) "A"
    string(1) "A"
    string(2) "Φ"
    string(2) "Φ"
    string(1) "1"
    int(65)
    int(65)

### See Also

- IntlChar::tolower() - Make Unicode character lowercase
- IntlChar::totitle() - Make Unicode character titlecase
- mb_strtoupper() - Make a string uppercase

## Table of Contents

- IntlChar::charAge — Get the "age" of the code point
- IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
- IntlChar::charDirection — Get bidirectional category value for a code point
- IntlChar::charFromName — Find Unicode character by name and return its code point value
- IntlChar::charMirror — Get the "mirror-image" character for a code point
- IntlChar::charName — Retrieve the name of a Unicode character
- IntlChar::charType — Get the general category value for a code point
- IntlChar::chr — Return Unicode character by code point value
- IntlChar::digit — Get the decimal digit value of a code point for a given radix
- IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
- IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
- IntlChar::foldCase — Perform case folding on a code point
- IntlChar::forDigit — Get character representation for a given digit and radix
- IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
- IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
- IntlChar::getCombiningClass — Get the combining class of a code point
- IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
- IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
- IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
- IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
- IntlChar::getNumericValue — Get the numeric value for a Unicode code point
- IntlChar::getPropertyEnum — Get the property constant value for a given property name
- IntlChar::getPropertyName — Get the Unicode name for a property
- IntlChar::getPropertyValueEnum — Get the property value for a given value name
- IntlChar::getPropertyValueName — Get the Unicode name for a property value
- IntlChar::getUnicodeVersion — Get the Unicode version
- IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
- IntlChar::isalnum — Check if code point is an alphanumeric character
- IntlChar::isalpha — Check if code point is a letter character
- IntlChar::isbase — Check if code point is a base character
- IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
- IntlChar::iscntrl — Check if code point is a control character
- IntlChar::isdefined — Check whether the code point is defined
- IntlChar::isdigit — Check if code point is a digit character
- IntlChar::isgraph — Check if code point is a graphic character
- IntlChar::isIDIgnorable — Check if code point is an ignorable character
- IntlChar::isIDPart — Check if code point is permissible in an identifier
- IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
- IntlChar::isISOControl — Check if code point is an ISO control code
- IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
- IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
- IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
- IntlChar::islower — Check if code point is a lowercase letter
- IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
- IntlChar::isprint — Check if code point is a printable character
- IntlChar::ispunct — Check if code point is punctuation character
- IntlChar::isspace — Check if code point is a space character
- IntlChar::istitle — Check if code point is a titlecase letter
- IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
- IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
- IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
- IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
- IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
- IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
- IntlChar::isxdigit — Check if code point is a hexadecimal digit
- IntlChar::ord — Return Unicode code point value of character
- IntlChar::tolower — Make Unicode character lowercase
- IntlChar::totitle — Make Unicode character titlecase
- IntlChar::toupper — Make Unicode character uppercase

# Exception class for intl errors

(PHP 5 > 5.5.0, PHP 7, PHP 8, PECL intl > 3.0.0a1)

## Introduction

This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.

## Class synopsis

class IntlException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
public Exception::__construct(string `$message` = "", int `$code` = 0, ?Throwable `$previous` = `null`)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

# The IntlIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

## Introduction

This class represents iterator objects throughout the intl extension whenever the iterator cannot be identified with any other object provided by the extension. The distinct iterator object used internally by the `foreach` construct can only be obtained (in the relevant part here) from objects, so objects of this class serve the purpose of providing the hook through which this internal object can be obtained. As a convenience, this class also implements the Iterator interface, allowing the collection of values to be navigated using the methods defined in that interface. Both these methods and the internal iterator objects provided to `foreach` are backed by the same state (e.g. the position of the iterator and its current value).

Subclasses may provide richer functionality.

## Class synopsis

class IntlIterator implements Iterator {
/* Methods */
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

# IntlIterator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::current — Get the current element

### Description

public IntlIterator::current(): mixed

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlIterator::key

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::key — Get the current key

### Description

public IntlIterator::key(): mixed

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlIterator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::next — Move forward to the next element

### Description

public IntlIterator::next(): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlIterator::rewind

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::rewind — Rewind the iterator to the first element

### Description

public IntlIterator::rewind(): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

# IntlIterator::valid

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::valid — Check if current position is valid

### Description

public IntlIterator::valid(): bool

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

## Table of Contents

- IntlIterator::current — Get the current element
- IntlIterator::key — Get the current key
- IntlIterator::next — Move forward to the next element
- IntlIterator::rewind — Rewind the iterator to the first element
- IntlIterator::valid — Check if current position is valid

# intl Functions

# intl_error_name

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

### Description

intl_error_name(int `$errorCode`): string

Return ICU error code name.

### Parameters

`errorCode`

  ICU error code.

### Return Values

The returned string will be the same as the name of the error code constant.

### Examples

Example #1 intl_error_name() example

`<?php
$coll = collator_create( 'en_RU' );
$err_code = collator_get_error_code( $coll );
printf( "Symbolic name for %d is %s\n.", $err_code, intl_error_name( $err_code ) );
?>`

The above example will output something similar to:

    Symbolic name for -128 is U_USING_FALLBACK_WARNING.

### See Also

- intl_is_failure() - Check whether the given error code indicates failure
- intl_get_error_code() - Get the last error code
- intl_get_error_message() - Get description of the last error

# intl_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

### Description

intl_get_error_code(): int

Useful to handle errors occurred in static methods when there's no object to get error code from.

### Parameters

This function has no parameters.

### Return Values

Error code returned by the last API function call.

### Examples

Example #1 intl_get_error_code() example

`<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
handle_error( intl_get_error_code() );
}
?>`

### See Also

- intl_is_failure() - Check whether the given error code indicates failure
- intl_error_name() - Get symbolic name for a given error code
- intl_get_error_message() - Get description of the last error
- collator_get_error_code() - Get collator's last error code
- numfmt_get_error_code() - Get formatter's last error code

# intl_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

### Description

intl_get_error_message(): string

Get error message from last internationalization function called.

### Parameters

This function has no parameters.

### Return Values

Description of an error occurred in the last API function call.

### Examples

Example #1 intl_get_error_message() example

`<?php
if( Collator::getAvailableLocales() === false ) {
show_error( intl_get_error_message() );
}
?>`

### See Also

- intl_error_name() - Get symbolic name for a given error code
- intl_get_error_code() - Get the last error code
- intl_is_failure() - Check whether the given error code indicates failure
- collator_get_error_message() - Get text for collator's last error code
- numfmt_get_error_message() - Get formatter's last error message

# intl_is_failure

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

### Description

intl_is_failure(int `$errorCode`): bool

### Parameters

`errorCode`

  is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

### Return Values

`true` if it the code indicates some failure, and `false` in case of success or a warning.

### Examples

Example #1 intl_is_failure() example

`<?php
function check( $err_code )
{
var_export( intl_is_failure( $err_code ) );
echo "\n";
}
check( U_ZERO_ERROR );
check( U_USING_FALLBACK_WARNING );
check( U_ILLEGAL_ARGUMENT_ERROR );
?>`

The above example will output something similar to:

    false
    false
    true

### See Also

- intl_get_error_code() - Get the last error code
- collator_get_error_code() - Get collator's last error code
- Collator-getErrorCode()

## Table of Contents

- intl_error_name — Get symbolic name for a given error code
- intl_get_error_code — Get the last error code
- intl_get_error_message — Get description of the last error
- intl_is_failure — Check whether the given error code indicates failure

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Examples
  - Basic usage of this extension
- Collator — The Collator class
  - Collator::asort — Sort array maintaining index association
  - Collator::compare — Compare two Unicode strings
  - Collator::__construct — Create a collator
  - Collator::create — Create a collator
  - Collator::getAttribute — Get collation attribute value
  - Collator::getErrorCode — Get collator's last error code
  - Collator::getErrorMessage — Get text for collator's last error code
  - Collator::getLocale — Get the locale name of the collator
  - Collator::getSortKey — Get sorting key for a string
  - Collator::getStrength — Get current collation strength
  - Collator::setAttribute — Set collation attribute
  - Collator::setStrength — Set collation strength
  - Collator::sort — Sort array using specified collator
  - Collator::sortWithSortKeys — Sort array using specified collator and sort keys
- NumberFormatter — The NumberFormatter class
  - NumberFormatter::create — Create a number formatter
  - NumberFormatter::format — Format a number
  - NumberFormatter::formatCurrency — Format a currency value
  - NumberFormatter::getAttribute — Get an attribute
  - NumberFormatter::getErrorCode — Get formatter's last error code
  - NumberFormatter::getErrorMessage — Get formatter's last error message
  - NumberFormatter::getLocale — Get formatter locale
  - NumberFormatter::getPattern — Get formatter pattern
  - NumberFormatter::getSymbol — Get a symbol value
  - NumberFormatter::getTextAttribute — Get a text attribute
  - NumberFormatter::parse — Parse a number
  - NumberFormatter::parseCurrency — Parse a currency number
  - NumberFormatter::setAttribute — Set an attribute
  - NumberFormatter::setPattern — Set formatter pattern
  - NumberFormatter::setSymbol — Set a symbol value
  - NumberFormatter::setTextAttribute — Set a text attribute
- Locale — The Locale class
  - Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  - Locale::canonicalize — Canonicalize the locale string
  - Locale::composeLocale — Returns a correctly ordered and delimited locale ID
  - Locale::filterMatches — Checks if a language tag filter matches with locale
  - Locale::getAllVariants — Gets the variants for the input locale
  - Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
  - Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
  - Locale::getDisplayName — Returns an appropriately localized display name for the input locale
  - Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
  - Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
  - Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
  - Locale::getKeywords — Gets the keywords for the input locale
  - Locale::getPrimaryLanguage — Gets the primary language for the input locale
  - Locale::getRegion — Gets the region for the input locale
  - Locale::getScript — Gets the script for the input locale
  - Locale::isRightToLeft — Check whether a locale uses a right-to-left writing system
  - Locale::lookup — Searches the language tag list for the best match to the language
  - Locale::parseLocale — Returns a key-value array of locale ID subtag elements
  - Locale::setDefault — Sets the default runtime locale
- Normalizer — The Normalizer class
  - Normalizer::getRawDecomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
  - Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form
  - Normalizer::normalize — Normalizes the input provided and returns the normalized string
- MessageFormatter — The MessageFormatter class
  - MessageFormatter::create — Constructs a new Message Formatter
  - MessageFormatter::format — Format the message
  - MessageFormatter::formatMessage — Quick format message
  - MessageFormatter::getErrorCode — Get the error code from last operation
  - MessageFormatter::getErrorMessage — Get the error text from the last operation
  - MessageFormatter::getLocale — Get the locale for which the formatter was created
  - MessageFormatter::getPattern — Get the pattern used by the formatter
  - MessageFormatter::parse — Parse input string according to pattern
  - MessageFormatter::parseMessage — Quick parse input string
  - MessageFormatter::setPattern — Set the pattern used by the formatter
- IntlCalendar — The IntlCalendar class
  - IntlCalendar::add — Add a (signed) amount of time to a field
  - IntlCalendar::after — Whether this objectʼs time is after that of the passed object
  - IntlCalendar::before — Whether this objectʼs time is before that of the passed object
  - IntlCalendar::clear — Clear a field or all fields
  - IntlCalendar::__construct — Private constructor for disallowing instantiation
  - IntlCalendar::createInstance — Create a new IntlCalendar
  - IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
  - IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time
  - IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
  - IntlCalendar::get — Get the value for a field
  - IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time
  - IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time
  - IntlCalendar::getAvailableLocales — Get array of locales for which there is data
  - IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
  - IntlCalendar::getErrorCode — Get last error code on the object
  - IntlCalendar::getErrorMessage — Get last error message on the object
  - IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale
  - IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
  - IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
  - IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
  - IntlCalendar::getLocale — Get the locale associated with the object
  - IntlCalendar::getMaximum — Get the global maximum value for a field
  - IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
  - IntlCalendar::getMinimum — Get the global minimum value for a field
  - IntlCalendar::getNow — Get number representing the current time
  - IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
  - IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
  - IntlCalendar::getTime — Get time currently represented by the object
  - IntlCalendar::getTimeZone — Get the objectʼs timezone
  - IntlCalendar::getType — Get the calendar type
  - IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
  - IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time
  - IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
  - IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
  - IntlCalendar::isSet — Whether a field is set
  - IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
  - IntlCalendar::roll — Add value to field without carrying into more significant fields
  - IntlCalendar::set — Set a time field or several common fields at once
  - IntlCalendar::setDate — Set a date fields
  - IntlCalendar::setDateTime — Set a date and time fields
  - IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
  - IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
  - IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
  - IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
  - IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
  - IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
  - IntlCalendar::setTimeZone — Set the timezone used by this calendar
  - IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object
- IntlGregorianCalendar — The IntlGregorianCalendar class
  - IntlGregorianCalendar::__construct — Create the Gregorian Calendar class
  - IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date
  - IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time
  - IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date
  - IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year
  - IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date
- IntlTimeZone — The IntlTimeZone class
  - IntlTimeZone::__construct — Private constructor to disallow direct instantiation
  - IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
  - IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
  - IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
  - IntlTimeZone::createTimeZone — Create a timezone object for the given ID
  - IntlTimeZone::createTimeZoneIDEnumeration — Get an enumeration over system time zone IDs with the given filter conditions
  - IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
  - IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
  - IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
  - IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
  - IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
  - IntlTimeZone::getErrorCode — Get last error code on the object
  - IntlTimeZone::getErrorMessage — Get last error message on the object
  - IntlTimeZone::getGMT — Create GMT (UTC) timezone
  - IntlTimeZone::getID — Get timezone ID
  - IntlTimeZone::getIDForWindowsID — Translate a Windows timezone into a system timezone
  - IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
  - IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
  - IntlTimeZone::getRegion — Get the region code associated with the given system time zone ID
  - IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
  - IntlTimeZone::getUnknown — Get the "unknown" time zone
  - IntlTimeZone::getWindowsID — Translate a system timezone into a Windows timezone
  - IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
  - IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
  - IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time
- IntlDateFormatter — The IntlDateFormatter class
  - IntlDateFormatter::create — Create a date formatter
  - IntlDateFormatter::format — Format the date/time value as a string
  - IntlDateFormatter::formatObject — Formats an object
  - IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
  - IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
  - IntlDateFormatter::getErrorCode — Get the error code from last operation
  - IntlDateFormatter::getErrorMessage — Get the error text from the last operation
  - IntlDateFormatter::getLocale — Get the locale used by formatter
  - IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
  - IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
  - IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
  - IntlDateFormatter::getCalendarObject — Get copy of formatterʼs calendar object
  - IntlDateFormatter::getTimeZone — Get formatterʼs timezone
  - IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
  - IntlDateFormatter::localtime — Parse string to a field-based time value
  - IntlDateFormatter::parse — Parse string to a timestamp value
  - IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
  - IntlDateFormatter::setLenient — Set the leniency of the parser
  - IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
  - IntlDateFormatter::setTimeZone — Sets formatterʼs timezone
- ResourceBundle — The ResourceBundle class
  - ResourceBundle::count — Get number of elements in the bundle
  - ResourceBundle::create — Create a resource bundle
  - ResourceBundle::get — Get data from the bundle
  - ResourceBundle::getErrorCode — Get bundle's last error code
  - ResourceBundle::getErrorMessage — Get bundle's last error message
  - ResourceBundle::getLocales — Get supported locales
- Spoofchecker — The Spoofchecker class
  - Spoofchecker::areConfusable — Checks if given strings can be confused
  - Spoofchecker::__construct — Constructor
  - Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
  - Spoofchecker::setAllowedLocales — Locales to use when running checks
  - Spoofchecker::setChecks — Set the checks to run
  - Spoofchecker::setRestrictionLevel — Set the restriction level
- Transliterator — The Transliterator class
  - Transliterator::__construct — Private constructor to deny instantiation
  - Transliterator::create — Create a transliterator
  - Transliterator::createFromRules — Create transliterator from rules
  - Transliterator::createInverse — Create an inverse transliterator
  - Transliterator::getErrorCode — Get last error code
  - Transliterator::getErrorMessage — Get last error message
  - Transliterator::listIDs — Get transliterator IDs
  - Transliterator::transliterate — Transliterate a string
- IntlBreakIterator — The IntlBreakIterator class
  - IntlBreakIterator::__construct — Private constructor for disallowing instantiation
  - IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
  - IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
  - IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
  - IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
  - IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
  - IntlBreakIterator::createWordInstance — Create break iterator for word breaks
  - IntlBreakIterator::current — Get index of current position
  - IntlBreakIterator::first — Set position to the first character in the text
  - IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
  - IntlBreakIterator::getErrorCode — Get last error code on the object
  - IntlBreakIterator::getErrorMessage — Get last error message on the object
  - IntlBreakIterator::getLocale — Get the locale associated with the object
  - IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
  - IntlBreakIterator::getText — Get the text being scanned
  - IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset
  - IntlBreakIterator::last — Set the iterator position to index beyond the last character
  - IntlBreakIterator::next — Advance the iterator the next boundary
  - IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
  - IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
  - IntlBreakIterator::setText — Set the text being scanned
- IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
  - IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
  - IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
  - IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
  - IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
  - IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position
- IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
  - IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator
- IntlDatePatternGenerator — The IntlDatePatternGenerator class
  - IntlDatePatternGenerator::create — Creates a new IntlDatePatternGenerator instance
  - IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format
- IntlPartsIterator — The IntlPartsIterator class
  - IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator
- UConverter — The UConverter class
  - UConverter::__construct — Create UConverter object
  - UConverter::convert — Convert string from one charset to another
  - UConverter::fromUCallback — Default "from" callback function
  - UConverter::getAliases — Get the aliases of the given name
  - UConverter::getAvailable — Get the available canonical converter names
  - UConverter::getDestinationEncoding — Get the destination encoding
  - UConverter::getDestinationType — Get the destination converter type
  - UConverter::getErrorCode — Get last error code on the object
  - UConverter::getErrorMessage — Get last error message on the object
  - UConverter::getSourceEncoding — Get the source encoding
  - UConverter::getSourceType — Get the source converter type
  - UConverter::getStandards — Get standards associated to converter names
  - UConverter::getSubstChars — Get substitution chars
  - UConverter::reasonText — Get string representation of the callback reason
  - UConverter::setDestinationEncoding — Set the destination encoding
  - UConverter::setSourceEncoding — Set the source encoding
  - UConverter::setSubstChars — Set the substitution chars
  - UConverter::toUCallback — Default "to" callback function
  - UConverter::transcode — Convert a string from one character encoding to another
- Grapheme Functions
  - grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
  - grapheme_str_split — Split a string into an array
  - grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
  - grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  - grapheme_strlen — Get string length in grapheme units
  - grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
  - grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
  - grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
  - grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack
  - grapheme_substr — Return part of a string
- IDN Functions
  - idn_to_ascii — Convert domain name to IDNA ASCII form
  - idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode
- IntlChar
  - IntlChar::charAge — Get the "age" of the code point
  - IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
  - IntlChar::charDirection — Get bidirectional category value for a code point
  - IntlChar::charFromName — Find Unicode character by name and return its code point value
  - IntlChar::charMirror — Get the "mirror-image" character for a code point
  - IntlChar::charName — Retrieve the name of a Unicode character
  - IntlChar::charType — Get the general category value for a code point
  - IntlChar::chr — Return Unicode character by code point value
  - IntlChar::digit — Get the decimal digit value of a code point for a given radix
  - IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
  - IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
  - IntlChar::foldCase — Perform case folding on a code point
  - IntlChar::forDigit — Get character representation for a given digit and radix
  - IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
  - IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
  - IntlChar::getCombiningClass — Get the combining class of a code point
  - IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
  - IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
  - IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
  - IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
  - IntlChar::getNumericValue — Get the numeric value for a Unicode code point
  - IntlChar::getPropertyEnum — Get the property constant value for a given property name
  - IntlChar::getPropertyName — Get the Unicode name for a property
  - IntlChar::getPropertyValueEnum — Get the property value for a given value name
  - IntlChar::getPropertyValueName — Get the Unicode name for a property value
  - IntlChar::getUnicodeVersion — Get the Unicode version
  - IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
  - IntlChar::isalnum — Check if code point is an alphanumeric character
  - IntlChar::isalpha — Check if code point is a letter character
  - IntlChar::isbase — Check if code point is a base character
  - IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
  - IntlChar::iscntrl — Check if code point is a control character
  - IntlChar::isdefined — Check whether the code point is defined
  - IntlChar::isdigit — Check if code point is a digit character
  - IntlChar::isgraph — Check if code point is a graphic character
  - IntlChar::isIDIgnorable — Check if code point is an ignorable character
  - IntlChar::isIDPart — Check if code point is permissible in an identifier
  - IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
  - IntlChar::isISOControl — Check if code point is an ISO control code
  - IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
  - IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
  - IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
  - IntlChar::islower — Check if code point is a lowercase letter
  - IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
  - IntlChar::isprint — Check if code point is a printable character
  - IntlChar::ispunct — Check if code point is punctuation character
  - IntlChar::isspace — Check if code point is a space character
  - IntlChar::istitle — Check if code point is a titlecase letter
  - IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
  - IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
  - IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
  - IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
  - IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
  - IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
  - IntlChar::isxdigit — Check if code point is a hexadecimal digit
  - IntlChar::ord — Return Unicode code point value of character
  - IntlChar::tolower — Make Unicode character lowercase
  - IntlChar::totitle — Make Unicode character titlecase
  - IntlChar::toupper — Make Unicode character uppercase
- IntlException — Exception class for intl errors
- IntlIterator — The IntlIterator class
  - IntlIterator::current — Get the current element
  - IntlIterator::key — Get the current key
  - IntlIterator::next — Move forward to the next element
  - IntlIterator::rewind — Rewind the iterator to the first element
  - IntlIterator::valid — Check if current position is valid
- intl Functions
  - intl_error_name — Get symbolic name for a given error code
  - intl_get_error_code — Get the last error code
  - intl_get_error_message — Get description of the last error
  - intl_is_failure — Check whether the given error code indicates failure

# Multibyte String

# Introduction

While there are many languages in which every necessary character can be represented by a one-to-one mapping to an 8-bit value, there are also several languages which require so many characters for written communication that they cannot be contained within the range a mere byte can code (A byte is made up of eight bits. Each bit can contain only two distinct values, one or zero. Because of this, a byte can only represent 256 unique values (two to the power of eight)). Multibyte character encoding schemes were developed to express more than 256 characters in the regular bytewise coding system.

When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.

`mbstring` provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that, `mbstring` handles character encoding conversion between the possible encoding pairs. `mbstring` is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed in Supported Character Encodings).

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

`mbstring` is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the `configure` option. See the Install section for details.

The following configure options are related to the `mbstring` module.

- --enable-mbstring: Enable `mbstring` functions. This option is required to use `mbstring` functions.

  libmbfl is necessary for `mbstring`. libmbfl is bundled with `mbstring`. Prior to PHP 7.3.0, if libmbfl is already installed on the system, --with-libmbfl[=DIR] can be specified to use the installed library.

- --disable-mbregex: Disable regular expression functions with multibyte character support.

  Oniguruma is necessary for the regular expression functions with multibyte character support. As of PHP 7.4.0, pkg-config is used to detect the libonig library. Prior to PHP 7.4.0, Oniguruma was bundled with `mbstring`, but it was possible to build against an already installed libonig by passing --with-onig[=DIR].

  It is possible to disable the multibyte regex backtrack check by specifying --disable-mbregex-backtrack.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mbstring configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mbstring.language | "neutral" | `INI_ALL` |
mbstring.detect_order | NULL | `INI_ALL` |
mbstring.http_input | "pass" | `INI_ALL` | Deprecated
mbstring.http_output | "pass" | `INI_ALL` | Deprecated
mbstring.internal_encoding | NULL | `INI_ALL` | Deprecated
mbstring.substitute_character | NULL | `INI_ALL` |
mbstring.func_overload | "0" | `INI_SYSTEM` | Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation | "0" | `INI_PERDIR` |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | `INI_ALL` |
mbstring.strict_detection | "0" | `INI_ALL` |
mbstring.regex_retry_limit | "1000000" | `INI_ALL` | Available as of PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | `INI_ALL` | Available as of PHP 7.3.5.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mbstring.language` string

  The default national language setting (NLS) used in mbstring. Note that this option automagically defines `mbstring.internal_encoding` and `mbstring.internal_encoding` should be placed after `mbstring.language` in php.ini

`mbstring.encoding_translation` bool

  Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.

`mbstring.internal_encoding` string
  Warning

  This deprecated feature will certainly be removed in the future.

  Defines the default internal character encoding.

  Users should leave this empty and set `default_charset` instead.

`mbstring.http_input` string
  Warning

  This deprecated feature will certainly be removed in the future.

  Defines the default HTTP input character encoding.

  Users should leave this empty and set `default_charset` instead.

`mbstring.http_output` string
  Warning

  This deprecated feature will certainly be removed in the future.

  Defines the default HTTP output character encoding (output will be converted from the internal encoding to the HTTP output encoding upon output).

  Users should leave this empty and set `default_charset` instead.

`mbstring.detect_order` string

  Defines default character code detection order. See also mb_detect_order().

`mbstring.substitute_character` string

  Defines character to substitute for invalid character encoding. See mb_substitute_character() for supported values.

`mbstring.func_overload` string
  Warning

  This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.

  Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.

  This setting can only be changed from the php.ini file.

`mbstring.http_output_conv_mimetypes` string

`mbstring.strict_detection` bool

  Enables strict encoding detection. See mb_detect_encoding() for a description and examples.

`mbstring.regex_retry_limit` int

  Limits the amount of backtracking that may be performed during one mbregex match.

  This setting only takes effect when linking against oniguruma >= 6.8.0.

`mbstring.regex_stack_limit` int

  Limits the stack depth of mbstring regular expressions.

According to the » HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.

Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the `charset` parameter in the `Content-Type` HTTP header to the appropriate value by header() or default_charset ini setting.

Example #1 php.ini setting examples

    ; Set default language
    mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
    mbstring.language        = English; Set default language to English
    mbstring.language        = Japanese; Set default language to Japanese

    ;; Set default internal encoding
    ;; Note: Make sure to use character encoding works with PHP
    mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

    ;; HTTP input encoding translation is enabled.
    mbstring.encoding_translation = On

    ;; Set default HTTP input character encoding
    ;; Note: Script cannot change http_input setting.
    mbstring.http_input           = pass    ; No conversion.
    mbstring.http_input           = auto    ; Set HTTP input to auto
                                    ; "auto" is expanded according to mbstring.language
    mbstring.http_input           = SJIS    ; Set HTTP input to SJIS
    mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

    ;; Set default HTTP output character encoding
    mbstring.http_output          = pass    ; No conversion
    mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

    ;; Set default character encoding detection order
    mbstring.detect_order         = auto    ; Set detect order to auto
    mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

    ;; Set default substitute character
    mbstring.substitute_character = 12307   ; Specify Unicode value
    mbstring.substitute_character = none    ; Do not print character
    mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Example #2 php.ini setting for `EUC-JP` users

    ;; Disable Output Buffering
    output_buffering      = Off

    ;; Set HTTP header charset
    default_charset       = EUC-JP

    ;; Set default language to Japanese
    mbstring.language = Japanese

    ;; HTTP input encoding translation is enabled.
    mbstring.encoding_translation = On

    ;; Set HTTP input encoding conversion to auto
    mbstring.http_input   = auto

    ;; Convert HTTP output to EUC-JP
    mbstring.http_output  = EUC-JP

    ;; Set internal encoding to EUC-JP
    mbstring.internal_encoding = EUC-JP

    ;; Do not print invalid characters
    mbstring.substitute_character = none

Example #3 php.ini setting for `SJIS` users

    ;; Enable Output Buffering
    output_buffering     = On

    ;; Set mb_output_handler to enable output conversion
    output_handler       = mb_output_handler

    ;; Set HTTP header charset
    default_charset      = Shift_JIS

    ;; Set default language to Japanese
    mbstring.language = Japanese

    ;; Set http input encoding conversion to auto
    mbstring.http_input  = auto

    ;; Convert to SJIS
    mbstring.http_output = SJIS

    ;; Set internal encoding to EUC-JP
    mbstring.internal_encoding = EUC-JP

    ;; Do not print invalid characters
    mbstring.substitute_character = none

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

`MB_OVERLOAD_MAIL` (int)
  Removed as of PHP 8.0.0.
`MB_OVERLOAD_STRING` (int)
  Removed as of PHP 8.0.0.
`MB_OVERLOAD_REGEX` (int)
  Removed as of PHP 8.0.0.
`MB_CASE_UPPER` (int)
  Performs a full upper-case folding. This may change the length of the string. This is the mode used by mb_strtoupper().
`MB_CASE_LOWER` (int)
  Performs a full lower-case folding. This may change the length of the string. This is the mode used by mb_strtolower().
`MB_CASE_TITLE` (int)
  Performs a full title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this improves handling of quotes and apostrophes. This may change the length of the string.
`MB_CASE_FOLD` (int)
  Performs a full case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This may change the length of the string. Available since PHP 7.3.
`MB_CASE_LOWER_SIMPLE` (int)
  Performs a simple lower-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
`MB_CASE_UPPER_SIMPLE` (int)
  Performs simple upper-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
`MB_CASE_TITLE_SIMPLE` (int)
  Performs simple title-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
`MB_CASE_FOLD_SIMPLE` (int)
  Performs a simple case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This does not change the length of the string. Used by case-insensitive operations internally by the MBString extension. Available as of PHP 7.3.
`MB_ONIGURUMA_VERSION` (string)
  The Oniguruma version, e.g. `6.9.4`. Available as of PHP 7.4.

# Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry | Underlying character set | Description | Additional note
--- | --- | --- | ---
ISO-10646-UCS-4 | ISO 10646 | The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map. | If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to `UCS-4`, strings are always assumed to be in big endian form.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to `UCS-4`, strings are always assumed to be in little endian form.
ISO-10646-UCS-2 | UCS-2 | The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map. | If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to `UCS-2`, strings are always assumed to be in big endian form.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to `UCS-2`, strings are always assumed to be in little endian form.
UTF-32 | Unicode | Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value. | If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
UTF-32BE | Unicode | See above | In contrast to `UTF-32`, strings are always assumed to be in big endian form.
UTF-32LE | Unicode | See above | In contrast to `UTF-32`, strings are always assumed to be in little endian form.
UTF-16 | Unicode | Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space. | If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
UTF-16BE | Unicode | See above. | In contrast to `UTF-16`, strings are always assumed to be in big endian form.
UTF-16LE | Unicode | See above. | In contrast to `UTF-16`, strings are always assumed to be in little endian form.
UTF-8 | Unicode / UCS | Unicode Transformation Format of 8-bit unit width. | none
UTF-7 | Unicode | A mail-safe transformation format of Unicode, specified in » RFC2152. | none
(none) | Unicode | A variant of UTF-7 which is specialized for use in the » IMAP protocol. | none
US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII | ASCII / ISO 646 | American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646. | (none)
EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese | Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990 | As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022. | The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS | Compound of JIS X0201:1997 / JIS X0208:1997 | Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatibilities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets. | For the CP932 codemap, use SJIS-WIN instead.
(none) | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP. | none
Windows-31J / csWindows31J | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS. | (none)
ISO-2022-JP (preferred MIME name) / csISO2022JP | US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983 | » RFC1468 | (none)
JIS |  |  |
ISO-8859-1 |  |  |
ISO-8859-2 |  |  |
ISO-8859-3 |  |  |
ISO-8859-4 |  |  |
ISO-8859-5 |  |  |
ISO-8859-6 |  |  |
ISO-8859-7 |  |  |
ISO-8859-8 |  |  |
ISO-8859-9 |  |  |
ISO-8859-10 |  |  |
ISO-8859-13 |  |  |
ISO-8859-14 |  |  |
ISO-8859-15 |  |  |
ISO-8859-16 |  |  |
byte2be |  |  |
byte2le |  |  |
byte4be |  |  |
byte4le |  |  |
BASE64 |  |  |
HTML-ENTITIES |  |  |
7bit |  |  |
8bit |  |  |
EUC-CN |  |  |
CP936 |  |  |
HZ |  |  |
EUC-TW |  |  |
CP950 |  |  |
BIG-5 |  |  |
EUC-KR |  |  |
UHC (CP949) |  |  |
ISO-2022-KR |  |  |
Windows-1251 (CP1251) |  |  |
Windows-1252 (CP1252) |  |  |
CP866 (IBM866) |  |  |
KOI8-R |  |  |
KOI8-U |  |  |

# Basics of Japanese multi-byte encodings

Japanese characters can only be represented by multibyte encodings, and multiple encoding standards are used depending on platform and text purpose. To make matters worse, these encoding standards differ slightly from one another. In order to create a web application which would be usable in a Japanese environment, a developer has to keep these complexities in mind to ensure that the proper character encodings are used.

- Storage for a character can be up to six bytes
- Most Japanese multibyte characters appear twice as wide as single-byte characters. These characters are called "zen-kaku" in Japanese, which means "full width". Other, narrower, characters are called "han-kaku", which means "half width". The graphical properties of the characters, however, depends upon the type faces used to display them.
- Some character encodings use shift(escape) sequences defined in ISO-2022 to switch the code map of the specific code area (`00h` to `7fh`).
- ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
- Web pages created for mobile phone services such as » i-mode or » EZweb are supposed to use Shift_JIS.
- Emoji used for mobile phone service such as » i-mode or » EZweb are supported.

# HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

> Note:

> If `enctype` for HTML form is set to `multipart/form-data` and `mbstring.encoding_translation` is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.

- HTTP Input

  There is no way to control HTTP input character conversion from a PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

  Example #1 Disable HTTP input conversion in php.ini

      ;; Disable HTTP Input conversion
      mbstring.http_input = pass
      ;; Disable HTTP Input conversion
      mbstring.encoding_translation = Off

  When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

- HTTP Output

  There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as the `ob_start` callback function.

Example #2 php.ini setting example

    ;; Enable output character encoding conversion for all PHP pages

    ;; Enable Output Buffering
    output_buffering    = On

    ;; Set mb_output_handler to enable output conversion
    output_handler      = mb_output_handler

Example #3 Script example

`<?php
// Enable output character encoding conversion only for this page
// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');
// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');
?>`

# Supported Character Encodings

Currently the following character encodings are supported by the `mbstring` module. Any of those Character encodings can be specified in the `encoding` parameter of `mbstring` functions.

The following character encodings are supported in this PHP extension:

- UCS-4*
- UCS-4BE
- UCS-4LE*
- UCS-2
- UCS-2BE
- UCS-2LE
- UTF-32*
- UTF-32BE*
- UTF-32LE*
- UTF-16*
- UTF-16BE*
- UTF-16LE*
- UTF-7
- UTF7-IMAP
- UTF-8*
- ASCII*
- EUC-JP*
- SJIS*
- eucJP-win*
- SJIS-win*
- ISO-2022-JP
- ISO-2022-JP-MS
- CP932
- CP51932
- SJIS-mac (alias: MacJapanese)
- SJIS-Mobile#DOCOMO (alias: SJIS-DOCOMO)
- SJIS-Mobile#KDDI (alias: SJIS-KDDI)
- SJIS-Mobile#SOFTBANK (alias: SJIS-SOFTBANK)
- UTF-8-Mobile#DOCOMO (alias: UTF-8-DOCOMO)
- UTF-8-Mobile#KDDI-A
- UTF-8-Mobile#KDDI-B (alias: UTF-8-KDDI)
- UTF-8-Mobile#SOFTBANK (alias: UTF-8-SOFTBANK)
- ISO-2022-JP-MOBILE#KDDI (alias: ISO-2022-JP-KDDI)
- JIS
- JIS-ms
- CP50220
- CP50220raw
- CP50221
- CP50222
- ISO-8859-1*
- ISO-8859-2*
- ISO-8859-3*
- ISO-8859-4*
- ISO-8859-5*
- ISO-8859-6*
- ISO-8859-7*
- ISO-8859-8*
- ISO-8859-9*
- ISO-8859-10*
- ISO-8859-13*
- ISO-8859-14*
- ISO-8859-15*
- ISO-8859-16*
- byte2be
- byte2le
- byte4be
- byte4le
- BASE64
- HTML-ENTITIES (alias: HTML)
- 7bit
- 8bit
- EUC-CN*
- CP936
- GB18030
- HZ
- EUC-TW*
- CP950
- BIG-5*
- EUC-KR*
- UHC (alias: CP949)
- ISO-2022-KR
- Windows-1251 (alias: CP1251)
- Windows-1252 (alias: CP1252)
- CP866 (alias: IBM866)
- KOI8-R*
- KOI8-U*
- ArmSCII-8 (alias: ArmSCII8)

* denotes encodings usable also in regular expressions.

Any php.ini entry which accepts an encoding name can also use the values "`auto`" and "`pass`". `mbstring` functions which accept an encoding name can also use the value "`auto`".

If "`pass`" is set, no character encoding conversion is performed.

If "`auto`" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to `Japanese`, the value is assumed to be "`ASCII,JIS,UTF-8,EUC-JP,SJIS`".

See also mb_detect_order()

# Function Overloading Feature

Warning

This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.

You might often find it difficult to get an existing PHP application to work in a given multibyte environment. This happens because most PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.

mbstring supports a 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.

To use function overloading, set `mbstring.func_overload` in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if it is set to 7, mail, strings and regular expression functions will be overloaded. The list of overloaded functions are shown below.

Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function
--- | --- | ---
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
2 | strtolower() | mb_strtolower()
2 | strtoupper() | mb_strtoupper()
2 | stripos() | mb_stripos()
2 | strripos() | mb_strripos()
2 | strstr() | mb_strstr()
2 | stristr() | mb_stristr()
2 | strrchr() | mb_strrchr()
2 | substr_count() | mb_substr_count()

> Note:

> It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.

# PHP Character Encoding Requirements

Encodings of the following types are safely used with PHP.

- A singlebyte encoding,

  - which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of `00h` to `7fh`.

- A multibyte encoding,

  - which has ASCII-compatible mappings for the characters in range of `00h` to `7fh`.
  - which don't use ISO2022 escape sequences.
  - which don't use a value from `00h` to `7fh` in any of the compounded bytes that represents a single character.

These are examples of character encodings that are unlikely to work with PHP.

    JIS, SJIS, ISO-2022-JP, BIG-5

Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the `mbstring`'s transparent encoding filter function for incoming HTTP queries.

> Note:

> It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.

> Note:

> If you are connecting to a database with PHP, it is recommended that you use the same character encoding for both the database and the `internal encoding` for ease of use and better performance.

> If you are using PostgreSQL, the character encoding used in the database and the one used in PHP may differ as it supports automatic character set conversion between the backend and the frontend.

# Multibyte String Functions

# References

Multibyte character encoding schemes and their related issues are fairly complicated, and are beyond the scope of this documentation. Please refer to the following URLs and other resources for further information regarding these topics.

- Unicode materials

  » http://www.unicode.org/

- Japanese/Korean/Chinese character information

  » https://resources.oreilly.com/examples/9781565922242/blob/master/doc/cjk.inf

# mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3, PHP 7, PHP 8)

mb_check_encoding — Check if strings are valid for the specified encoding

### Description

mb_check_encoding(array|string|null `$value` = `null`, ?string `$encoding` = `null`): bool

Checks if the specified byte stream is valid for the specified encoding. If `value` is of type array, all keys and values are validated recursively. It is useful to prevent so-called "Invalid Encoding Attack".

### Parameters

`value`

  The byte stream or array to check. If it is omitted, this function checks all the input from the beginning of the request.

  Warning

  As of PHP 8.1.0, omitting this parameter or passing `null` is deprecated.

`encoding`

  The expected encoding.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Calling this function with `null` as `value` or without argument is deprecated.
8.0.0 | `value` and `encoding` are nullable now.
7.2.0 | This function now also accepts an array as `value`. Formerly, only strings have been supported.

# mb_chr

(PHP 7 >= 7.2.0, PHP 8)

mb_chr — Return character by Unicode code point value

### Description

mb_chr(int `$codepoint`, ?string `$encoding` = `null`): string|false

Returns a string containing the character specified by the Unicode code point value, encoded in the specified encoding.

This function complements mb_ord().

### Parameters

`codepoint`

  A Unicode codepoint value, e.g. `128024` for U+1F418 ELEPHANT

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

A string containing the requested character, if it can be represented in the specified encoding or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 Testing different code points

`<?php
$values = [65, 63, 0x20AC, 128024];
foreach ($values as $value) {
var_dump(mb_chr($value, 'UTF-8'));
var_dump(mb_chr($value, 'ISO-8859-1'));
}
?>`

The above example will output:

    string(1) "A"
    string(1) "A"
    string(1) "?"
    string(1) "?"
    string(3) "€"
    bool(false)
    string(4) "🐘"
    bool(false)

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_ord() - Get Unicode code point of character
- IntlChar::ord() - Return Unicode code point value of character
- chr() - Generate a single-byte string from a number

# mb_convert_case

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_convert_case — Perform case folding on a string

### Description

mb_convert_case(string `$string`, int `$mode`, ?string `$encoding` = `null`): string

Performs case folding on a string, converted in the way specified by `mode`.

### Parameters

`string`

  The string being converted.

`mode`

  The mode of the conversion. It can be one of `MB_CASE_UPPER`, `MB_CASE_LOWER`, `MB_CASE_TITLE`, `MB_CASE_FOLD`, `MB_CASE_UPPER_SIMPLE`, `MB_CASE_LOWER_SIMPLE`, `MB_CASE_TITLE_SIMPLE`, `MB_CASE_FOLD_SIMPLE`.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

A case folded version of `string` converted in the way specified by `mode`.

### Changelog

Version | Description
--- | ---
8.3.0 | Implemented conditional casing rules for the Greek letter sigma which only apply to `MB_CASE_LOWER` and `MB_CASE_TITLE` modes, not to `MB_CASE_LOWER_SIMPLE` and `MB_CASE_TITLE_SIMPLE`.
7.3.0 | Added support for `MB_CASE_FOLD`, `MB_CASE_UPPER_SIMPLE`, `MB_CASE_LOWER_SIMPLE`, `MB_CASE_TITLE_SIMPLE`, and `MB_CASE_FOLD_SIMPLE` as `mode`.

### Examples

Example #1 mb_convert_case() example

`<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str, PHP_EOL;
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str, PHP_EOL;
?>`

Example #2 mb_convert_case() example with non-Latin UTF-8 text

`<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str, PHP_EOL;
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str, PHP_EOL;
?>`

### Notes

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such a-umlaut (ä).

For more information about the Unicode properties, please see » http://www.unicode.org/reports/tr21/.

### See Also

- mb_strtolower() - Make a string lowercase
- mb_strtoupper() - Make a string uppercase
- strtolower() - Make a string lowercase
- strtoupper() - Make a string uppercase
- ucfirst() - Make a string's first character uppercase
- ucwords() - Uppercase the first character of each word in a string

# mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_encoding — Convert a string from one character encoding to another

### Description

mb_convert_encoding(array|string `$string`, string `$to_encoding`, array|string|null `$from_encoding` = `null`): array|string|false

Converts `string` from `from_encoding`, or the current internal encoding, to `to_encoding`. If `string` is an array, all its string values will be converted recursively.

### Parameters

`string`

  The string or array to be converted.

`to_encoding`

  The desired encoding of the result.

`from_encoding`

  The current encoding used to interpret `string`. Multiple encodings may be specified as an array or comma separated list, in which case the correct encoding will be guessed using the same algorithm as mb_detect_encoding().

  If `from_encoding` is omitted or `null`, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting.

  See supported encodings for valid values of `to_encoding` and `from_encoding`.

### Return Values

The encoded string or array on success, or `false` on failure.

### Errors/Exceptions

As of PHP 8.0.0, a ValueError is thrown if the value of `to_encoding` or `from_encoding` is an invalid encoding. Prior to PHP 8.0.0, a `E_WARNING` was emitted instead.

### Changelog

Version | Description
--- | ---
8.2.0 | mb_convert_encoding() will no longer return the following non text encodings: `"Base64"`, `"QPrint"`, `"UUencode"`, `"HTML entities"`, `"7 bit"` and `"8 bit"`.
8.0.0 | mb_convert_encoding() will now throw a ValueError when `to_encoding` is passed an invalid encoding.
8.0.0 | mb_convert_encoding() will now throw a ValueError when `from_encoding` is passed an invalid encoding.
8.0.0 | `from_encoding` is nullable now.
7.2.0 | This function now also accepts an array as `string`. Formerly, only strings have been supported.

### Examples

Example #1 mb_convert_encoding() example

`<?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");
/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");
/* If mbstring.language is "Japanese", "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>`

### See Also

- mb_detect_order() - Set/Get character encoding detection order
- UConverter::transcode() - Convert a string from one character encoding to another
- iconv() - Convert a string from one character encoding to another

# mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

### Description

mb_convert_kana(string `$string`, string `$mode` = "KV", ?string `$encoding` = `null`): string

Performs a "han-kaku" - "zen-kaku" conversion for string `string`. This function is only useful for Japanese.

### Parameters

`string`

  The string being converted.

`mode`

  The conversion option.

  Specify with a combination of following options.

  Applicable Conversion Options
  Option | Meaning
  --- | ---
  `r` | Convert "zen-kaku" alphabets to "han-kaku"
  `R` | Convert "han-kaku" alphabets to "zen-kaku"
  `n` | Convert "zen-kaku" numbers to "han-kaku"
  `N` | Convert "han-kaku" numbers to "zen-kaku"
  `a` | Convert "zen-kaku" alphabets and numbers to "han-kaku"
  `A` | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
  `s` | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
  `S` | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
  `k` | Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
  `K` | Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
  `h` | Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
  `H` | Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
  `c` | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
  `C` | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
  `V` | Collapse voiced sound notation and convert them into a character. Use with "K","H"

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The converted string.

### Errors/Exceptions

Throws a ValueError if the combination of different `mode`s is invalid. For example `"sS"`.

### Changelog

Version | Description
--- | ---
8.2.0 | A ValueError is now thrown if the combination of different `mode`s is invalid.
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 mb_convert_kana() example

`<?php
/* Convert all "han-kaku" "kata-kana" to "zen-kaku" "hira-gana" */
echo mb_convert_kana('ﾔﾏﾀﾞ ﾊﾅｺ', "HV") . "\n";
/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
and "zen-kaku" alphanumeric to "han-kaku" */
echo mb_convert_kana('ｺｳｻﾞﾊﾞﾝｺﾞｳ ０１２３４５６', "KVa") . "\n";
?>`

The above example will output:

    やまだ はなこ
    コウザバンゴウ 0123456

# mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_variables — Convert character code in variable(s)

### Description

mb_convert_variables(
string `$to_encoding`,
array|string `$from_encoding`,
mixed `&$var`,
mixed `&...$vars`
): string|false

Converts character encoding of variables `var` and `vars` in encoding `from_encoding` to encoding `to_encoding`.

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

### Parameters

`to_encoding`

  The encoding that the string is being converted to.

`from_encoding`

  `from_encoding` is specified as an array or comma separated string, it tries to detect encoding from `from-coding`. When `from_encoding` is omitted, `detect_order` is used.

`var`

  `var` is the reference to the variable being converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

`vars`

  Additional `var`s.

### Return Values

The character encoding before conversion for success, or `false` for failure.

### Examples

Example #1 mb_convert_variables() example

`<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>`

# mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_decode_mimeheader — Decode string in MIME header field

### Description

mb_decode_mimeheader(string `$string`): string

Decodes encoded-word string `string` in MIME header.

### Parameters

`string`

  The string being decoded.

### Return Values

The decoded string in internal character encoding.

### Changelog

Version | Description
--- | ---
8.3.0 | Underscores are converted to spaces as specified by » RFC 2047.

### See Also

- mb_encode_mimeheader() - Encode string for MIME header

# mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_decode_numericentity — Decode HTML numeric string reference to character

### Description

mb_decode_numericentity(string `$string`, array `$map`, ?string `$encoding` = `null`): string

Convert numeric string reference of string `string` in a specified block to character.

### Parameters

`string`

  The string being decoded.

`map`

  `map` is an array that specifies the code area to convert.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The converted string.

### Errors/Exceptions

Throws a ValueError if `map` is not a list of ints.

### Changelog

Version | Description
--- | ---
8.4.0 | mb_decode_numericentity() now throws a ValueError if `map` is not a list of ints.
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 `map` example

`<?php
$convmap = array (
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
// ........
int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.
?>`

Example #2 `map` example escapes JavaScript string

`<?php
function escape_javascript_string($str) {
$map = [
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,0,0, // 49
0,0,0,0,0,0,0,0,1,1,
1,1,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,0,0,0, // 99
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 149
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 199
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 249
1,1,1,1,1,1,1, // 255
];
// Char encoding is UTF-8
$mblen = mb_strlen($str, 'UTF-8');
$utf32 = bin2hex(mb_convert_encoding($str, 'UTF-32', 'UTF-8'));
for ($i=0, $encoded=''; $i < $mblen; $i++) {
$u = substr($utf32, $i*8, 8);
$v = base_convert($u, 16, 10);
if ($v < 256 && $map[$v]) {
$encoded .= '\\x'.substr($u, 6,2);
} else if ($v == 2028) {
$encoded .= '\\u2028';
} else if ($v == 2029) {
$encoded .= '\\u2029';
} else {
$encoded .= mb_convert_encoding(hex2bin($u), 'UTF-8', 'UTF-32');
}
}
return $encoded;
}
// Test data
$convmap = [ 0x0, 0xffff, 0, 0xffff ];
$msg = '';
for ($i=0; $i < 1000; $i++) {
// chr() cannot generate correct UTF-8 data larger value than 128, use mb_decode_numericentity().
$msg .= mb_decode_numericentity('&#'.$i.';', $convmap, 'UTF-8');
}
// var_dump($msg);
var_dump(escape_javascript_string($msg));`

### See Also

- mb_encode_numericentity() - Encode character to HTML numeric string reference

# mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_detect_encoding — Detect character encoding

### Description

mb_detect_encoding(string `$string`, array|string|null `$encodings` = `null`, bool `$strict` = `false`): string|false

Detects the most likely character encoding for string `string` from a list of candidates.

As of PHP 8.1 this function uses heuristics to detect which of the valid text encodings in the specified list is most likely to be correct and may not be in order of `encodings` provided.

Automatic detection of the intended character encoding can never be entirely reliable; without some additional information, it is similar to decoding an encrypted string without the key. It is always preferable to use an indication of character encoding stored or transmitted with the data, such as a "Content-Type" HTTP header.

This function is most useful with multibyte encodings, where not all sequences of bytes form a valid string. If the input string contains such a sequence, that encoding will be rejected.

Warning

# The result is not accurate

The name of this function is misleading, it performs "guessing" rather than "detection".

The guesses are far from accurate, and therefore you cannot use this function to accurately detect the correct character encoding.

### Parameters

`string`

  The string being inspected.

`encodings`

  A list of character encodings to try. The list may be specified as an array of strings, or a single string separated by commas.

  If `encodings` is omitted or `null`, the current detect_order (set with the mbstring.detect_order configuration option, or mb_detect_order() function) will be used.

`strict`

  Controls the behaviour when `string` is not valid in any of the listed `encodings`. If `strict` is set to `false`, the closest matching encoding will be returned; if `strict` is set to `true`, `false` will be returned.

  The default value for `strict` can be set with the mbstring.strict_detection configuration option.

### Return Values

The detected character encoding, or `false` if the string is not valid in any of the listed encodings.

### Changelog

Version | Description
--- | ---
8.2.0 | mb_detect_encoding() will no longer return the following non text encodings: `"Base64"`, `"QPrint"`, `"UUencode"`, `"HTML entities"`, `"7 bit"` and `"8 bit"`.

### Examples

Example #1 mb_detect_encoding() example

`<?php
$str = "\x95\xB6\x8E\x9A\x83\x52\x81\x5B\x83\x68";
// Detect character encoding with current detect_order
var_dump(mb_detect_encoding($str));
// "auto" is expanded according to mbstring.language
var_dump(mb_detect_encoding($str, "auto"));
// Specify "encodings" parameter by list separated by comma
var_dump(mb_detect_encoding($str, "JIS, eucjp-win, sjis-win"));
// Use array to specify "encodings" parameter
$encodings = [
"ASCII",
"JIS",
"EUC-JP"
];
var_dump(mb_detect_encoding($str, $encodings));
?>`

The above example will output:

    string(5) "ASCII"
    string(5) "ASCII"
    string(8) "SJIS-win"
    string(5) "ASCII"

Example #2 Effect of `strict` parameter

`<?php
// 'áéóú' encoded in ISO-8859-1
$str = "\xE1\xE9\xF3\xFA";
// The string is not valid ASCII or UTF-8, but UTF-8 is considered a closer match
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], true));
// If a valid encoding is found, the strict parameter does not change the result
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], true));
?>`

The above example will output:

    string(5) "UTF-8"
    bool(false)
    string(10) "ISO-8859-1"
    string(10) "ISO-8859-1"

In some cases, the same sequence of bytes may form a valid string in multiple character encodings, and it is impossible to know which interpretation was intended. For instance, among many others, the byte sequence "\xC4\xA2" could be:

- "Ä¢" (U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS followed by U+00A2 CENT SIGN) encoded in any of ISO-8859-1, ISO-8859-15, or Windows-1252
- "ФЂ" (U+0424 CYRILLIC CAPITAL LETTER EF followed by U+0402 CYRILLIC CAPITAL LETTER DJE) encoded in ISO-8859-5
- "Ģ" (U+0122 LATIN CAPITAL LETTER G WITH CEDILLA) encoded in UTF-8

Example #3 Effect of order when multiple encodings match

`<?php
$str = "\xC4\xA2";
// The string is valid in all three encodings, but the first one listed may not always be the one returned
var_dump(mb_detect_encoding($str, ['UTF-8']));
var_dump(mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'ISO-8859-5'])); // as of php8.1 this returns ISO-8859-1 instead of UTF-8
var_dump(mb_detect_encoding($str, ['ISO-8859-1', 'ISO-8859-5', 'UTF-8']));
var_dump(mb_detect_encoding($str, ['ISO-8859-5', 'UTF-8', 'ISO-8859-1']));
?>`

The above example will output:

    string(5) "UTF-8"
    string(10) "ISO-8859-1"
    string(10) "ISO-8859-1"
    string(10) "ISO-8859-5"

### See Also

- mb_detect_order() - Set/Get character encoding detection order

# mb_detect_order

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_detect_order — Set/Get character encoding detection order

### Description

mb_detect_order(array|string|null `$encoding` = `null`): array|bool

Sets the automatic character encoding detection order to `encoding`.

### Parameters

`encoding`

  `encoding` is an array or comma separated list of character encoding. See supported encodings.

  If `encoding` is omitted or `null`, it returns the current character encoding detection order as array.

  This setting affects mb_detect_encoding() and mb_send_mail().

  `mbstring` currently implements the following encoding detection filters. If there is an invalid byte sequence for the following encodings, encoding detection will fail.

  `UTF-8`, `UTF-7`, `ASCII`, `EUC-JP`,`SJIS`, `eucJP-win`, `SJIS-win`, `JIS`, `ISO-2022-JP`

  For `ISO-8859-*`, `mbstring` always detects as `ISO-8859-*`.

  For `UTF-16`, `UTF-32`, `UCS2` and `UCS4`, encoding detection will fail always.

### Return Values

When setting the encoding detection order, `true` is returned on success or `false` on failure.

When getting the encoding detection order, an ordered array of the encodings is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 mb_detect_order() examples

`<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");
/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);
/* Display current detection order */
echo implode(", ", mb_detect_order());
?>`

Example #2 Example showing useless detect orders

    ; Always detect as ISO-8859-1
    detect_order = ISO-8859-1, UTF-8

    ; Always detect as UTF-8, since ASCII/UTF-7 values are
    ; valid for UTF-8
    detect_order = UTF-8, ASCII, UTF-7

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_http_input() - Detect HTTP input character encoding
- mb_http_output() - Set/Get HTTP output character encoding
- mb_send_mail() - Send encoded mail

# mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_encode_mimeheader — Encode string for MIME header

### Description

mb_encode_mimeheader(
string `$string`,
?string `$charset` = `null`,
?string `$transfer_encoding` = `null`,
string `$newline` = "\r\n",
int `$indent` = 0
): string

Encodes a given string `string` by the MIME header encoding scheme.

### Parameters

`string`

  The string being encoded. Its encoding should be same as mb_internal_encoding().

`charset`

  `charset` specifies the name of the character set in which `string` is represented in. The default value is determined by the current NLS setting (`mbstring.language`).

`transfer_encoding`

  `transfer_encoding` specifies the scheme of MIME encoding. It should be either `"B"` (Base64) or `"Q"` (Quoted-Printable). Falls back to `"B"` if not given.

`newline`

  `newline` specifies the EOL (end-of-line) marker with which mb_encode_mimeheader() performs line-folding (a » RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to `"\r\n"` (CRLF) if not given.

`indent`

  Indentation of the first line (number of characters in the header before `string`).

### Return Values

A converted version of the string represented in ASCII.

### Changelog

Version | Description
--- | ---
8.3.0 | `NUL` (0) bytes are no longer dropped when encoded using Quoted-Printable encoding, but encoded as `=00`.
8.0.0 | `charset` and `transfer_encoding` are nullable now.

### Examples

Example #1 mb_encode_mimeheader() example

`<?php
$name = "太郎"; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = '"' . addcslashes(mb_encode_mimeheader($name, "UTF-7", "Q"), '"') . '" <' . $mbox . "@" . $doma . ">";
echo $addr;
?>`

The above example will output:

    "=?UTF-7?Q?+WSqQzg-?=" <kru@gtinn.mon>

### Notes

> Note:

> This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.

### See Also

- mb_decode_mimeheader() - Decode string in MIME header field

# mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_encode_numericentity — Encode character to HTML numeric string reference

### Description

mb_encode_numericentity(
string `$string`,
array `$map`,
?string `$encoding` = `null`,
bool `$hex` = `false`
): string

Converts specified character codes in string `string` from character code to HTML numeric character reference.

### Parameters

`string`

  The string being encoded.

`map`

  `map` is array specifies code area to convert.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

`hex`

  Whether the returned entity reference should be in hexadecimal notation (otherwise it is in decimal notation).

### Return Values

The converted string.

### Errors/Exceptions

Throws a ValueError if `map` is not a list of ints.

### Changelog

Version | Description
--- | ---
8.4.0 | mb_encode_numericentity() now throws a ValueError if `map` is not a list of ints.
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 `map` example

`<?php
$convmap = array (
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
........
int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.
?>`

Example #2 mb_encode_numericentity() example

`<?php
$str = "aAæÆあア𩸽";
/* Convert all UTF8 characters up to 4 bytes to HTML numeric character reference */
$convmap = [0, 0x1FFFFF, 0, 0x10FFFF];
var_dump(mb_encode_numericentity($str, $convmap, "utf8"));
/* Converts only 2-byte and 4-byte UTF8 characters to HTML numeric character reference */
$convmap = [
0x80, 0x7FF, 0, 0x10FFFF,
0x10000, 0x1FFFFF, 0, 0x10FFFF,
];
var_dump(mb_encode_numericentity($str, $convmap, "utf8"));
?>`

The above example will output:

    string(46) "&#97;&#65;&#230;&#198;&#12354;&#12450;&#40509;"
    string(28) "aA&#230;&#198;あア&#40509;"

### See Also

- mb_decode_numericentity() - Decode HTML numeric string reference to character

# mb_encoding_aliases

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mb_encoding_aliases — Get aliases of a known encoding type

### Description

mb_encoding_aliases(string `$encoding`): array

Returns an array of aliases for a known `encoding` type.

### Parameters

`encoding`

  The encoding type being checked, for aliases.

### Return Values

Returns a numerically indexed array of encoding aliases.

### Errors/Exceptions

Throws a ValueError if `encoding` is unknown.

### Changelog

Version | Description
--- | ---
8.0.0 | If the `encoding` is unknown, a ValueError is now thrown; previously an `E_WARNING` was emitted, and the function returned `false`.

### Examples

Example #1 mb_encoding_aliases() example

`<?php
$encoding = 'ASCII';
$known_encodings = mb_list_encodings();
if (in_array($encoding, $known_encodings)) {
$aliases = mb_encoding_aliases($encoding);
print_r($aliases);
} else {
echo "Unknown ($encoding) encoding.\n";
}
?>`

The above example will output something similar to:

    Array
    (
        [0] => ANSI_X3.4-1968
        [1] => iso-ir-6
        [2] => ANSI_X3.4-1986
        [3] => ISO_646.irv:1991
        [4] => US-ASCII
        [5] => ISO646-US
        [6] => us
        [7] => IBM367
        [8] => cp367
        [9] => csASCII
    )

### See Also

- mb_list_encodings() - Returns an array of all supported encodings

# mb_ereg

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg — Regular expression match with multibyte support

### Description

mb_ereg(string `$pattern`, string `$string`, array `&$matches` = `null`): bool

Executes the regular expression match with multibyte support.

### Parameters

`pattern`

  The search pattern.

`string`

  The search string.

`matches`

  If matches are found for parenthesized substrings of `pattern` and the function is called with the third argument `matches`, the matches will be stored in the elements of the array `matches`. If no matches are found, `matches` is set to an empty array.

  $matches[1] will contain the substring which starts at the first left parenthesis; $matches[2] will contain the substring starting at the second, and so on. $matches[0] will contain a copy of the complete string matched.

### Return Values

Returns whether `pattern` matches `string`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function returns `true` on success now. Previously, it returned the byte length of the matched string if a match for `pattern` was found in `string` and `matches` was passed. If the optional parameter `matches` was not passed or the length of the matched string was `0`, this function returned `1`.
7.1.0 | mb_ereg() will now set `matches` to an empty array, if nothing matched. Formerly, `matches` was not modified in that case.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_eregi() - Regular expression match ignoring case with multibyte support

# mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_match — Regular expression match for multibyte string

### Description

mb_ereg_match(string `$pattern`, string `$string`, ?string `$options` = `null`): bool

A regular expression match for a multibyte string

> Note: `pattern` is only matched at the beginning of `string`.

### Parameters

`pattern`

  The regular expression pattern.

`string`

  The string being evaluated.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

Returns `true` if `string` matches the regular expression `pattern`, `false` if not.

### Changelog

Version | Description
--- | ---
8.0.0 | `options` is nullable now.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg() - Regular expression match with multibyte support

# mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_replace — Replace regular expression with multibyte support

### Description

mb_ereg_replace(
string `$pattern`,
string `$replacement`,
string `$string`,
?string `$options` = `null`
): string|false|null

Scans `string` for matches to `pattern`, then replaces the matched text with `replacement`

### Parameters

`pattern`

  The regular expression pattern.

  Multibyte characters may be used in `pattern`.

`replacement`

  The replacement text.

`string`

  The string being checked.

`options`
  The search option. See mb_regex_set_options() for explanation.

### Return Values

The resultant string on success, or `false` on error. If `string` is not valid for the current encoding, `null` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `options` is nullable now.
7.1.0 | The function checks whether `string` is valid for the current encoding.
7.1.0 | The `e` modifier has been deprecated.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the `e` modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

# mb_ereg_replace_callback

(PHP 5 >= 5.4.1, PHP 7, PHP 8)

mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback

### Description

mb_ereg_replace_callback(
string `$pattern`,
callable `$callback`,
string `$string`,
?string `$options` = `null`
): string|false|null

Scans `string` for matches to `pattern`, then replaces the matched text with the output of `callback` function.

The behavior of this function is almost identical to mb_ereg_replace(), except for the fact that instead of `replacement` parameter, one should specify a `callback`.

### Parameters

`pattern`

  The regular expression pattern.

  Multibyte characters may be used in `pattern`.

`callback`

  A callback that will be called and passed an array of matched elements in the `string` string. The callback should return the replacement string.

  You'll often need the `callback` function for a mb_ereg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to mb_ereg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

`string`

  The string being checked.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

The resultant string on success, or `false` on error. If `string` is not valid for the current encoding, `null` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `options` is nullable now.
7.1.0 | The function checks whether `string` is valid for the current encoding.

### Examples

Example #1 mb_ereg_replace_callback() example

`<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
"next_year",
$text);
?>`

The above example will output:

    April fools day is 04/01/2003
    Last christmas was 12/24/2002

Example #2 mb_ereg_replace_callback() using anonymous function

`<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
function ($matches) {
return $matches[1].($matches[2]+1);
},
$text);
?>`

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_replace() - Replace regular expression with multibyte support
- Anonymous functions

# mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

### Description

mb_ereg_search(?string `$pattern` = `null`, ?string `$options` = `null`): bool

Performs a multibyte regular expression match for a predefined multibyte string.

### Parameters

`pattern`

  The search pattern.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

mb_ereg_search() returns `true` if the multibyte string matches with the regular expression, or `false` otherwise. The string for matching is set by mb_ereg_search_init(). If `pattern` is not specified, the previous one is used.

### Changelog

Version | Description
--- | ---
8.0.0 | `pattern` and `options` are nullable now.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

# mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_getpos — Returns start point for next regular expression match

### Description

mb_ereg_search_getpos(): int

Returns the start point for the next regular expression match.

### Parameters

This function has no parameters.

### Return Values

mb_ereg_search_getpos() returns the point to start regular expression match for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). The position is represented by bytes from the head of string.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_setpos() - Set start point of next regular expression match

# mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

### Description

mb_ereg_search_getregs(): array|false

Retrieve the result from the last multibyte regular expression match

### Parameters

This function has no parameters.

### Return Values

An array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some matches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns `false` on error.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

# mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

### Description

mb_ereg_search_init(string `$string`, ?string `$pattern` = `null`, ?string `$options` = `null`): bool

mb_ereg_search_init() sets `string` and `pattern` for a multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), and mb_ereg_search_regs().

### Parameters

`string`

  The search string.

`pattern`

  The search pattern.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `pattern` and `options` are nullable now.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

# mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

### Description

mb_ereg_search_pos(?string `$pattern` = `null`, ?string `$options` = `null`): array|false

Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

### Parameters

`pattern`

  The search pattern.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

An array containing two elements. The first element is the offset, in bytes, where the match begins relative to the start of the search string, and the second element is the length in bytes of the match.

If an error occurs, `false` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `pattern` and `options` are nullable now.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

# mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

### Description

mb_ereg_search_regs(?string `$pattern` = `null`, ?string `$options` = `null`): array|false

Returns the matched part of a multibyte regular expression.

### Parameters

`pattern`

  The search pattern.

`options`

  The search option. See mb_regex_set_options() for explanation.

### Return Values

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | `pattern` and `options` are nullable now.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

# mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_setpos — Set start point of next regular expression match

### Description

mb_ereg_search_setpos(int `$offset`): bool

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

### Parameters

`offset`

  The position to set. If it is negative, it counts from the end of the string.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
7.1.0 | Support for negative `offset`s has been added.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

# mb_eregi

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_eregi — Regular expression match ignoring case with multibyte support

### Description

mb_eregi(string `$pattern`, string `$string`, array `&$matches` = `null`): bool

Executes the case insensitive regular expression match with multibyte support.

### Parameters

`pattern`

  The regular expression pattern.

`string`

  The string being searched.

`matches`

  If matches are found for parenthesized substrings of `pattern` and the function is called with the third argument `matches`, the matches will be stored in the elements of the array `matches`. If no matches are found, `matches` is set to an empty array.

  $matches[1] will contain the substring which starts at the first left parenthesis; $matches[2] will contain the substring starting at the second, and so on. $matches[0] will contain a copy of the complete string matched.

### Return Values

Returns whether `pattern` matches `string`.

### Changelog

Version | Description
--- | ---
8.0.0 | This function returns `true` on success now. Previously, it returned the byte length of the matched string if a match for `pattern` was found in `string` and `matches` was passed. If the optional parameter `matches` was not passed or the length of the matched string was `0`, this function returned `1`.
7.1.0 | mb_eregi() will now set `matches` to an empty array, if nothing matched. Formerly, `matches` was not modified in that case.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg() - Regular expression match with multibyte support

# mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

### Description

mb_eregi_replace(
string `$pattern`,
string `$replacement`,
string `$string`,
?string `$options` = `null`
): string|false|null

Scans `string` for matches to `pattern`, then replaces the matched text with `replacement`.

### Parameters

`pattern`

  The regular expression pattern. Multibyte characters may be used. The case will be ignored.

`replacement`

  The replacement text.

`string`

  The searched string.

`options`
  The search option. See mb_regex_set_options() for explanation.

### Return Values

The resultant string or `false` on error. If `string` is not valid for the current encoding, `null` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `options` is nullable now.
7.1.0 | The function checks whether `string` is valid for the current encoding.
7.1.0 | The `e` modifier has been deprecated.

### Notes

> Note:

> The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the `e` modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg_replace() - Replace regular expression with multibyte support

# mb_get_info

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_get_info — Get internal settings of mbstring

### Description

mb_get_info(string `$type` = "all"): array|string|int|false|null

mb_get_info() returns the internal setting parameters of mbstring.

### Parameters

`type`

  If `type` is not specified or is specified as `"all"`, `"internal_encoding"`, `"http_input"`, `"http_output"`, `"http_output_conv_mimetypes"`, `"mail_charset"`, `"mail_header_encoding"`, `"mail_body_encoding"`, `"illegal_chars"`, `"encoding_translation"`, `"language"`, `"detect_order"`, `"substitute_character"` and `"strict_detection"` will be returned.

  If `type` is specified as `"internal_encoding"`, `"http_input"`, `"http_output"`, `"http_output_conv_mimetypes"`, `"mail_charset"`, `"mail_header_encoding"`, `"mail_body_encoding"`, `"illegal_chars"`, `"encoding_translation"`, `"language"`, `"detect_order"`, `"substitute_character"` or `"strict_detection"` the specified setting parameter will be returned.

### Return Values

An array of type information if `type` is not specified, otherwise a specific `type`, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | The `type`s `"func_overload"` and `"func_overload_list"` are no longer supported.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_http_output() - Set/Get HTTP output character encoding

# mb_http_input

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_http_input — Detect HTTP input character encoding

### Description

mb_http_input(?string `$type` = `null`): array|string|false

Detects the HTTP input character encoding.

### Parameters

`type`

  Input string specifies the input type. `"G"` for GET, `"P"` for POST, `"C"` for COOKIE, `"S"` for string, `"L"` for list, and `"I"` for the whole list (will return array). If type is omitted, it returns the last input type processed.

### Return Values

The character encoding name, as per the `type`, or an array of character encoding names, if `type` is `"I"`. If mb_http_input() does not process specified HTTP input, it returns `false`.

### Errors/Exceptions

Throws a ValueError if `type` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | mb_http_input() now throws a ValueError if `type` is invalid.
8.0.0 | `type` is nullable now.

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_http_output() - Set/Get HTTP output character encoding
- mb_detect_order() - Set/Get character encoding detection order

# mb_http_output

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_http_output — Set/Get HTTP output character encoding

### Description

mb_http_output(?string `$encoding` = `null`): string|bool

Set/Get the HTTP output character encoding. Output after this function is called will be converted from the set internal encoding to `encoding`.

### Parameters

`encoding`

  If `encoding` is set, mb_http_output() sets the HTTP output character encoding to `encoding`.

  If `encoding` is omitted, mb_http_output() returns the current HTTP output character encoding.

### Return Values

If `encoding` is omitted, mb_http_output() returns the current HTTP output character encoding. Otherwise, Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws a ValueError if `encoding` contains null bytes.

### Changelog

Version | Description
--- | ---
8.4.0 | mb_http_output() now throws a ValueError if `encoding` contains null bytes.
8.0.0 | `encoding` is nullable now.

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_http_input() - Detect HTTP input character encoding
- mb_detect_order() - Set/Get character encoding detection order

# mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_internal_encoding — Set/Get internal character encoding

### Description

mb_internal_encoding(?string `$encoding` = `null`): string|bool

Set/Get the internal character encoding

### Parameters

`encoding`

  `encoding` is the character encoding name used for the HTTP input character encoding conversion, HTTP output character encoding conversion, and the default character encoding for string functions defined by the mbstring module. You should notice that the internal encoding is totally different from the one for multibyte regex.

### Return Values

If `encoding` is set, then Returns `true` on success or `false` on failure. In this case, the character encoding for multibyte regex is NOT changed. If `encoding` is omitted, then the current character encoding name is returned.

### Errors/Exceptions

As of PHP 8.0.0, a ValueError is thrown if the value of `encoding` is an invalid encoding. Prior to PHP 8.0.0, a `E_WARNING` was emitted instead.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.
8.0.0 | Now throws a ValueError if `encoding` is an invalid encoding. Previously a `E_WARNING` was emitted instead.

### Examples

Example #1 mb_internal_encoding() example

`<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");
/* Display current internal character encoding */
echo mb_internal_encoding();
?>`

### See Also

- mb_http_input() - Detect HTTP input character encoding
- mb_http_output() - Set/Get HTTP output character encoding
- mb_detect_order() - Set/Get character encoding detection order
- mb_regex_encoding() - Set/Get character encoding for multibyte regex

# mb_language

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_language — Set/Get current language

### Description

mb_language(?string `$language` = `null`): string|bool

Set/Get the current language.

### Parameters

`language`

  Used for encoding e-mail messages. The valid languages are listed in the following table. mb_send_mail() uses this setting to encode e-mail.

  Language | Charset | Encoding | Alias
  --- | --- | --- | ---
  German/de | ISO-8859-15 | Quoted-Printable | Deutsch
  English/en | ISO-8859-1 | Quoted-Printable |
  Armenian/hy | ArmSCII-8 | Quoted-Printable |
  Japanese/ja | ISO-2022-JP | BASE64 |
  Korean/ko | ISO-2022-KR | BASE64 |
  neutral | UTF-8 | BASE64 |
  Russian/ru | KOI8-R | Quoted-Printable |
  Turkish/tr | ISO-8859-9 | Quoted-Printable |
  Ukrainian/ua | KOI8-U | Quoted-Printable |
  uni | UTF-8 | BASE64 | universal
  Simplified Chinese/zh-cn | HZ | BASE64 |
  Traditional Chinese/zh-tw | BIG-5 | BASE64 |

### Return Values

If `language` is set and `language` is valid, it returns `true`. Otherwise, it returns `false`. When `language` is omitted or `null`, it returns the language name as a string.

### Changelog

Version | Description
--- | ---
8.0.0 | `language` is nullable now.

### See Also

- mb_send_mail() - Send encoded mail

# mb_lcfirst

(PHP 8 >= 8.4.0)

mb_lcfirst — Make a string's first character lowercase

### Description

mb_lcfirst(string `$string`, ?string `$encoding` = `null`): string

Performs a multi-byte safe lcfirst() operation, and returns a string with the first character of `string` lowercased.

### Parameters

`string`
  The input string.
`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the resulting string.

### See Also

- mb_ucfirst() - Make a string's first character uppercase
- lcfirst() - Make a string's first character lowercase

# mb_list_encodings

(PHP 5, PHP 7, PHP 8)

mb_list_encodings — Returns an array of all supported encodings

### Description

mb_list_encodings(): array

Returns an array containing all supported encodings.

### Parameters

This function has no parameters.

### Return Values

Returns a numerically indexed array.

### Errors/Exceptions

This function does not emit any errors.

### Examples

Example #1 mb_list_encodings() example

`<?php
print_r(mb_list_encodings());
?>`

The above example will output something similar to:

    Array
    (
        [0] => pass
        [1] => auto
        [2] => wchar
        [3] => byte2be
        [4] => byte2le
        [5] => byte4be
        [6] => byte4le
        [7] => BASE64
        [8] => UUENCODE
        [9] => HTML-ENTITIES
        [10] => Quoted-Printable
        [11] => 7bit
        [12] => 8bit
        [13] => UCS-4
        [14] => UCS-4BE
        [15] => UCS-4LE
        [16] => UCS-2
        [17] => UCS-2BE
        [18] => UCS-2LE
        [19] => UTF-32
        [20] => UTF-32BE
        [21] => UTF-32LE
        [22] => UTF-16
        [23] => UTF-16BE
        [24] => UTF-16LE
        [25] => UTF-8
        [26] => UTF-7
        [27] => UTF7-IMAP
        [28] => ASCII
        [29] => EUC-JP
        [30] => SJIS
        [31] => eucJP-win
        [32] => SJIS-win
        [33] => JIS
        [34] => ISO-2022-JP
        [35] => Windows-1252
        [36] => ISO-8859-1
        [37] => ISO-8859-2
        [38] => ISO-8859-3
        [39] => ISO-8859-4
        [40] => ISO-8859-5
        [41] => ISO-8859-6
        [42] => ISO-8859-7
        [43] => ISO-8859-8
        [44] => ISO-8859-9
        [45] => ISO-8859-10
        [46] => ISO-8859-13
        [47] => ISO-8859-14
        [48] => ISO-8859-15
        [49] => EUC-CN
        [50] => CP936
        [51] => HZ
        [52] => EUC-TW
        [53] => BIG-5
        [54] => EUC-KR
        [55] => UHC
        [56] => ISO-2022-KR
        [57] => Windows-1251
        [58] => CP866
        [59] => KOI8-R
    )

### See Also

- mb_encoding_aliases() - Get aliases of a known encoding type

# mb_ltrim

(PHP 8 >= 8.4.0)

mb_ltrim — Strip whitespace (or other characters) from the beginning of a string

### Description

mb_ltrim(string `$string`, ?string `$characters` = `null`, ?string `$encoding` = `null`): string

Performs a multi-byte safe ltrim() operation. Strip whitespace (or other characters) from the beginning of a string.

Without the second parameter, mb_ltrim() will strip these characters:

- `" "` (Unicode U+0020), an ordinary space.
- `"\t"` (Unicode U+0009), a tab.
- `"\n"` (Unicode U+000A), a new line (line feed).
- `"\r"` (Unicode U+000D), a carriage return.
- `"\0"` (Unicode U+0000), the NUL-byte.
- `"\v"` (Unicode U+000B), a vertical tab.
- `"\f"` (Unicode U+000C), a form feed.
- `"\u00A0"` (Unicode U+00A0), a NO-BREAK SPACE.
- `"\u1680"` (Unicode U+1680), a OGHAM SPACE MARK.
- `"\u2000"` (Unicode U+2000), a EN QUAD.
- `"\u2001"` (Unicode U+2001), a EM QUAD.
- `"\u2002"` (Unicode U+2002), a EN SPACE.
- `"\u2003"` (Unicode U+2003), a EM SPACE.
- `"\u2004"` (Unicode U+2004), a THREE-PER-EM SPACE.
- `"\u2005"` (Unicode U+2005), a FOUR-PER-EM SPACE.
- `"\u2006"` (Unicode U+2006), a SIX-PER-EM SPACE.
- `"\u2007"` (Unicode U+2007), a FIGURE SPACE.
- `"\u2008"` (Unicode U+2008), a PUNCTUATION SPACE.
- `"\u2009"` (Unicode U+2009), a THIN SPACE.
- `"\u200A"` (Unicode U+200A), a HAIR SPACE.
- `"\u2028"` (Unicode U+2028), a LINE SEPARATOR.
- `"\u2029"` (Unicode U+2029), a PARAGRAPH SEPARATOR.
- `"\u202F"` (Unicode U+202F), a NARROW NO-BREAK SPACE.
- `"\u205F"` (Unicode U+205F), a MEDIUM MATHEMATICAL SPACE.
- `"\u3000"` (Unicode U+3000), a IDEOGRAPHIC SPACE.
- `"\u0085"` (Unicode U+0085), a NEXT LINE (NEL).
- `"\u180E"` (Unicode U+180E), a MONGOLIAN VOWEL SEPARATOR.

### Parameters

`string`
  The input string.
`characters`
  Optionally, the stripped characters can also be specified using the `characters` parameter. Simply list all characters that need to be stripped.
`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

This function returns a string with whitespace stripped from the beginning of `string`.

### See Also

- mb_trim() - Strip whitespace (or other characters) from the beginning and end of a string
- mb_rtrim() - Strip whitespace (or other characters) from the end of a string
- ltrim() - Strip whitespace (or other characters) from the beginning of a string

# mb_ord

(PHP 7 >= 7.2.0, PHP 8)

mb_ord — Get Unicode code point of character

### Description

mb_ord(string `$string`, ?string `$encoding` = `null`): int|false

Returns the Unicode code point value of the given character.

This function complements mb_chr().

### Parameters

`string`

  A string

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The Unicode code point for the first character of `string` or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 A basic mb_ord() example

`<?php
var_dump(mb_ord("A", "UTF-8"));
var_dump(mb_ord("🐘", "UTF-8"));
var_dump(mb_ord("\x80", "ISO-8859-1"));
var_dump(mb_ord("\x80", "Windows-1252"));
?>`

The above example will output:

int(65)
int(128024)
int(128)
int(8364)

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_chr() - Return character by Unicode code point value
- IntlChar::ord() - Return Unicode code point value of character
- ord() - Convert the first byte of a string to a value between 0 and 255

# mb_output_handler

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_output_handler — Callback function converts character encoding in output buffer

### Description

mb_output_handler(string `$string`, int `$status`): string

mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in the output buffer from internal character encoding to HTTP output character encoding.

### Parameters

`string`

  The contents of the output buffer.

`status`

  The status of the output buffer.

### Return Values

The converted string.

### Examples

Example #1 mb_output_handler() example

`<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>`

### Notes

> Note:

> If you want to output binary data, such as an image, a Content-Type: header must be set using header() before any binary data is sent to the client (e.g. header("Content-Type: image/png")). If Content-Type: header is sent, output character encoding conversion will not be performed.

> Note that if 'Content-Type: text/*' is sent, the content body is regarded as text; conversion will take place.

### See Also

- ob_start() - Turn on output buffering

# mb_parse_str

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_parse_str — Parse GET/POST/COOKIE data and set global variable

### Description

mb_parse_str(string `$string`, array `&$result`): bool

Parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only be used for GET data for now. It parses URL encoded data, detects encoding, converts coding to internal encoding and set values to the `result` array or global variables.

### Parameters

`string`

  The URL encoded data.

`result`

  An array containing decoded and character encoded converted values.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | The second parameter was no longer optional.
7.2.0 | Calling mb_parse_str() without the second parameter was deprecated.

### See Also

- mb_detect_order() - Set/Get character encoding detection order
- mb_internal_encoding() - Set/Get internal character encoding

# mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_preferred_mime_name — Get MIME charset string

### Description

mb_preferred_mime_name(string `$encoding`): string|false

Get a MIME charset string for a specific encoding.

### Parameters

`encoding`

  The encoding being checked.

### Return Values

The MIME `charset` string for character encoding `encoding`, or `false` if no charset is preferred for the given `encoding`.

### Examples

Example #1 mb_preferred_mime_name() example

`<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>`

# mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_regex_encoding — Set/Get character encoding for multibyte regex

### Description

mb_regex_encoding(?string `$encoding` = `null`): string|bool

Set/Get character encoding for a multibyte regex.

### Parameters

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

If `encoding` is set, then Returns `true` on success or `false` on failure. In this case, the internal character encoding is NOT changed. If `encoding` is omitted, then the current character encoding name for a multibyte regex is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- mb_ereg() - Regular expression match with multibyte support

# mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_regex_set_options — Set/Get the default options for mbregex functions

### Description

mb_regex_set_options(?string `$options` = `null`): string

Sets the default options described by `options` for multibyte regex functions.

### Parameters

`options`

  The options to set. This is a string where each character is an option. To set a mode, the mode character must be the last one set, however there can only be set one mode but multiple options.

  Regex options
  Option | Meaning | Changelog
  --- | --- | ---
  i | Ambiguity match on |
  x | Enables extended pattern form |
  m | `'.'` matches with newlines |
  s | `'^'` -> `'\A'`, `'$'` -> `'\Z'` |
  p | Same as both the `m` and `s` options |
  l | Finds longest matches |
  n | Ignores empty matches |
  e | eval() resulting code | Deprecated as of PHP 7.1.0 and removed as of PHP 8.0.0

  > Note:

  > The `"e"` option has no effect when set through mb_regex_set_options(). Use it with mb_ereg_replace() or mb_eregi_replace().

  Regex syntax modes (only one may be set)
  Mode | Meaning
  --- | ---
  j | Java (Sun java.util.regex)
  u | GNU regex
  g | grep
  c | Emacs
  r | Ruby
  z | Perl
  b | POSIX Basic regex
  d | POSIX Extended regex

### Return Values

The previous options. If `options` is omitted or `null`, it returns the string that describes the current options.

### Changelog

Version | Description
--- | ---
8.0.0 | If the parameter `options` is given and not `null`, the previous options are returned. Formerly, the current options have been returned.
8.0.0 | `options` is nullable now.
8.0.0 | The `"e"` option now throws a ValueError.
7.1.0 | The `"e"` option now emits an `E_DEPRECATED`.

### See Also

- mb_split() - Split multibyte string using regular expression
- mb_ereg() - Regular expression match with multibyte support
- mb_eregi() - Regular expression match ignoring case with multibyte support

# mb_rtrim

(PHP 8 >= 8.4.0)

mb_rtrim — Strip whitespace (or other characters) from the end of a string

### Description

mb_rtrim(string `$string`, ?string `$characters` = `null`, ?string `$encoding` = `null`): string

Performs a multi-byte safe rtrim() operation, and returns a string with whitespace (or other characters) stripped from the end of `string`.

Without the second parameter, mb_rtrim() will strip these characters:

- `" "` (Unicode U+0020), an ordinary space.
- `"\t"` (Unicode U+0009), a tab.
- `"\n"` (Unicode U+000A), a new line (line feed).
- `"\r"` (Unicode U+000D), a carriage return.
- `"\0"` (Unicode U+0000), the NUL-byte.
- `"\v"` (Unicode U+000B), a vertical tab.
- `"\f"` (Unicode U+000C), a form feed.
- `"\u00A0"` (Unicode U+00A0), a NO-BREAK SPACE.
- `"\u1680"` (Unicode U+1680), a OGHAM SPACE MARK.
- `"\u2000"` (Unicode U+2000), a EN QUAD.
- `"\u2001"` (Unicode U+2001), a EM QUAD.
- `"\u2002"` (Unicode U+2002), a EN SPACE.
- `"\u2003"` (Unicode U+2003), a EM SPACE.
- `"\u2004"` (Unicode U+2004), a THREE-PER-EM SPACE.
- `"\u2005"` (Unicode U+2005), a FOUR-PER-EM SPACE.
- `"\u2006"` (Unicode U+2006), a SIX-PER-EM SPACE.
- `"\u2007"` (Unicode U+2007), a FIGURE SPACE.
- `"\u2008"` (Unicode U+2008), a PUNCTUATION SPACE.
- `"\u2009"` (Unicode U+2009), a THIN SPACE.
- `"\u200A"` (Unicode U+200A), a HAIR SPACE.
- `"\u2028"` (Unicode U+2028), a LINE SEPARATOR.
- `"\u2029"` (Unicode U+2029), a PARAGRAPH SEPARATOR.
- `"\u202F"` (Unicode U+202F), a NARROW NO-BREAK SPACE.
- `"\u205F"` (Unicode U+205F), a MEDIUM MATHEMATICAL SPACE.
- `"\u3000"` (Unicode U+3000), a IDEOGRAPHIC SPACE.
- `"\u0085"` (Unicode U+0085), a NEXT LINE (NEL).
- `"\u180E"` (Unicode U+180E), a MONGOLIAN VOWEL SEPARATOR.

### Parameters

`string`
  The input string.
`characters`
  Optionally, the stripped characters can also be specified using the `characters` parameter. Simply list all characters that need to be stripped.
`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the modified string.

### See Also

- mb_trim() - Strip whitespace (or other characters) from the beginning and end of a string
- mb_ltrim() - Strip whitespace (or other characters) from the beginning of a string
- rtrim() - Strip whitespace (or other characters) from the end of a string

# mb_scrub

(PHP 7 >= 7.2.0, PHP 8)

mb_scrub — Replace ill-formed byte sequences with the substitute character

### Description

mb_scrub(string `$string`, ?string `$encoding` = `null`): string

Perform a character set conversion from the specified encoding, or the default encoding if no encoding was specified, to the same encoding. This has the effect of replacing any invalid byte sequences with the substitute character.

### Parameters

`string`

  The input string.

`encoding`

  The encoding used to interpret `string`. If it is omitted or `null`, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting will be used.

### Return Values

The string result with invalid byte sequences replaced.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

# mb_send_mail

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_send_mail — Send encoded mail

### Description

mb_send_mail(
string `$to`,
string `$subject`,
string `$message`,
array|string `$additional_headers` = [],
?string `$additional_params` = `null`
): bool

Sends email. Headers and messages are converted and encoded according to the mb_language() setting. It's a wrapper function for mail(), so see also mail() for details.

### Parameters

`to`

  The mail addresses being sent to. Multiple recipients may be specified by putting a comma between each address in `to`. This parameter is not automatically encoded.

`subject`

  The subject of the mail.

`message`

  The message of the mail.

`additional_headers` (optional)

  String or array to be inserted at the end of the email header.

  This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). Validate parameter not to be injected unwanted headers by attackers.

  If an array is passed, its keys are the header names and its values are the respective header values.

  > Note:

  > When sending mail, the mail must contain a `From` header. This can be set with the `additional_headers` parameter, or a default can be set in php.ini.

  > Failing to do this will result in an error message similar to `Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing`. The `From` header sets also `Return-Path` under Windows.

  > Note:

  > If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

`additional_params`

  `additional_params` is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

  This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add additional parameters. For security reason, this parameter should be validated.

  Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters mail() cannot be used.

  The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `additional_params` is nullable now.
7.2.0 | The `additional_headers` parameter now also accepts an array.

### See Also

- mail() - Send mail
- mb_encode_mimeheader() - Encode string for MIME header
- mb_language() - Set/Get current language

# mb_split

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_split — Split multibyte string using regular expression

### Description

mb_split(string `$pattern`, string `$string`, int `$limit` = -1): array|false

Split a multibyte `string` using regular expression `pattern` and returns the result as an array.

### Parameters

`pattern`

  The regular expression pattern.

`string`

  The string being split.

`limit`
  If optional parameter `limit` is specified, it will be split in `limit` elements as maximum.

### Return Values

The result as an array, or `false` on failure.

### Notes

> Note:

> The character encoding specified by mb_regex_encoding() will be used as the character encoding for this function by default.

### See Also

- mb_regex_encoding() - Set/Get character encoding for multibyte regex
- mb_ereg() - Regular expression match with multibyte support
- explode() - Split a string by a string

# mb_str_pad

(PHP 8 >= PHP 8.3.0)

mb_str_pad — Pad a multibyte string to a certain length with another multibyte string

### Description

mb_str_pad(
string `$string`,
int `$length`,
string `$pad_string` = " ",
int `$pad_type` = `STR_PAD_RIGHT`,
?string `$encoding` = `null`
): string

This function returns the `string` padded on the left, the right, or both sides to the specified padding length, where the length is measured in Unicode codepoints. If the optional argument `pad_string` is not supplied, the `string` is padded with spaces, otherwise it is padded with characters from `pad_string` up to the limit.

### Parameters

`string`

  The input string.

`length`

  If the value of `length` is negative, less than, or equal to the length of the input string, no padding takes place, and `string` will be returned.

`pad_string`

  > Note:

  > The `pad_string` may be truncated if the required number of padding characters can't be evenly divided by the `pad_string`'s length.

`pad_type`

  Optional argument `pad_type` can be `STR_PAD_RIGHT`, `STR_PAD_LEFT`, or `STR_PAD_BOTH`. By default `STR_PAD_RIGHT`.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the padded string.

### Examples

Example #1 mb_str_pad() example

`<?php
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_RIGHT)); // string(18) "▶▶❤❓❇❤"
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_LEFT)); // string(18) "❤❓❇❤▶▶"
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_BOTH)); // string(18) "❤❓▶▶❤❓"
var_dump(mb_str_pad("🎉", 3, "祝", STR_PAD_LEFT)); // string(10) "祝祝🎉"
?>`

# mb_str_split

(PHP 7 >= 7.4.0, PHP 8)

mb_str_split — Given a multibyte string, return an array of its characters

### Description

mb_str_split(string `$string`, int `$length` = 1, ?string `$encoding` = `null`): array

This function will return an array of strings, it is a version of str_split() with support for encodings of variable character size as well as fixed-size encodings of 1,2 or 4 byte characters. If the `length` parameter is specified, the string is broken down into chunks of the specified length in characters (not bytes). The `encoding` parameter can be optionally specified and it is good practice to do so.

### Parameters

`string`

  The string to split into characters or chunks.

`length`

  If specified, each element of the returned array will be composed of multiple characters instead of a single character.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

  A string specifying one of the supported encodings.

### Return Values

mb_str_split() returns an array of strings.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.
8.0.0 | This function no longer returns `false` on failure.

### See Also

- str_split() - Convert a string to an array
- grapheme_str_split() - Split a string into an array
- explode() - Split a string by a string

# mb_strcut

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strcut — Get part of string

### Description

mb_strcut(
string `$string`,
int `$start`,
?int `$length` = `null`,
?string `$encoding` = `null`
): string

mb_strcut() extracts a substring from a string similarly to mb_substr(), but operates on bytes instead of characters. If the cut position happens to be between two bytes of a multi-byte character, the cut is performed starting from the first byte of that character. This is also the difference to the substr() function, which would simply cut the string between the bytes and thus result in a malformed byte sequence.

### Parameters

`string`

  The string being cut.

`start`

  If `start` is non-negative, the returned string will start at the `start`'th byte position in `string`, counting from zero. For instance, in the string '`abcdef`', the byte at position `0` is '`a`', the byte at position `2` is '`c`', and so forth.

  If `start` is negative, the returned string will start at the `start`'th byte counting back from the end of `string`. However, if the magnitude of a negative `start` is greater than the length of the string, the returned portion will start from the beginning of `string`.

`length`

  Length in bytes. If omitted or `NULL` is passed, extract all bytes to the end of the string.

  If `length` is negative, the returned string will end at the `length`'th byte counting back from the end of `string`. However, if the magnitude of a negative `length` is greater than the number of characters after the `start` position, an empty string will be returned.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

mb_strcut() returns the portion of `string` specified by the `start` and `length` parameters.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- mb_substr() - Get part of string
- mb_internal_encoding() - Set/Get internal character encoding

# mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strimwidth — Get truncated string with specified width

### Description

mb_strimwidth(
string `$string`,
int `$start`,
int `$width`,
string `$trim_marker` = "",
?string `$encoding` = `null`
): string

Truncates string `string` to specified `width`, where halfwidth characters count as `1`, and fullwidth characters count as `2`. See » http://www.unicode.org/reports/tr11/ for details regarding East Asian character widths.

### Parameters

`string`

  The string being decoded.

`start`

  The start position offset. Number of characters from the beginning of string (first character is 0), or if start is negative, number of characters from the end of the string.

`width`

  The width of the desired trim. If negative width is specified, count from the end of the string.

  > Note:

  > Passing negative width is deprecated as of PHP 8.3.0.

`trim_marker`

  A string that is added to the end of string when string is truncated.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The truncated string. If `trim_marker` is set, `trim_marker` replaces the last chars to match the `width`.

### Changelog

Version | Description
--- | ---
8.3.0 | Passing a negative `width` to mb_strimwidth() is now deprecated.
8.0.0 | `encoding` is nullable now.
7.1.0 | Support for negative `start`s and `width`s has been added.

### Examples

Example #1 mb_strimwidth() example

`<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."
?>`

### See Also

- mb_strwidth() - Return width of string
- mb_internal_encoding() - Set/Get internal character encoding

# mb_stripos

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_stripos — Finds position of first occurrence of a string within another, case insensitive

### Description

mb_stripos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
?string `$encoding` = `null`
): int|false

mb_stripos() returns the numeric position of the first occurrence of `needle` in the `haystack` string. Unlike mb_strpos(), mb_stripos() is case-insensitive. If `needle` is not found, it returns `false`.

### Parameters

`haystack`

  The string from which to get the position of the first occurrence of `needle`

`needle`

  The string to find in `haystack`

`offset`

  The position in `haystack` to start searching. A negative offset counts from the end of the string.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Return the numeric position of the first occurrence of `needle` in the `haystack` string, or `false` if `needle` is not found.

### Errors/Exceptions

- If `offset` is greater than the length of `haystack`, a ValueError will be thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.
7.1.0 | Support for negative `offset`s has been added.

### See Also

- stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
- strpos() - Find the position of the first occurrence of a substring in a string
- mb_strpos() - Find position of first occurrence of string in a string

# mb_stristr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_stristr — Finds first occurrence of a string within another, case insensitive

### Description

mb_stristr(
string `$haystack`,
string `$needle`,
bool `$before_needle` = `false`,
?string `$encoding` = `null`
): string|false

mb_stristr() finds the first occurrence of `needle` in `haystack` and returns the portion of `haystack`. Unlike mb_strstr(), mb_stristr() is case-insensitive. If `needle` is not found, it returns `false`.

### Parameters

`haystack`

  The string from which to get the first occurrence of `needle`

`needle`

  The string to find in `haystack`

`before_needle`

  Determines which portion of `haystack` this function returns. If set to `true`, it returns all of `haystack` from the beginning to the first occurrence of `needle` (excluding needle). If set to `false`, it returns all of `haystack` from the first occurrence of `needle` to the end (including needle).

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the portion of `haystack`, or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.

### See Also

- stristr() - Case-insensitive strstr
- strstr() - Find the first occurrence of a string
- mb_strstr() - Finds first occurrence of a string within another

# mb_strlen

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strlen — Get string length

### Description

mb_strlen(string `$string`, ?string `$encoding` = `null`): int

Gets the length of a string.

### Parameters

`string`

  The string being checked for length.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the number of characters in string `string` having character encoding `encoding`. A multi-byte character is counted as 1.

### Errors/Exceptions

If the encoding is unknown, an error of level `E_WARNING` is generated.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- grapheme_strlen() - Get string length in grapheme units
- iconv_strlen() - Returns the character count of string
- strlen() - Get string length

# mb_strpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strpos — Find position of first occurrence of string in a string

### Description

mb_strpos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
?string `$encoding` = `null`
): int|false

Finds position of the first occurrence of `needle` in the `haystack` string.

Performs a multi-byte safe strpos() operation based on number of characters. The first character's position is 0, the second character position is 1, and so on.

### Parameters

`haystack`

  The string from which to get the position of the first occurrence of `needle`.

`needle`

  The string to find in `haystack`. In contrast with strpos(), numeric values are not applied as the ordinal value of a character.

`offset`

  The search offset. If it is not specified, 0 is used. A negative offset counts from the end of the string.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the numeric position of the first occurrence of `needle` in the `haystack` string. If `needle` is not found, it returns `false`.

### Errors/Exceptions

- If `offset` is greater than the length of `haystack`, a ValueError will be thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.
7.1.0 | Support for negative `offset`s has been added.

### See Also

- mb_internal_encoding() - Set/Get internal character encoding
- strpos() - Find the position of the first occurrence of a substring in a string

# mb_strrchr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strrchr — Finds the last occurrence of a character in a string within another

### Description

mb_strrchr(
string `$haystack`,
string `$needle`,
bool `$before_needle` = `false`,
?string `$encoding` = `null`
): string|false

mb_strrchr() finds the last occurrence of `needle` in `haystack` and returns the portion of `haystack`. If `needle` is not found, it returns `false`.

### Parameters

`haystack`

  The string from which to get the last occurrence of `needle`.

`needle`

  The string to find in `haystack`.

`before_needle`

  Determines which portion of `haystack` this function returns. If set to `true`, it returns all of `haystack` from the beginning to the last occurrence of `needle`. If set to `false`, it returns all of `haystack` from the last occurrence of `needle` to the end.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the portion of `haystack`. or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.

### See Also

- strrchr() - Find the last occurrence of a character in a string
- mb_strstr() - Finds first occurrence of a string within another
- mb_strrichr() - Finds the last occurrence of a character in a string within another, case insensitive

# mb_strrichr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive

### Description

mb_strrichr(
string `$haystack`,
string `$needle`,
bool `$before_needle` = `false`,
?string `$encoding` = `null`
): string|false

mb_strrichr() finds the last occurrence of `needle` in `haystack` and returns the portion of `haystack`. Unlike mb_strrchr(), mb_strrichr() is case-insensitive. If `needle` is not found, it returns `false`.

### Parameters

`haystack`

  The string from which to get the last occurrence of `needle`.

`needle`

  The string to find in `haystack`.

`before_needle`

  Determines which portion of `haystack` this function returns. If set to `true`, it returns all of `haystack` from the beginning to the last occurrence of `needle`. If set to `false`, it returns all of `haystack` from the last occurrence of `needle` to the end.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the portion of `haystack`. or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.

### See Also

- mb_stristr() - Finds first occurrence of a string within another, case insensitive
- mb_strrchr() - Finds the last occurrence of a character in a string within another

# mb_strripos

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strripos — Finds position of last occurrence of a string within another, case insensitive

### Description

mb_strripos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
?string `$encoding` = `null`
): int|false

mb_strripos() performs multi-byte safe strripos() operation based on number of characters. `needle` position is counted from the beginning of `haystack`. First character's position is 0. Second character position is 1. Unlike mb_strrpos(), mb_strripos() is case-insensitive.

### Parameters

`haystack`

  The string from which to get the position of the last occurrence of `needle`.

`needle`

  The string to find in `haystack`.

`offset`

  May be specified to begin searching an arbitrary number of characters into the `haystack`. Negative values will stop searching at an arbitrary point prior to the end of the `haystack`.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Return the numeric position of the last occurrence of `needle` in the `haystack` string, or `false` if `needle` is not found.

### Errors/Exceptions

- If `offset` is greater than the length of `haystack`, a ValueError will be thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.

### See Also

- strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
- strrpos() - Find the position of the last occurrence of a substring in a string
- mb_strrpos() - Find position of last occurrence of a string in a string

# mb_strrpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strrpos — Find position of last occurrence of a string in a string

### Description

mb_strrpos(
string `$haystack`,
string `$needle`,
int `$offset` = 0,
?string `$encoding` = `null`
): int|false

Performs a multibyte safe strrpos() operation based on the number of characters. `needle` position is counted from the beginning of `haystack`. First character's position is 0. Second character position is 1.

### Parameters

`haystack`

  The string being checked, for the last occurrence of `needle`

`needle`

  The string to find in `haystack`.

`offset`
  May be specified to begin searching an arbitrary number of characters into the `haystack`. Negative values will stop searching at an arbitrary point prior to the end of the `haystack`.
`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the numeric position of the last occurrence of `needle` in the `haystack` string. If `needle` is not found, it returns `false`.

### Errors/Exceptions

- If `offset` is greater than the length of `haystack`, a ValueError will be thrown.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | Passing the `encoding` as the third argument instead of an `offset` has been removed.
8.0.0 | `encoding` is nullable now.

### See Also

- mb_strpos() - Find position of first occurrence of string in a string
- mb_internal_encoding() - Set/Get internal character encoding
- strrpos() - Find the position of the last occurrence of a substring in a string

# mb_strstr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strstr — Finds first occurrence of a string within another

### Description

mb_strstr(
string `$haystack`,
string `$needle`,
bool `$before_needle` = `false`,
?string `$encoding` = `null`
): string|false

mb_strstr() finds the first occurrence of `needle` in `haystack` and returns the portion of `haystack`. If `needle` is not found, it returns `false`.

### Parameters

`haystack`

  The string from which to get the first occurrence of `needle`

`needle`

  The string to find in `haystack`

`before_needle`

  Determines which portion of `haystack` this function returns. If set to `true`, it returns all of `haystack` from the beginning to the first occurrence of `needle` (excluding needle). If set to `false`, it returns all of `haystack` from the first occurrence of `needle` to the end (including needle).

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

Returns the portion of `haystack`, or `false` if `needle` is not found.

### Changelog

Version | Description
--- | ---
8.0.0 | `needle` now accepts an empty string.
8.0.0 | `encoding` is nullable now.

### See Also

- stristr() - Case-insensitive strstr
- strstr() - Find the first occurrence of a string
- mb_stristr() - Finds first occurrence of a string within another, case insensitive

# mb_strtolower

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_strtolower — Make a string lowercase

### Description

mb_strtolower(string `$string`, ?string `$encoding` = `null`): string

Returns `string` with all alphabetic characters converted to lowercase.

### Parameters

`string`

  The string being lowercased.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

`string` with all alphabetic characters converted to lowercase.

### Changelog

Version | Description
--- | ---
8.3.0 | Implemented conditional casing rules for the Greek letter sigma.

### Examples

Example #1 mb_strtolower() example

`<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>`

Example #2 mb_strtolower() example with non-Latin UTF-8 text

`<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>`

### Notes

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

For more information about the Unicode properties, please see » http://www.unicode.org/reports/tr21/.

### See Also

- mb_strtoupper() - Make a string uppercase
- mb_convert_case() - Perform case folding on a string
- strtolower() - Make a string lowercase

# mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_strtoupper — Make a string uppercase

### Description

mb_strtoupper(string `$string`, ?string `$encoding` = `null`): string

Returns `string` with all alphabetic characters converted to uppercase.

### Parameters

`string`

  The string being uppercased.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

`string` with all alphabetic characters converted to uppercase.

### Examples

Example #1 mb_strtoupper() example

`<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>`

Example #2 mb_strtoupper() example with non-Latin UTF-8 text

`<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
?>`

### Notes

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

For more information about the Unicode properties, please see » http://www.unicode.org/reports/tr21/.

### See Also

- mb_strtolower() - Make a string lowercase
- mb_convert_case() - Perform case folding on a string
- strtoupper() - Make a string uppercase

# mb_strwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strwidth — Return width of string

### Description

mb_strwidth(string `$string`, ?string `$encoding` = `null`): int

Returns the width of string `string`, where halfwidth characters count as `1`, and fullwidth characters count as `2`. See » http://www.unicode.org/reports/tr11/ for details regarding East Asian character widths.

The fullwidth characters are: `U+1100`-`U+115F`, `U+11A3`-`U+11A7`, `U+11FA`-`U+11FF`, `U+2329`-`U+232A`, `U+2E80`-`U+2E99`, `U+2E9B`-`U+2EF3`, `U+2F00`-`U+2FD5`, `U+2FF0`-`U+2FFB`, `U+3000`-`U+303E`, `U+3041`-`U+3096`, `U+3099`-`U+30FF`, `U+3105`-`U+312D`, `U+3131`-`U+318E`, `U+3190`-`U+31BA`, `U+31C0`-`U+31E3`, `U+31F0`-`U+321E`, `U+3220`-`U+3247`, `U+3250`-`U+32FE`, `U+3300`-`U+4DBF`, `U+4E00`-`U+A48C`, `U+A490`-`U+A4C6`, `U+A960`-`U+A97C`, `U+AC00`-`U+D7A3`, `U+D7B0`-`U+D7C6`, `U+D7CB`-`U+D7FB`, `U+F900`-`U+FAFF`, `U+FE10`-`U+FE19`, `U+FE30`-`U+FE52`, `U+FE54`-`U+FE66`, `U+FE68`-`U+FE6B`, `U+FF01`-`U+FF60`, `U+FFE0`-`U+FFE6`, `U+1B000`-`U+1B001`, `U+1F200`-`U+1F202`, `U+1F210`-`U+1F23A`, `U+1F240`-`U+1F248`, `U+1F250`-`U+1F251`, `U+20000`-`U+2FFFD`, `U+30000`-`U+3FFFD`. All other characters are halfwidth characters.

### Parameters

`string`

  The string being decoded.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The width of string `string`.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 mb_strwidth() example

`<?php
var_dump(
mb_strwidth('a'), // LATIN SMALL LETTER A
mb_strwidth("\u{ff41}") // FULLWIDTH LATIN SMALL LETTER A
);
?>`

The above example will output:

    int(1)
    int(2)

### See Also

- mb_strimwidth() - Get truncated string with specified width
- mb_internal_encoding() - Set/Get internal character encoding

# mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_substitute_character — Set/Get substitution character

### Description

mb_substitute_character(string|int|null `$substitute_character` = `null`): string|int|bool

Specifies a substitution character when input character encoding is invalid or character code does not exist in output character encoding. Invalid characters may be substituted `"none"` (no output), string or int value (Unicode character code value).

This setting affects mb_convert_encoding(), mb_convert_variables(), mb_output_handler(), mb_scrub(), and mb_send_mail().

### Parameters

`substitute_character`

  Specify the Unicode value as an int, or as one of the following strings:

  - `"none"`: no output
  - `"long"`: Output character code value (Example: `U+3000`, `JIS+7E7E`)
  - `"entity"`: Output character entity (Example: `&#x200;`)

### Return Values

If `substitute_character` is set, it returns `true` for success, otherwise returns `false`. If `substitute_character` is not set, it returns the current setting.

### Changelog

Version | Description
--- | ---
8.0.0 | Passing an empty string to `substitute_character` is no longer supported; `"none"` should be passed instead.
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 mb_substitute_character() example

`<?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);
/* Set hex format */
mb_substitute_character("long");
/* Display current setting */
echo mb_substitute_character();
?>`

# mb_substr

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_substr — Get part of string

### Description

mb_substr(
string `$string`,
int `$start`,
?int `$length` = `null`,
?string `$encoding` = `null`
): string

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of `string`. First character's position is 0. Second character position is 1, and so on.

### Parameters

`string`

  The string to extract the substring from.

`start`

  If `start` is non-negative, the returned string will start at the `start`'th position in `string`, counting from zero. For instance, in the string '`abcdef`', the character at position `0` is '`a`', the character at position `2` is '`c`', and so forth.

  If `start` is negative, the returned string will start at the `start`'th character from the end of `string`.

`length`

  Maximum number of characters to use from `string`. If omitted or `NULL` is passed, extract all characters to the end of the string.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

mb_substr() returns the portion of `string` specified by the `start` and `length` parameters.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### See Also

- mb_strcut() - Get part of string
- mb_internal_encoding() - Set/Get internal character encoding

# mb_substr_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_substr_count — Count the number of substring occurrences

### Description

mb_substr_count(string `$haystack`, string `$needle`, ?string `$encoding` = `null`): int

Counts the number of times the `needle` substring occurs in the `haystack` string.

### Parameters

`haystack`

  The string being checked.

`needle`

  The string being found.

`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The number of times the `needle` substring occurs in the `haystack` string.

### Changelog

Version | Description
--- | ---
8.0.0 | `encoding` is nullable now.

### Examples

Example #1 mb_substr_count() example

`<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>`

### See Also

- mb_strpos() - Find position of first occurrence of string in a string
- mb_substr() - Get part of string
- substr_count() - Count the number of substring occurrences

# mb_trim

(PHP 8 >= 8.4.0)

mb_trim — Strip whitespace (or other characters) from the beginning and end of a string

### Description

mb_trim(string `$string`, ?string `$characters` = `null`, ?string `$encoding` = `null`): string

Performs a multi-byte safe trim() operation, and returns a string with whitespace stripped from the beginning and end of `string`. Without the second parameter, mb_trim() will strip these characters:

- `" "` (Unicode U+0020), an ordinary space.
- `"\t"` (Unicode U+0009), a tab.
- `"\n"` (Unicode U+000A), a new line (line feed).
- `"\r"` (Unicode U+000D), a carriage return.
- `"\0"` (Unicode U+0000), the NUL-byte.
- `"\v"` (Unicode U+000B), a vertical tab.
- `"\f"` (Unicode U+000C), a form feed.
- `"\u00A0"` (Unicode U+00A0), a NO-BREAK SPACE.
- `"\u1680"` (Unicode U+1680), a OGHAM SPACE MARK.
- `"\u2000"` (Unicode U+2000), a EN QUAD.
- `"\u2001"` (Unicode U+2001), a EM QUAD.
- `"\u2002"` (Unicode U+2002), a EN SPACE.
- `"\u2003"` (Unicode U+2003), a EM SPACE.
- `"\u2004"` (Unicode U+2004), a THREE-PER-EM SPACE.
- `"\u2005"` (Unicode U+2005), a FOUR-PER-EM SPACE.
- `"\u2006"` (Unicode U+2006), a SIX-PER-EM SPACE.
- `"\u2007"` (Unicode U+2007), a FIGURE SPACE.
- `"\u2008"` (Unicode U+2008), a PUNCTUATION SPACE.
- `"\u2009"` (Unicode U+2009), a THIN SPACE.
- `"\u200A"` (Unicode U+200A), a HAIR SPACE.
- `"\u2028"` (Unicode U+2028), a LINE SEPARATOR.
- `"\u2029"` (Unicode U+2029), a PARAGRAPH SEPARATOR.
- `"\u202F"` (Unicode U+202F), a NARROW NO-BREAK SPACE.
- `"\u205F"` (Unicode U+205F), a MEDIUM MATHEMATICAL SPACE.
- `"\u3000"` (Unicode U+3000), a IDEOGRAPHIC SPACE.
- `"\u0085"` (Unicode U+0085), a NEXT LINE (NEL).
- `"\u180E"` (Unicode U+180E), a MONGOLIAN VOWEL SEPARATOR.

### Parameters

`string`
  The string that will be trimmed.
`characters`
  Optionally, the stripped characters can also be specified using the `characters` parameter. Simply list all characters that need to be stripped.
`encoding`

  The `encoding` parameter is the character encoding. If it is omitted or `null`, the internal character encoding value will be used.

### Return Values

The trimmed string.

### See Also

- mb_ltrim() - Strip whitespace (or other characters) from the beginning of a string
- mb_rtrim() - Strip whitespace (or other characters) from the end of a string
- trim() - Strip whitespace (or other characters) from the beginning and end of a string

# mb_ucfirst

(PHP 8 >= 8.4.0)

mb_ucfirst — Make a string's first character uppercase

### Description

mb_ucfirst(string `$string`, ?string `$encoding` = `null`): string

Performs a multi-byte safe ucfirst() operation, and returns a string with the first character of `string` title-cased.

### Parameters

`string`
  The input string.
`encoding`
  The string encoding.

### Return Values

Returns the resulting string.

### Notes

> Note:

> By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such a-umlaut (ä).

For more information about the Unicode properties, please see » http://www.unicode.org/reports/tr21/.

### See Also

- mb_lcfirst() - Make a string's first character lowercase
- mb_convert_case() - Perform case folding on a string
- ucfirst() - Make a string's first character uppercase

## Table of Contents

- mb_check_encoding — Check if strings are valid for the specified encoding
- mb_chr — Return character by Unicode code point value
- mb_convert_case — Perform case folding on a string
- mb_convert_encoding — Convert a string from one character encoding to another
- mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
- mb_convert_variables — Convert character code in variable(s)
- mb_decode_mimeheader — Decode string in MIME header field
- mb_decode_numericentity — Decode HTML numeric string reference to character
- mb_detect_encoding — Detect character encoding
- mb_detect_order — Set/Get character encoding detection order
- mb_encode_mimeheader — Encode string for MIME header
- mb_encode_numericentity — Encode character to HTML numeric string reference
- mb_encoding_aliases — Get aliases of a known encoding type
- mb_ereg — Regular expression match with multibyte support
- mb_ereg_match — Regular expression match for multibyte string
- mb_ereg_replace — Replace regular expression with multibyte support
- mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
- mb_ereg_search — Multibyte regular expression match for predefined multibyte string
- mb_ereg_search_getpos — Returns start point for next regular expression match
- mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
- mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
- mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
- mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
- mb_ereg_search_setpos — Set start point of next regular expression match
- mb_eregi — Regular expression match ignoring case with multibyte support
- mb_eregi_replace — Replace regular expression with multibyte support ignoring case
- mb_get_info — Get internal settings of mbstring
- mb_http_input — Detect HTTP input character encoding
- mb_http_output — Set/Get HTTP output character encoding
- mb_internal_encoding — Set/Get internal character encoding
- mb_language — Set/Get current language
- mb_lcfirst — Make a string's first character lowercase
- mb_list_encodings — Returns an array of all supported encodings
- mb_ltrim — Strip whitespace (or other characters) from the beginning of a string
- mb_ord — Get Unicode code point of character
- mb_output_handler — Callback function converts character encoding in output buffer
- mb_parse_str — Parse GET/POST/COOKIE data and set global variable
- mb_preferred_mime_name — Get MIME charset string
- mb_regex_encoding — Set/Get character encoding for multibyte regex
- mb_regex_set_options — Set/Get the default options for mbregex functions
- mb_rtrim — Strip whitespace (or other characters) from the end of a string
- mb_scrub — Replace ill-formed byte sequences with the substitute character
- mb_send_mail — Send encoded mail
- mb_split — Split multibyte string using regular expression
- mb_str_pad — Pad a multibyte string to a certain length with another multibyte string
- mb_str_split — Given a multibyte string, return an array of its characters
- mb_strcut — Get part of string
- mb_strimwidth — Get truncated string with specified width
- mb_stripos — Finds position of first occurrence of a string within another, case insensitive
- mb_stristr — Finds first occurrence of a string within another, case insensitive
- mb_strlen — Get string length
- mb_strpos — Find position of first occurrence of string in a string
- mb_strrchr — Finds the last occurrence of a character in a string within another
- mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
- mb_strripos — Finds position of last occurrence of a string within another, case insensitive
- mb_strrpos — Find position of last occurrence of a string in a string
- mb_strstr — Finds first occurrence of a string within another
- mb_strtolower — Make a string lowercase
- mb_strtoupper — Make a string uppercase
- mb_strwidth — Return width of string
- mb_substitute_character — Set/Get substitution character
- mb_substr — Get part of string
- mb_substr_count — Count the number of substring occurrences
- mb_trim — Strip whitespace (or other characters) from the beginning and end of a string
- mb_ucfirst — Make a string's first character uppercase

- Installing/Configuring
  - Installation
  - Runtime Configuration
- Predefined Constants
- Summaries of supported encodings
- Basics of Japanese multi-byte encodings
- HTTP Input and Output
- Supported Character Encodings
- Function Overloading Feature
- PHP Character Encoding Requirements
- Multibyte String Functions
  - mb_check_encoding — Check if strings are valid for the specified encoding
  - mb_chr — Return character by Unicode code point value
  - mb_convert_case — Perform case folding on a string
  - mb_convert_encoding — Convert a string from one character encoding to another
  - mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  - mb_convert_variables — Convert character code in variable(s)
  - mb_decode_mimeheader — Decode string in MIME header field
  - mb_decode_numericentity — Decode HTML numeric string reference to character
  - mb_detect_encoding — Detect character encoding
  - mb_detect_order — Set/Get character encoding detection order
  - mb_encode_mimeheader — Encode string for MIME header
  - mb_encode_numericentity — Encode character to HTML numeric string reference
  - mb_encoding_aliases — Get aliases of a known encoding type
  - mb_ereg — Regular expression match with multibyte support
  - mb_ereg_match — Regular expression match for multibyte string
  - mb_ereg_replace — Replace regular expression with multibyte support
  - mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
  - mb_ereg_search — Multibyte regular expression match for predefined multibyte string
  - mb_ereg_search_getpos — Returns start point for next regular expression match
  - mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
  - mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
  - mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
  - mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
  - mb_ereg_search_setpos — Set start point of next regular expression match
  - mb_eregi — Regular expression match ignoring case with multibyte support
  - mb_eregi_replace — Replace regular expression with multibyte support ignoring case
  - mb_get_info — Get internal settings of mbstring
  - mb_http_input — Detect HTTP input character encoding
  - mb_http_output — Set/Get HTTP output character encoding
  - mb_internal_encoding — Set/Get internal character encoding
  - mb_language — Set/Get current language
  - mb_lcfirst — Make a string's first character lowercase
  - mb_list_encodings — Returns an array of all supported encodings
  - mb_ltrim — Strip whitespace (or other characters) from the beginning of a string
  - mb_ord — Get Unicode code point of character
  - mb_output_handler — Callback function converts character encoding in output buffer
  - mb_parse_str — Parse GET/POST/COOKIE data and set global variable
  - mb_preferred_mime_name — Get MIME charset string
  - mb_regex_encoding — Set/Get character encoding for multibyte regex
  - mb_regex_set_options — Set/Get the default options for mbregex functions
  - mb_rtrim — Strip whitespace (or other characters) from the end of a string
  - mb_scrub — Replace ill-formed byte sequences with the substitute character
  - mb_send_mail — Send encoded mail
  - mb_split — Split multibyte string using regular expression
  - mb_str_pad — Pad a multibyte string to a certain length with another multibyte string
  - mb_str_split — Given a multibyte string, return an array of its characters
  - mb_strcut — Get part of string
  - mb_strimwidth — Get truncated string with specified width
  - mb_stripos — Finds position of first occurrence of a string within another, case insensitive
  - mb_stristr — Finds first occurrence of a string within another, case insensitive
  - mb_strlen — Get string length
  - mb_strpos — Find position of first occurrence of string in a string
  - mb_strrchr — Finds the last occurrence of a character in a string within another
  - mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
  - mb_strripos — Finds position of last occurrence of a string within another, case insensitive
  - mb_strrpos — Find position of last occurrence of a string in a string
  - mb_strstr — Finds first occurrence of a string within another
  - mb_strtolower — Make a string lowercase
  - mb_strtoupper — Make a string uppercase
  - mb_strwidth — Return width of string
  - mb_substitute_character — Set/Get substitution character
  - mb_substr — Get part of string
  - mb_substr_count — Count the number of substring occurrences
  - mb_trim — Strip whitespace (or other characters) from the beginning and end of a string
  - mb_ucfirst — Make a string's first character uppercase

# Pspell

# Introduction

Warning

This extension is DEPRECATED and UNBUNDLED as of PHP 8.4.0.

These functions allow you to check the spelling of a word and offer suggestions.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.

## Installation

## PHP 8.4

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 8.4.0

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: » https://pecl.php.net/package/pspell.

## PHP < 8.4

To enable this extension compile PHP with the --with-pspell[=dir] option.

> Note: Note to Win32 Users

> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: aspell-15.dll from the bin folder of the aspell installation.

> Win32 support requires at least aspell version 0.50.

## Resource Types

Prior to PHP 8.1.0, there were two resource types used in this extension. The first one is the dictionary link identifier, the second is a resource which holds pspell config.

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

`PSPELL_FAST` (int)
`PSPELL_NORMAL` (int)
`PSPELL_BAD_SPELLERS` (int)
`PSPELL_RUN_TOGETHER` (int)

# Pspell Functions

# pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_add_to_personal — Add the word to a personal wordlist

### Description

pspell_add_to_personal(PSpell\Dictionary `$dictionary`, string `$word`): bool

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist().

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

`word`

  The added word.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_add_to_personal()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_add_to_personal($pspell, "Vlad");
pspell_save_wordlist($pspell);
?>`

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_add_to_session — Add the word to the wordlist in the current session

### Description

pspell_add_to_session(PSpell\Dictionary `$dictionary`, string `$word`): bool

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

`word`

  The added word.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

# pspell_check

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_check — Check a word

### Description

pspell_check(PSpell\Dictionary `$dictionary`, string `$word`): bool

pspell_check() checks the spelling of a word.

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

`word`

  The tested word.

### Return Values

Returns `true` if the spelling is correct, `false` if not.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_check() Example

`<?php
$pspell = pspell_new("en");
if (pspell_check($pspell, "testt")) {
echo "This is a valid spelling";
} else {
echo "Sorry, wrong spelling";
}
?>`

# pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_clear_session — Clear the current session

### Description

pspell_clear_session(PSpell\Dictionary `$dictionary`): bool

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_add_to_personal() Example

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_add_to_personal($pspell, "Vlad");
pspell_clear_session($pspell);
pspell_save_wordlist($pspell); //"Vlad" will not be saved
?>`

# pspell_config_create

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_create — Create a config used to open a dictionary

### Description

pspell_config_create(
string `$language`,
string `$spelling` = "",
string `$jargon` = "",
string `$encoding` = ""
): PSpell\Config

Create a config used to open a dictionary.

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

### Parameters

`language`

  The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

`spelling`

  The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

`jargon`

  The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

`encoding`

  The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

### Return Values

Returns an PSpell\Config instance.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PSpell\Config instance now; previously, a resource was returned.

### Examples

Example #1 pspell_config_create()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell = pspell_new_personal($pspell_config, "en");
?>`

# pspell_config_data_dir

(PHP 5, PHP 7, PHP 8)

pspell_config_data_dir — Location of language data files

### Description

pspell_config_data_dir(PSpell\Config `$config`, string `$directory`): bool

Warning

This function is currently not documented; only its argument list is available.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

# pspell_config_dict_dir

(PHP 5, PHP 7, PHP 8)

pspell_config_dict_dir — Location of the main word list

### Description

pspell_config_dict_dir(PSpell\Config `$config`, string `$directory`): bool

Warning

This function is currently not documented; only its argument list is available.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

# pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_ignore — Ignore words less than N characters long

### Description

pspell_config_ignore(PSpell\Config `$config`, int `$min_length`): bool

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker.

### Parameters

`config`

  An PSpell\Config instance.

`min_length`

  Words less than `min_length` characters will be skipped.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Examples

Example #1 pspell_config_ignore()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "abcd"); //will not result in an error
?>`

# pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_mode — Change the mode number of suggestions returned

### Description

pspell_config_mode(PSpell\Config `$config`, int `$mode`): bool

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

### Parameters

`config`

  An PSpell\Config instance.

`mode`

  The mode parameter is the mode in which spellchecker will work. There are several modes available:

  - `PSPELL_FAST` - Fast mode (least number of suggestions)
  - `PSPELL_NORMAL` - Normal mode (more suggestions)
  - `PSPELL_BAD_SPELLERS` - Slow mode (a lot of suggestions)

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Examples

Example #1 pspell_config_mode() Example

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>`

# pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_personal — Set a file that contains personal wordlist

### Description

pspell_config_personal(PSpell\Config `$config`, string `$filename`): bool

Set a file that contains personal wordlist. The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). The file is also the file where pspell_save_wordlist() will save personal wordlist to.

pspell_config_personal() should be used on a config before calling pspell_new_config().

### Parameters

`config`

  An PSpell\Config instance.

`filename`

  The personal wordlist. If the file does not exist, it will be created. The file should be writable by whoever PHP runs as (e.g. nobody).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Examples

Example #1 pspell_config_personal()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>`

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_repl — Set a file that contains replacement pairs

### Description

pspell_config_repl(PSpell\Config `$config`, string `$filename`): bool

Set a file that contains replacement pairs.

The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs.

pspell_config_repl() should be used on a config before calling pspell_new_config().

### Parameters

`config`

  An PSpell\Config instance.

`filename`

  The file should be writable by whoever PHP runs as (e.g. nobody).

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Examples

Example #1 pspell_config_repl()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>`

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_runtogether — Consider run-together words as valid compounds

### Description

pspell_config_runtogether(PSpell\Config `$config`, bool `$allow`): bool

This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

pspell_config_runtogether() should be used on a config before calling pspell_new_config().

### Parameters

`config`

  An PSpell\Config instance.

`allow`

  `true` if run-together words should be treated as legal compounds, `false` otherwise.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Examples

Example #1 pspell_config_runtogether()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>`

# pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

### Description

pspell_config_save_repl(PSpell\Config `$config`, bool `$save`): bool

pspell_config_save_repl() determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved.

pspell_config_save_repl() should be used on a config before calling pspell_new_config().

### Parameters

`config`

  An PSpell\Config instance.

`save`

  `true` if replacement pairs should be saved, `false` otherwise.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_new

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new — Load a new dictionary

### Description

pspell_new(
string `$language`,
string `$spelling` = "",
string `$jargon` = "",
string `$encoding` = "",
int `$mode` = 0
): PSpell\Dictionary|false

pspell_new() opens up a new dictionary and returns an PSpell\Dictionary instance for use in other pspell functions.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

### Parameters

`language`

  The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

`spelling`

  The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

`jargon`

  The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

`encoding`

  The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

`mode`

  The mode parameter is the mode in which spellchecker will work. There are several modes available:

  - `PSPELL_FAST` - Fast mode (least number of suggestions)
  - `PSPELL_NORMAL` - Normal mode (more suggestions)
  - `PSPELL_BAD_SPELLERS` - Slow mode (a lot of suggestions)
  - `PSPELL_RUN_TOGETHER` - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
  Mode is a bitmask constructed from different constants listed above. However, `PSPELL_FAST`, `PSPELL_NORMAL` and `PSPELL_BAD_SPELLERS` are mutually exclusive, so you should select only one of them.

### Return Values

Returns an PSpell\Dictionary instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

### Examples

Example #1 pspell_new()

`<?php
$pspell = pspell_new("en", "", "", "",
(PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>`

# pspell_new_config

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new_config — Load a new dictionary with settings based on a given config

### Description

pspell_new_config(PSpell\Config `$config`): PSpell\Dictionary|false

pspell_new_config() opens up a new dictionary with settings specified in a `config`, created with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

### Parameters

`config`

  The `config` parameter is the one returned by pspell_config_create() when the config was created.

### Return Values

Returns an PSpell\Dictionary instance on success, or `false` on failure

### Changelog

Version | Description
--- | ---
8.1.0 | The `config` parameter expects an PSpell\Config instance now; previously, a resource was expected.
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

### Examples

Example #1 pspell_new_config()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell = pspell_new_config($pspell_config);
?>`

# pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new_personal — Load a new dictionary with personal wordlist

### Description

pspell_new_personal(
string `$filename`,
string `$language`,
string `$spelling` = "",
string `$jargon` = "",
string `$encoding` = "",
int `$mode` = 0
): PSpell\Dictionary|false

pspell_new_personal() opens up a new dictionary with a personal wordlist. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

### Parameters

`filename`

  The file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

`language`

  The language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

`spelling`

  The requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

`jargon`

  Extra information to distinguish two different words lists that have the same language and spelling parameters.

`encoding`

  The encoding that words are expected to be in. Valid values are `utf-8`, `iso8859-*`, `koi8-r`, `viscii`, `cp1252`, `machine unsigned 16`, `machine unsigned 32`.

`mode`

  The mode in which spellchecker will work. There are several modes available:

  - `PSPELL_FAST` - Fast mode (least number of suggestions)
  - `PSPELL_NORMAL` - Normal mode (more suggestions)
  - `PSPELL_BAD_SPELLERS` - Slow mode (a lot of suggestions)
  - `PSPELL_RUN_TOGETHER` - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
  Mode is a bitmask constructed from different constants listed above. However, `PSPELL_FAST`, `PSPELL_NORMAL` and `PSPELL_BAD_SPELLERS` are mutually exclusive, so you should select only one of them.

### Return Values

Returns an PSpell\Dictionary instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

### Examples

Example #1 pspell_new_personal()

`<?php
$pspell = pspell_new_personal ("/var/dictionaries/custom.pws",
"en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>`

# pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_save_wordlist — Save the personal wordlist to a file

### Description

pspell_save_wordlist(PSpell\Dictionary `$dictionary`): bool

pspell_save_wordlist() saves the personal wordlist from the current session. The location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl().

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_add_to_personal()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell = pspell_new_config($pspell_config);
pspell_add_to_personal($pspell, "Vlad");
pspell_save_wordlist($pspell);
?>`

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_store_replacement — Store a replacement pair for a word

### Description

pspell_store_replacement(PSpell\Dictionary `$dictionary`, string `$misspelled`, string `$correct`): bool

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk.

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

`misspelled`

  The misspelled word.

`correct`

  The fixed spelling for the `misspelled` word.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_store_replacement()

`<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell = pspell_new_config($pspell_config);
pspell_store_replacement($pspell, $misspelled, $correct);
pspell_save_wordlist($pspell);
?>`

### Notes

> Note:

> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

# pspell_suggest

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_suggest — Suggest spellings of a word

### Description

pspell_suggest(PSpell\Dictionary `$dictionary`, string `$word`): array|false

pspell_suggest() returns an array of possible spellings for the given word.

### Parameters

`dictionary`

  An PSpell\Dictionary instance.

`word`

  The tested word.

### Return Values

Returns an array of possible spellings.

### Changelog

Version | Description
--- | ---
8.1.0 | The `dictionary` parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

### Examples

Example #1 pspell_suggest() example

`<?php
$pspell = pspell_new("en");
if (!pspell_check($pspell, "testt")) {
$suggestions = pspell_suggest($pspell, "testt");
foreach ($suggestions as $suggestion) {
echo "Possible spelling: $suggestion<br />";
}
}
?>`

## Table of Contents

- pspell_add_to_personal — Add the word to a personal wordlist
- pspell_add_to_session — Add the word to the wordlist in the current session
- pspell_check — Check a word
- pspell_clear_session — Clear the current session
- pspell_config_create — Create a config used to open a dictionary
- pspell_config_data_dir — Location of language data files
- pspell_config_dict_dir — Location of the main word list
- pspell_config_ignore — Ignore words less than N characters long
- pspell_config_mode — Change the mode number of suggestions returned
- pspell_config_personal — Set a file that contains personal wordlist
- pspell_config_repl — Set a file that contains replacement pairs
- pspell_config_runtogether — Consider run-together words as valid compounds
- pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
- pspell_new — Load a new dictionary
- pspell_new_config — Load a new dictionary with settings based on a given config
- pspell_new_personal — Load a new dictionary with personal wordlist
- pspell_save_wordlist — Save the personal wordlist to a file
- pspell_store_replacement — Store a replacement pair for a word
- pspell_suggest — Suggest spellings of a word

# The PSpell\Dictionary class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `pspell` resource as of PHP 8.1.0.

## Class synopsis

final class PSpell\Dictionary {
}

# The PSpell\Config class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `pspell config` resource as of PHP 8.1.0.

## Class synopsis

final class PSpell\Config {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- Pspell Functions
  - pspell_add_to_personal — Add the word to a personal wordlist
  - pspell_add_to_session — Add the word to the wordlist in the current session
  - pspell_check — Check a word
  - pspell_clear_session — Clear the current session
  - pspell_config_create — Create a config used to open a dictionary
  - pspell_config_data_dir — Location of language data files
  - pspell_config_dict_dir — Location of the main word list
  - pspell_config_ignore — Ignore words less than N characters long
  - pspell_config_mode — Change the mode number of suggestions returned
  - pspell_config_personal — Set a file that contains personal wordlist
  - pspell_config_repl — Set a file that contains replacement pairs
  - pspell_config_runtogether — Consider run-together words as valid compounds
  - pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
  - pspell_new — Load a new dictionary
  - pspell_new_config — Load a new dictionary with settings based on a given config
  - pspell_new_personal — Load a new dictionary with personal wordlist
  - pspell_save_wordlist — Save the personal wordlist to a file
  - pspell_store_replacement — Store a replacement pair for a word
  - pspell_suggest — Suggest spellings of a word
- PSpell\Dictionary — The PSpell\Dictionary class
- PSpell\Config — The PSpell\Config class

# GNU Recode

# Introduction

Warning

This extension is unmaintained.

This module contains an interface to the GNU Recode library. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most » RFC 1345 character sets are supported.

> Note: This extension is unbundled and moved to » PECL as of PHP 7.4.0. Consider to use the Multibyte String or iconv extensions instead.

> Note: This extension is not available on Windows platforms.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from » http://directory.fsf.org/All_GNU_Packages/recode.html.

Warning

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.

## Installation

## PHP 7.4

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.4.0

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: » https://pecl.php.net/package/recode.

## PHP < 7.4

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Warning

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proved to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own `hash_lookup()` function and both mysql and recode have their own `hash_insert` function.

Warning

The IMAP, recode and YAZ extensions cannot be used in conjunction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

# Recode Functions

# recode

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode — Alias of recode_string()

### Description

This function is an alias of: recode_string().

# recode_file

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode_file — Recode from file to file according to recode request

### Description

recode_file(string `$request`, resource `$input`, resource `$output`): bool

Recode the file referenced by file handle `input` into the file referenced by file handle `output` according to the recode `request`.

### Parameters

`request`
  The desired recode request type
`input`
  A local file handle resource for the `input`
`output`
  A local file handle resource for the `output`

### Return Values

Returns `false`, if unable to comply, `true` otherwise.

### Examples

Example #1 Basic recode_file() example

`<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>`

### Notes

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

### See Also

- fopen() - Opens file or URL

# recode_string

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode_string — Recode a string according to a recode request

### Description

recode_string(string `$request`, string `$string`): string

Recode the string `string` according to the recode request `request`.

### Parameters

`request`
  The desired recode request type
`string`
  The string to be recoded

### Return Values

Returns the recoded string or `false`, if unable to perform the recode request.

### Examples

Example #1 Basic recode_string() example

`<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>`

### Notes

A simple recode request may be "lat1..iso646-de".

### See Also

- The GNU Recode documentation of your installation for detailed instructions about recode requests.
- mb_convert_encoding() - Convert a string from one character encoding to another
- UConverter::transcode() - Convert a string from one character encoding to another
- iconv() - Convert a string from one character encoding to another

## Table of Contents

- recode — Alias of recode_string
- recode_file — Recode from file to file according to recode request
- recode_string — Recode a string according to a recode request

- Installing/Configuring
  - Requirements
  - Installation
- Recode Functions
  - recode — Alias of recode_string
  - recode_file — Recode from file to file according to recode request
  - recode_string — Recode a string according to a recode request

- Enchant — Enchant spelling library
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Enchant Functions
  - EnchantBroker — The EnchantBroker class
  - EnchantDictionary — The EnchantDictionary class
- Gender — Determine gender of firstnames
  - Installing/Configuring
  - Examples
  - Gender\Gender — The Gender\Gender class
- Gettext
  - Installing/Configuring
  - Gettext Functions
- iconv
  - Installing/Configuring
  - Predefined Constants
  - iconv Functions
- intl — Internationalization Functions
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Collator — The Collator class
  - NumberFormatter — The NumberFormatter class
  - Locale — The Locale class
  - Normalizer — The Normalizer class
  - MessageFormatter — The MessageFormatter class
  - IntlCalendar — The IntlCalendar class
  - IntlGregorianCalendar — The IntlGregorianCalendar class
  - IntlTimeZone — The IntlTimeZone class
  - IntlDateFormatter — The IntlDateFormatter class
  - ResourceBundle — The ResourceBundle class
  - Spoofchecker — The Spoofchecker class
  - Transliterator — The Transliterator class
  - IntlBreakIterator — The IntlBreakIterator class
  - IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
  - IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
  - IntlDatePatternGenerator — The IntlDatePatternGenerator class
  - IntlPartsIterator — The IntlPartsIterator class
  - UConverter — The UConverter class
  - Grapheme Functions
  - IDN Functions
  - IntlChar
  - IntlException — Exception class for intl errors
  - IntlIterator — The IntlIterator class
  - intl Functions
- Multibyte String
  - Installing/Configuring
  - Predefined Constants
  - Summaries of supported encodings
  - Basics of Japanese multi-byte encodings
  - HTTP Input and Output
  - Supported Character Encodings
  - Function Overloading Feature
  - PHP Character Encoding Requirements
  - Multibyte String Functions
- Pspell
  - Installing/Configuring
  - Predefined Constants
  - Pspell Functions
  - PSpell\Dictionary — The PSpell\Dictionary class
  - PSpell\Config — The PSpell\Config class
- Recode — GNU Recode
  - Installing/Configuring
  - Recode Functions

# Image Processing and Generation

# Exchangeable image information

# Introduction

With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers. These are commonly found in JPEG and TIFF images.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

Your PHP must be compiled in with `--enable-exif`. To enable multibyte support in EXIF tags, the mbstring extension must be enabled by compiling PHP with `--enable-mbstring`. PHP does not require any additional library for the exif module.

## Installation

To enable exif-support configure PHP with --enable-exif

Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your `HTTP` output.

Exif configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
exif.encode_unicode | "ISO-8859-15" | `INI_ALL` |
exif.decode_unicode_motorola | "UCS-2BE" | `INI_ALL` |
exif.decode_unicode_intel | "UCS-2LE" | `INI_ALL` |
exif.encode_jis | "" | `INI_ALL` |
exif.decode_jis_motorola | "JIS" | `INI_ALL` |
exif.decode_jis_intel | "JIS" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`exif.encode_unicode` string
  `exif.encode_unicode` defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.
`exif.decode_unicode_motorola` string
  `exif.decode_unicode_motorola` defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.
`exif.decode_unicode_intel` string
  `exif.decode_unicode_intel` defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.
`exif.encode_jis` string
  `exif.encode_jis` defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.
`exif.decode_jis_motorola` string
  `exif.decode_jis_motorola` defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.
`exif.decode_jis_intel` string
  `exif.decode_jis_intel` defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

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

`EXIF_USE_MBSTRING` (int)
  This constant has a value of `1` if the mbstring is enabled, otherwise it has a value of `0`.

The exif_imagetype() lists several related built-in constants.

# Exif Functions

# exif_imagetype

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

exif_imagetype — Determine the type of an image

### Description

exif_imagetype(string `$filename`): int|false

exif_imagetype() reads the first bytes of an image and checks its signature.

exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.

### Parameters

`filename`
  The image being checked.

### Return Values

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is `false`. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

The following constants are defined, and represent possible exif_imagetype() return values:

Imagetype Constants
Value | Constant
--- | ---
1 | `IMAGETYPE_GIF`
2 | `IMAGETYPE_JPEG`
3 | `IMAGETYPE_PNG`
4 | `IMAGETYPE_SWF`
5 | `IMAGETYPE_PSD`
6 | `IMAGETYPE_BMP`
7 | `IMAGETYPE_TIFF_II` (intel byte order)
8 | `IMAGETYPE_TIFF_MM` (motorola byte order)
9 | `IMAGETYPE_JPC`
10 | `IMAGETYPE_JP2`
11 | `IMAGETYPE_JPX`
12 | `IMAGETYPE_JB2`
13 | `IMAGETYPE_SWC`
14 | `IMAGETYPE_IFF`
15 | `IMAGETYPE_WBMP`
16 | `IMAGETYPE_XBM`
17 | `IMAGETYPE_ICO`
18 | `IMAGETYPE_WEBP`
19 | `IMAGETYPE_AVIF`

> Note: exif_imagetype() will emit an `E_NOTICE` and return `false` if it is unable to read enough bytes from the file to determine the image type.

### Changelog

Version | Description
--- | ---
7.1.0 | Added WebP support.
8.1.0 | Added AVIF support.

### Examples

Example #1 exif_imagetype() example

`<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>`

### See Also

- image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
- getimagesize() - Get the size of an image

# exif_read_data

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_read_data — Reads the EXIF headers from an image file

### Description

exif_read_data(
resource|string `$file`,
?string `$required_sections` = `null`,
bool `$as_arrays` = `false`,
bool `$read_thumbnail` = `false`
): array|false

exif_read_data() reads the EXIF headers from an image file. This way you can read meta data generated by digital cameras.

EXIF headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

`Height` and `Width` are computed the same way getimagesize() does so their values must not be part of any header returned. Also, `html` is a height/width text string to be used inside normal HTML.

When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the `COMPUTED` section will return both entries `Copyright.Photographer` and `Copyright.Editor` while the `IFD0` sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The `COMPUTED` will also contain the entry `Copyright` which is either the original copyright string, or a comma separated list of the photo and editor copyright.

The tag `UserComment` has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the `IFD` section only contains the encoding or a byte array. The `COMPUTED` section will store both in the entries `UserCommentEncoding` and `UserComment`. The entry `UserComment` is available in both cases so it should be used in preference to the value in `IFD0` section.

exif_read_data() also validates EXIF data tags according to the EXIF specification (» http://exif.org/Exif2-2.PDF, page 20).

### Parameters

`file`
  The location of the image file. This can either be a path to the file (stream wrappers are also supported as usual) or a stream resource.
`required_sections`

  Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is `false`.

  FILE | FileName, FileSize, FileDateTime, SectionsFound
  COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, `html` is a height/width text string to be used inside normal HTML.
  ANY_TAG | Any information that has a Tag e.g. `IFD0`, `EXIF`, ...
  IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
  THUMBNAIL | A file is supposed to contain a thumbnail if it has a second `IFD`. All tagged information about the embedded thumbnail is stored in this section.
  COMMENT | Comment headers of JPEG images.
  EXIF | The EXIF section is a sub section of `IFD0`. It contains more detailed information about an image. Most of these entries are digital camera related.

`as_arrays`
  Specifies whether or not each section becomes an array. The `required_sections` `COMPUTED`, `THUMBNAIL`, and `COMMENT` always become arrays as they may contain values whose names conflict with other sections.
`read_thumbnail`
  When set to `true` the thumbnail itself is read. Otherwise, only the tagged data is read.

### Return Values

It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return `false`.

### Errors/Exceptions

Errors of level `E_WARNING` and/or `E_NOTICE` may be raised for unsupported tags or other potential error conditions, but the function still tries to read all comprehensible information.

### Changelog

Version | Description
--- | ---
8.0.0 | `required_sections` is nullable now.
7.2.0 | The `file` parameter now supports both local files and stream resources.
7.2.0 | Support for the following EXIF formats were added: Samsung DJI Panasonic Sony Pentax Minolta Sigma/Foveon AGFA Kyocera Ricoh Epson

### Examples

Example #1 exif_read_data() example

`<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";
$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
echo "$key.$name: $val<br />\n";
}
}
?>`

The first call fails because the image has no header information.

The above example will output something similar to:

    test1.jpg:
    No header data found.
    test2.jpg:
    FILE.FileName: test2.jpg
    FILE.FileDateTime: 1017666176
    FILE.FileSize: 1240
    FILE.FileType: 2
    FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
    COMPUTED.html: width="1" height="1"
    COMPUTED.Height: 1
    COMPUTED.Width: 1
    COMPUTED.IsColor: 1
    COMPUTED.ByteOrderMotorola: 1
    COMPUTED.UserComment: Exif test image.
    COMPUTED.UserCommentEncoding: ASCII
    COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
    COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
    COMPUTED.Copyright.Editor: Edited by M.Boerger.
    IFD0.Copyright: Photo (c) M.Boerger
    IFD0.UserComment: ASCII
    THUMBNAIL.JPEGInterchangeFormat: 134
    THUMBNAIL.JPEGInterchangeFormatLength: 523
    COMMENT.0: Comment #1.
    COMMENT.1: Comment #2.
    COMMENT.2: Comment #3end
    THUMBNAIL.JPEGInterchangeFormat: 134
    THUMBNAIL.Thumbnail.Height: 1
    THUMBNAIL.Thumbnail.Height: 1

Example #2 exif_read_data() with streams available as of PHP 7.2.0

`<?php
// Open a the file, this should be in binary mode
$fp = fopen('/path/to/image.jpg', 'rb');
if (!$fp) {
echo 'Error: Unable to open image for reading';
exit;
}
// Attempt to read the exif headers
$headers = exif_read_data($fp);
if (!$headers) {
echo 'Error: Unable to read exif headers';
exit;
}
// Print the 'COMPUTED' headers
echo 'EXIF Headers:' . PHP_EOL;
foreach ($headers['COMPUTED'] as $header => $value) {
printf(' %s => %s%s', $header, $value, PHP_EOL);
}
?>`

The above example will output something similar to:

    EXIF Headers:
     Height => 576
     Width => 1024
     IsColor => 1
     ByteOrderMotorola => 0
     ApertureFNumber => f/5.6
     UserComment =>
     UserCommentEncoding => UNDEFINED
     Copyright => Denis
     Thumbnail.FileType => 2
     Thumbnail.MimeType => image/jpeg

### Notes

> Note: If mbstring is enabled, exif will attempt to process the unicode and pick a charset as specified by exif.decode_unicode_motorola and exif.decode_unicode_intel. The exif extension will not attempt to figure out the encoding on its own, and it is up to the user to properly specify the encoding for which to use for decoding by setting one of these two ini directives prior to calling exif_read_data().

> Note: If the `file` is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns.

### See Also

- exif_thumbnail() - Retrieve the embedded thumbnail of an image
- getimagesize() - Get the size of an image
- Supported Protocols and Wrappers

# exif_tagname

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_tagname — Get the header name for an index

### Description

exif_tagname(int `$index`): string|false

### Parameters

`index`
  The Tag ID for which a Tag Name will be looked up.

### Return Values

Returns the header name, or `false` if `index` is not a defined EXIF tag id.

### Examples

Example #1 exif_tagname() example

`<?php
echo "256: ".exif_tagname(256).PHP_EOL;
echo "257: ".exif_tagname(257).PHP_EOL;
?>`

The above example will output:

    256: ImageWidth
    257: ImageLength

### See Also

- exif_imagetype() - Determine the type of an image
- » EXIF Specification
- » EXIF Tags

# exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_thumbnail — Retrieve the embedded thumbnail of an image

### Description

exif_thumbnail(
resource|string `$file`,
int `&$width` = `null`,
int `&$height` = `null`,
int `&$image_type` = `null`
): string|false

exif_thumbnail() reads the embedded thumbnail of an image.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.

It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is `false` but `width` and `height` are set.

### Parameters

`file`
  The location of the image file. This can either be a path to the file or a stream resource.
`width`
  The return width of the returned thumbnail.
`height`
  The returned height of the returned thumbnail.
`image_type`
  The returned image type of the returned thumbnail. This is either TIFF or JPEG.

### Return Values

Returns the embedded thumbnail, or `false` if the image contains no thumbnail.

### Changelog

Version | Description
--- | ---
7.2.0 | The `file` parameter now supports both local files and stream resources.

### Examples

Example #1 exif_thumbnail() example

`<?php
$image = exif_thumbnail('/path/to/image.jpg', $width, $height, $type);
if ($image!==false) {
header('Content-type: ' .image_type_to_mime_type($type));
echo $image;
exit;
} else {
// no thumbnail available, handle the error here
echo 'No thumbnail available';
}
?>`

### Notes

> Note: If the `file` is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns.

### See Also

- exif_read_data() - Reads the EXIF headers from an image file
- image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

# read_exif_data

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

read_exif_data — Alias of exif_read_data()

Warning

This alias was DEPRECATED in PHP 7.2.0, and REMOVED as of PHP 8.0.0.

### Description

This function is an alias of: exif_read_data().

### Changelog

Version | Description
--- | ---
7.2.0 | This function alias was deprecated.

## Table of Contents

- exif_imagetype — Determine the type of an image
- exif_read_data — Reads the EXIF headers from an image file
- exif_tagname — Get the header name for an index
- exif_thumbnail — Retrieve the embedded thumbnail of an image
- read_exif_data — Alias of exif_read_data

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Exif Functions
  - exif_imagetype — Determine the type of an image
  - exif_read_data — Reads the EXIF headers from an image file
  - exif_tagname — Get the header name for an index
  - exif_thumbnail — Retrieve the embedded thumbnail of an image
  - read_exif_data — Alias of exif_read_data

# Image Processing and GD

# Introduction

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more conveniently, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library.

> Note: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

> Note: The getimagesize() function does not require the GD extension.

Caution

While the bundled version of the GD library uses the Zend memory manager to allocate memory, system versions do not, so that memory_limit does not apply.

GD supports a varity of formats, below is a list of formats supported by GD and notes to their availability including read/write support.

Formats supported by GD
Format | Read support | Write support | Notes
--- | --- | --- | ---
JPEG | `true` | `true` |
PNG | `true` | `true` |
GIF | `true` | `true` |
XBM | `true` | `true` |
XPM | `true` | `false` |
WBMP | `true` | `true` |
WebP | `true` | `true` |
BMP | `true` | `true` | Available as of PHP 7.2.0

Despite most formats being available for both reading and writing in the above table, doesn't mean that PHP was compiled with support for them. To find out which formats that was available to GD during compilation, use the gd_info() function, for more information about compiling support for one or more formats, see the installation chapter.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

If you have the GD library (available at » http://www.libgd.org/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats.

> Note: libgd-2.1.0 or higher is required. Alternatively, use the bundled GD library that ships with PHP.

> Note: The GD library requires zlib >= 1.2.0.4.

You may wish to enhance GD to handle more image formats.

Supported image formats
Image format | Library to download | Notes
--- | --- | ---
`gif` |  |
`avif` |  |
`jpeg` | » http://www.ijg.org/ | When building the jpeg library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying `libjpeg.(a|so) not found` when you get to the configure step of building PHP.
`png` | » http://www.libpng.org/pub/png/libpng.html |
`xpm` | » http://www.ibiblio.org/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.
`webp` |  |

You may wish to enhance GD to deal with different fonts. The » FreeType 2 library is supported.

## Installation

To enable GD-support configure PHP --with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library, use the configure option --with-gd. GD library requires libpng and libjpeg to compile. As of PHP 7.4.0, --with-gd becomes --enable-gd (whether to enable the extension at all) and --with-external-gd (to opt into using an external libgd, rather than the bundled one).

In Windows, you'll include the GD DLL php_gd.dll as an extension in php.ini. Prior to PHP 8.0.0, the DLL was named php_gd2.dll.

Enhance the capabilities of GD to handle more image formats by specifying the `--with-XXXX` configure switch to your PHP configure line.

Supported image formats
Image Format | Configure Switch
--- | ---
`avif` | To enable support for avif add --with-avif. Available as of PHP 8.1.0.
`jpeg` | To enable support for jpeg add --with-jpeg-dir=DIR. Jpeg 6b, 7 or 8 are supported. As of PHP 7.4.0, use --with-jpeg instead.
`png` | To enable support for png add --with-png-dir=DIR. Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line. As of PHP 7.4.0, --with-png-dir and --with-zlib-dir have been removed. libpng and zlib are required.
`xpm` | To enable support for xpm add --with-xpm-dir=DIR. If configure is not able to find the required libraries, you may add the path to your X11 libraries. As of PHP 7.4.0, use --with-xpm instead.
`webp` | To enable support for webp add --with-webp-dir=DIR. As of PHP 7.4.0, use --with-webp instead.

> Note: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

Enhance the capabilities of GD to deal with different fonts by specifying the `--with-XXXX` configure switch to your PHP configure line.

Supported font libraries
Font library | Configure Switch
--- | ---
`FreeType 2` | To enable support for FreeType 2 add --with-freetype-dir=DIR. As of PHP 7.4.0 use --with-freetype instead, which relies on pkg-config.
`Native TrueType string function` | To enable support for native TrueType string function add --enable-gd-native-ttf. (This option has no effect and has been removed as of PHP 7.2.0.)

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Image Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
gd.jpeg_ignore_warning | "1" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`gd.jpeg_ignore_warning` bool

  Ignore warnings (but not errors) created by libjpeg(-turbo).

Changelog for `gd.jpeg_ignore_warning`
Version | Description
--- | ---
7.1.0 | The default of gd.jpeg_ignore_warning has been changed from 0 to 1.

See also the exif configuration directives.

Warning

Image functions are very memory intensive. Be sure to set memory_limit high enough, if you are using the bundled version of the GD library.

## Resource Types

This extension defines the following resource types:

List of resource types in GD
Name | Description | Notes
--- | --- | ---
`gd` | Image resource, used by functions like imagecreatefrompng() | Prior to PHP 8.0.0
`gd font` | Font resource internally created by imageloadfont() | Prior to PHP 8.1.0

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

`GD_VERSION` (string)
  The GD version PHP was compiled against.
`GD_MAJOR_VERSION` (int)
  The GD major version PHP was compiled against.
`GD_MINOR_VERSION` (int)
  The GD minor version PHP was compiled against.
`GD_RELEASE_VERSION` (int)
  The GD release version PHP was compiled against.
`GD_EXTRA_VERSION` (string)
  The GD "extra" version (beta/rc..) PHP was compiled against.
`GD_BUNDLED` (int)
  When the bundled version of GD is used this is 1 otherwise its set to 0.
`IMG_AVIF` (int)
  Used as a return value by imagetypes() (Available as of PHP 8.1.0)
`IMG_BMP` (int)
  Used as a return value by imagetypes()
`IMG_GIF` (int)
  Used as a return value by imagetypes()
`IMG_JPG` (int)
  Used as a return value by imagetypes()
`IMG_JPEG` (int)
  Used as a return value by imagetypes()

  > Note:

  > This constant has the same value as `IMG_JPG`

`IMG_PNG` (int)
  Used as a return value by imagetypes()
`IMG_TGA` (int)
  Used as a return value by imagetypes() (Available as of PHP 7.4.0)
`IMG_WBMP` (int)
  Used as a return value by imagetypes()
`IMG_XPM` (int)
  Used as a return value by imagetypes()
`IMG_WEBP` (int)
  Used as a return value by imagetypes() (Available as of PHP 7.0.10)
`IMG_WEBP_LOSSLESS` (int)
  (Available as of PHP 8.1.0)
`IMG_COLOR_TILED` (int)
  Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
`IMG_COLOR_STYLED` (int)
  Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
`IMG_COLOR_BRUSHED` (int)
  Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
`IMG_COLOR_STYLEDBRUSHED` (int)
  Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
`IMG_COLOR_TRANSPARENT` (int)
  Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
`IMG_AFFINE_TRANSLATE` (int)
  An affine transformation type constant used by the imageaffinematrixget() function.
`IMG_AFFINE_SCALE` (int)
  An affine transformation type constant used by the imageaffinematrixget() function.
`IMG_AFFINE_ROTATE` (int)
  An affine transformation type constant used by the imageaffinematrixget() function.
`IMG_AFFINE_SHEAR_HORIZONTAL` (int)
  An affine transformation type constant used by the imageaffinematrixget() function.
`IMG_AFFINE_SHEAR_VERTICAL` (int)
  An affine transformation type constant used by the imageaffinematrixget() function.
`IMG_ARC_ROUNDED` (int)
  A style constant used by the imagefilledarc() function.

  > Note:

  > This constant has the same value as `IMG_ARC_PIE`

`IMG_ARC_PIE` (int)
  A style constant used by the imagefilledarc() function.
`IMG_ARC_CHORD` (int)
  A style constant used by the imagefilledarc() function.
`IMG_ARC_NOFILL` (int)
  A style constant used by the imagefilledarc() function.
`IMG_ARC_EDGED` (int)
  A style constant used by the imagefilledarc() function.
`IMG_GD2_RAW` (int)
  A type constant used by the imagegd2() function.
`IMG_GD2_COMPRESSED` (int)
  A type constant used by the imagegd2() function.
`IMG_EFFECT_REPLACE` (int)
  Alpha blending effect used by the imagelayereffect() function.
`IMG_EFFECT_ALPHABLEND` (int)
  Alpha blending effect used by the imagelayereffect() function.
`IMG_EFFECT_NORMAL` (int)
  Alpha blending effect used by the imagelayereffect() function.
`IMG_EFFECT_OVERLAY` (int)
  Alpha blending effect used by the imagelayereffect() function.
`IMG_EFFECT_MULTIPLY` (int)
  Alpha blending effect used by the imagelayereffect() function.
`IMG_FILTER_NEGATE` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_GRAYSCALE` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_BRIGHTNESS` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_CONTRAST` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_COLORIZE` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_EDGEDETECT` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_GAUSSIAN_BLUR` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_SELECTIVE_BLUR` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_EMBOSS` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_MEAN_REMOVAL` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_SMOOTH` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_PIXELATE` (int)
  Special GD filter used by the imagefilter() function.
`IMG_FILTER_SCATTER` (int)
  Special GD filter used by the imagefilter() function. (Available as of PHP 7.4.0)
`IMAGETYPE_GIF` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JPEG` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JPEG2000` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_PNG` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_SWF` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_PSD` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_BMP` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_WBMP` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_XBM` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_TIFF_II` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_TIFF_MM` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_IFF` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JB2` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JPC` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JP2` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_JPX` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_SWC` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_ICO` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_WEBP` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 7.1.0)
`IMAGETYPE_AVIF` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 8.1.0)
`IMAGETYPE_UNKNOWN` (int)
  Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
`IMAGETYPE_COUNT` (int)
  The number of image type constants (including the "unknown" type) supported by the image_type_to_mime_type() and image_type_to_extension() functions
`PNG_NO_FILTER` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_FILTER_NONE` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_FILTER_SUB` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_FILTER_UP` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_FILTER_AVG` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_FILTER_PAETH` (int)
  A special PNG filter, used by the imagepng() function.
`PNG_ALL_FILTERS` (int)
  A special PNG filter, used by the imagepng() function.
`IMG_FLIP_VERTICAL` (int)
  Used together with imageflip(), available as of PHP 5.5.0.
`IMG_FLIP_HORIZONTAL` (int)
  Used together with imageflip(), available as of PHP 5.5.0.
`IMG_FLIP_BOTH` (int)
  Used together with imageflip(), available as of PHP 5.5.0.
`IMG_BELL` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BESSEL` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BILINEAR_FIXED` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BICUBIC` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BICUBIC_FIXED` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BLACKMAN` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BOX` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_BSPLINE` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_CATMULLROM` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_GAUSSIAN` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_GENERALIZED_CUBIC` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_HERMITE` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_HAMMING` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_HANNING` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_MITCHELL` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_POWER` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_QUADRATIC` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_SINC` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_NEAREST_NEIGHBOUR` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_WEIGHTED4` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_TRIANGLE` (int)
  Used together with imagesetinterpolation(), available as of PHP 5.5.0.
`IMG_CROP_BLACK` (int)
  Crops out a black background.
`IMG_CROP_DEFAULT` (int)
  Same as `IMG_CROP_TRANSPARENT`. Before PHP 7.4.0, the bundled libgd fell back to `IMG_CROP_SIDES`, if the image had no transparent color.
`IMG_CROP_SIDES` (int)
  Uses the 4 corners of the image to attempt to detect the background to crop.
`IMG_CROP_THRESHOLD` (int)
  Crops an image using the given `threshold` and `color`.
`IMG_CROP_TRANSPARENT` (int)
  Crops out a transparent background.
`IMG_CROP_WHITE` (int)
  Crops out a white background.

# Examples

## Table of Contents

- PNG creation with PHP
- Adding watermarks to images using alpha channels
- Using imagecopymerge to create a translucent watermark

## PNG creation with PHP

Example #1 PNG creation with PHP

`<?php
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
?>`
This example would be called from a page with a tag like: `<img src="button.php?text=text">`. The above button.php script then takes this `"text"` string and overlays it on top of a base image which in this case is `"images/button1.png"` and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

## Adding watermarks to images using alpha channels

Example #1 Adding watermarks to images using alpha channels

`<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');
// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
// Output
header('Content-type: image/png');
imagepng($im);
?>`
This example is a common way to add watermarks and stamps to photos and copyrighted images. Note that the presence of an alpha channel in the stamp image as the text is anti-aliased. This is preserved during copying.

## Using imagecopymerge() to create a translucent watermark

Example #1 Using imagecopymerge() to create a translucent watermark

`<?php
// Load the stamp and the photo to apply the watermark to
$im = imagecreatefromjpeg('photo.jpeg');
// First we create our stamp image manually from GD
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
imagestring($stamp, 5, 20, 20, 'libGD', 0x0000FF);
imagestring($stamp, 3, 20, 40, '(c) 2007-9', 0x0000FF);
// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
// Merge the stamp onto our photo with an opacity of 50%
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);
// Save the image to file
imagepng($im, 'photo_stamp.png');
?>`
This example uses imagecopymerge() to merge the stamp with our original image. Using this we can set the opacity of our stamp - in our example we've set it to 50% opacity. In practice this would be useful in copyright protection as semi-transparent watermarks are hard to remove yet allow viewers to see the image.

# GD and Image Functions

# gd_info

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

gd_info — Retrieve information about the currently installed GD library

### Description

gd_info(): array

Gets information about the version and capabilities of the installed GD library.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array.

Elements of array returned by gd_info()
Attribute | Meaning
--- | ---
GD Version | string value describing the installed `libgd` version.
FreeType Support | bool value. `true` if FreeType Support is installed.
FreeType Linkage | string value describing the way in which FreeType was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if `FreeType Support` evaluated to `true`.
GIF Read Support | bool value. `true` if support for reading `GIF` images is included.
GIF Create Support | bool value. `true` if support for creating `GIF` images is included.
JPEG Support | bool value. `true` if `JPEG` support is included.
PNG Support | bool value. `true` if `PNG` support is included.
WBMP Support | bool value. `true` if `WBMP` support is included.
XBM Support | bool value. `true` if `XBM` support is included.
WebP Support | bool value. `true` if `WebP` support is included.
AVIF Support | bool value. `true` if `AVIF` support is included. Available as of PHP 8.1.0.

### Examples

Example #1 Using gd_info()

`<?php
var_dump(gd_info());
?>`

The above example will output something similar to:

    array(10) {
      ["GD Version"]=>
      string(24) "bundled (2.1.0 compatible)"
      ["FreeType Support"]=>
      bool(false)
      ["GIF Read Support"]=>
      bool(true)
      ["GIF Create Support"]=>
      bool(false)
      ["JPEG Support"]=>
      bool(false)
      ["PNG Support"]=>
      bool(true)
      ["WBMP Support"]=>
      bool(true)
      ["XBM Support"]=>
      bool(false)
      ["WebP Support"]=>
      bool(false)
      ["AVIF Support"]=>
      bool(false)
    }

### See Also

- imagepng() - Output a PNG image to either the browser or a file
- imagejpeg() - Output image to browser or file
- imagegif() - Output image to browser or file
- imagewbmp() - Output image to browser or file
- imagewebp() - Output a WebP image to browser or file
- imageavif() - Output image to browser or file
- imagetypes() - Return the image types supported by this PHP build

# getimagesize

(PHP 4, PHP 5, PHP 7, PHP 8)

getimagesize — Get the size of an image

### Description

getimagesize(string `$filename`, array `&$image_info` = `null`): array|false

The getimagesize() function will determine the size of any supported given image file and return the dimensions along with the file type and a `height/width` text string to be used inside a normal HTML `IMG` tag and the correspondent HTTP content type.

getimagesize() can also return some more information in `image_info` parameter.

Caution

This function expects `filename` to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.

Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

> Note: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain `multiple JPEG 2000 codestreams`. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

> Note: The information about icons are retrieved from the icon with the highest bitrate.

> Note: GIF images consist of one or more frames, where each frame may only occupy part of the image. The size of the image which is reported by getimagesize() is the overall size (read from the logical screen descriptor).

### Parameters

`filename`

  This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.

`image_info`

  This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

  > Note:

  > The `image_info` only supports JFIF files.

### Return Values

Returns an array with up to 7 elements. Not all image types will include the `channels` and `bits` elements.

Index 0 and 1 contains respectively the width and the height of the image.

> Note:

> Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

> Note: getimagesize() is agnostic of any image metadata. If e.g. the Exif `Orientation` flag is set to a value which rotates the image by 90 or 270 degress, index 0 and 1 are swapped, i.e. the contain the height and width, respectively.

Index 2 is one of the `IMAGETYPE_*` constants indicating the type of the image.

Index 3 is a text string with the correct `height="yyy" width="xxx"` string that can be used directly in an IMG tag.

`mime` is the correspondant MIME type of the image. This information can be used to deliver images with the correct HTTP `Content-type` header:

Example #1 getimagesize() and MIME types

`<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
header("Content-type: {$size['mime']}");
fpassthru($fp);
exit;
} else {
// error
}
?>`

`channels` will be 3 for RGB pictures and 4 for CMYK pictures.

`bits` is the number of bits for each color.

For some image types, the presence of `channels` and `bits` values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, `false` is returned.

### Errors/Exceptions

If accessing the `filename` image is impossible getimagesize() will generate an error of level `E_WARNING`. On read error, getimagesize() will generate an error of level `E_NOTICE`.

As of PHP 8.0.0, a ValueError is thrown if `filename` is empty.

### Changelog

Version | Description
--- | ---
8.2.0 | Now returns the actual image dimensions, bits and channels of AVIF images; previously, the dimensions were reported as `0x0`, and bits and channels were not reported at all.
8.0.0 | A ValueError is now thrown if `filename` is empty; previously an `E_WARNING` was raised and the function returned `false`.
7.1.0 | Added WebP support.

### Examples

Example #2 getimagesize() example

`<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>`

Example #3 getimagesize (URL)

`<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");
// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");
?>`

Example #4 getimagesize() returning IPTC

`<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
$iptc = iptcparse($info["APP13"]);
var_dump($iptc);
}
?>`

### Notes

> Note:

> This function does not require the GD image library.

### See Also

- image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
- exif_imagetype() - Determine the type of an image
- exif_read_data() - Reads the EXIF headers from an image file
- exif_thumbnail() - Retrieve the embedded thumbnail of an image
- imagesx() - Get image width
- imagesy() - Get image height

# getimagesizefromstring

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

getimagesizefromstring — Get the size of an image from a string

### Description

getimagesizefromstring(string `$string`, array `&$image_info` = `null`): array|false

Identical to getimagesize() except that getimagesizefromstring() accepts a string instead of a file name as the first parameter.

See the getimagesize() documentation for details on how this function works.

### Parameters

`string`

  The image data, as a string.

`image_info`

  See getimagesize().

### Return Values

See getimagesize().

### Examples

Example #1 getimagesizefromstring() example

`<?php
$img = '/path/to/test.png';
// Open as a file
$size_info1 = getimagesize($img);
// Or open as a string
$data = file_get_contents($img);
$size_info2 = getimagesizefromstring($data);
?>`

### See Also

- getimagesize() - Get the size of an image

# image_type_to_extension

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

image_type_to_extension — Get file extension for image type

### Description

image_type_to_extension(int `$image_type`, bool `$include_dot` = `true`): string|false

Returns the extension for the given `IMAGETYPE_*` constant.

### Parameters

`image_type`

  One of the `IMAGETYPE_*` constant.

`include_dot`

  Whether to prepend a dot to the extension or not. Default to `true`.

### Return Values

A string with the extension corresponding to the given image type, or `false` on failure.

### Examples

Example #1 image_type_to_extension() example

`<?php
// Create image instance
$im = imagecreatetruecolor(100, 100);
// Save image
imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG));
?>`

### Notes

> Note:

> This function does not require the GD image library.

# image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

### Description

image_type_to_mime_type(int `$image_type`): string

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

### Parameters

`image_type`

  One of the `IMAGETYPE_*` constants.

### Return Values

The returned values are as follows

Returned values Constants
`image_type` | Returned value
--- | ---
`IMAGETYPE_GIF` | `image/gif`
`IMAGETYPE_JPEG` | `image/jpeg`
`IMAGETYPE_PNG` | `image/png`
`IMAGETYPE_SWF` | `application/x-shockwave-flash`
`IMAGETYPE_PSD` | `image/psd`
`IMAGETYPE_BMP` | `image/bmp`
`IMAGETYPE_TIFF_II` (intel byte order) | `image/tiff`
`IMAGETYPE_TIFF_MM` (motorola byte order) | `image/tiff`
`IMAGETYPE_JPC` | `application/octet-stream`
`IMAGETYPE_JP2` | `image/jp2`
`IMAGETYPE_JPX` | `application/octet-stream`
`IMAGETYPE_JB2` | `application/octet-stream`
`IMAGETYPE_SWC` | `application/x-shockwave-flash`
`IMAGETYPE_IFF` | `image/iff`
`IMAGETYPE_WBMP` | `image/vnd.wap.wbmp`
`IMAGETYPE_XBM` | `image/xbm`
`IMAGETYPE_ICO` | `image/vnd.microsoft.icon`
`IMAGETYPE_WEBP` | `image/webp`
`IMAGETYPE_AVIF` | `image/avif`

### Examples

Example #1 image_type_to_mime_type() example

`<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>`

### Notes

> Note:

> This function does not require the GD image library.

### See Also

- getimagesize() - Get the size of an image
- exif_imagetype() - Determine the type of an image
- exif_read_data() - Reads the EXIF headers from an image file
- exif_thumbnail() - Retrieve the embedded thumbnail of an image

# image2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

image2wbmp — Output image to browser or file

Warning

This function has been DEPRECATED as of PHP 7.3.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

image2wbmp(resource `$image`, string `$filename` = ?, int `$foreground` = ?): bool

image2wbmp() outputs or save a WBMP version of the given `image`.

### Parameters

`image`

  An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

`filename`

  Path to the saved file. If not given, the raw image stream will be output directly.

`foreground`

  You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Examples

Example #1 image2wbmp() example

`<?php
$file = 'php.png';
$image = imagecreatefrompng($file);
header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // output the stream directly
?>`

### See Also

- imagewbmp() - Output image to browser or file

# imageaffine

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffine — Return an image containing the affine transformed src image, using an optional clipping area

### Description

imageaffine(GdImage `$image`, array `$affine`, ?array `$clip` = `null`): GdImage|false

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`affine`

  Array with keys 0 to 5.

`clip`

  Array with keys "x", "y", "width" and "height"; or `null`.

### Return Values

Return affined image object on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `clip` is now nullable.
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

# imageaffinematrixconcat

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffinematrixconcat — Concatenate two affine transformation matrices

### Description

imageaffinematrixconcat(array `$matrix1`, array `$matrix2`): array|false

Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go.

### Parameters

`matrix1`

  An affine transformation matrix (an array with keys `0` to `5` and float values).

`matrix2`

  An affine transformation matrix (an array with keys `0` to `5` and float values).

### Return Values

An affine transformation matrix (an array with keys `0` to `5` and float values) or `false` on failure.

### Examples

Example #1 imageaffinematrixconcat() example

`<?php
$m1 = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' => 2, 'y' => 3));
$m2 = imageaffinematrixget(IMG_AFFINE_SCALE, array('x' => 4, 'y' => 5));
$matrix = imageaffinematrixconcat($m1, $m2);
print_r($matrix);
?>`

The above example will output:

    Array
    (
        [0] => 4
        [1] => 0
        [2] => 0
        [3] => 5
        [4] => 8
        [5] => 15
    )

### See Also

- imageaffine() - Return an image containing the affine transformed src image, using an optional clipping area
- imageaffinematrixget() - Get an affine transformation matrix

# imageaffinematrixget

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffinematrixget — Get an affine transformation matrix

### Description

imageaffinematrixget(int `$type`, array|float `$options`): array|false

Returns an affine transformation matrix.

### Parameters

`type`

  One of the `IMG_AFFINE_*` constants.

`options`

  If `type` is `IMG_AFFINE_TRANSLATE` or `IMG_AFFINE_SCALE`, `options` has to be an array with keys `x` and `y`, both having float values.

  If `type` is `IMG_AFFINE_ROTATE`, `IMG_AFFINE_SHEAR_HORIZONTAL` or `IMG_AFFINE_SHEAR_VERTICAL`, `options` has to be a float specifying the angle.

### Return Values

An affine transformation matrix (an array with keys `0` to `5` and float values) or `false` on failure.

### Examples

Example #1 imageaffinematrixget() example

`<?php
$matrix = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' => 2, 'y' => 3));
print_r($matrix);
?>`

The above example will output:

    Array
    (
        [0] => 1
        [1] => 0
        [2] => 0
        [3] => 1
        [4] => 2
        [5] => 3
    )

### See Also

- imageaffine() - Return an image containing the affine transformed src image, using an optional clipping area
- imageaffinematrixconcat() - Concatenate two affine transformation matrices

# imagealphablending

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagealphablending — Set the blending mode for an image

### Description

imagealphablending(GdImage `$image`, bool `$enable`): true

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`enable`

  Whether to enable the blending mode or not. On true color images the default value is `true` otherwise the default value is `false`

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagealphablending() usage example

`<?php
// Create image
$im = imagecreatetruecolor(100, 100);
// Set alphablending to on
imagealphablending($im, true);
// Draw a square
imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));
// Output
header('Content-Type: image/png');
imagepng($im);
?>`

# imageantialias

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imageantialias — Should antialias functions be used or not

### Description

imageantialias(GdImage `$image`, bool `$enable`): true

Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Thickness and styled are not supported.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`enable`

  Whether to enable antialiasing or not.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
7.2.0 | imageantialias() is now generally available. Formerly it was only available if PHP was compiled with the bundled version of the GD library.

### Examples

Example #1 A comparison of two lines, one with anti-aliasing switched on

`<?php
// Setup an anti-aliased image and a normal image
$aa = imagecreatetruecolor(400, 100);
$normal = imagecreatetruecolor(200, 100);
// Switch antialiasing on for one image
imageantialias($aa, true);
// Allocate colors
$red = imagecolorallocate($normal, 255, 0, 0);
$red_aa = imagecolorallocate($aa, 255, 0, 0);
// Draw two lines, one with AA enabled
imageline($normal, 0, 0, 200, 100, $red);
imageline($aa, 0, 0, 200, 100, $red_aa);
// Merge the two images side by side for output (AA: left, Normal: Right)
imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100);
// Output image
header('Content-type: image/png');
imagepng($aa);
?>`

The above example will output something similar to:

### See Also

- imagecreatetruecolor() - Create a new true color image

# imagearc

(PHP 4, PHP 5, PHP 7, PHP 8)

imagearc — Draws an arc

### Description

imagearc(
GdImage `$image`,
int `$center_x`,
int `$center_y`,
int `$width`,
int `$height`,
int `$start_angle`,
int `$end_angle`,
int `$color`
): true

imagearc() draws an arc of circle centered at the given coordinates.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`center_x`

  x-coordinate of the center.

`center_y`

  y-coordinate of the center.

`width`

  The arc width.

`height`

  The arc height.

`start_angle`

  The arc start angle, in degrees.

`end_angle`

  The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Drawing a circle with imagearc()

`<?php
// create a 200*200 image
$img = imagecreatetruecolor(200, 200);
// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$blue = imagecolorallocate($img, 0, 0, 255);
// draw the head
imagearc($img, 100, 100, 200, 200, 0, 360, $white);
// mouth
imagearc($img, 100, 100, 150, 150, 25, 155, $red);
// left and then the right eye
imagearc($img, 60, 75, 50, 50, 0, 360, $green);
imagearc($img, 140, 75, 50, 50, 0, 360, $blue);
// output image in the browser
header("Content-type: image/png");
imagepng($img);
?>`

The above example will output something similar to:

### See Also

- imagefilledarc() - Draw a partial arc and fill it
- imageellipse() - Draw an ellipse
- imagefilledellipse() - Draw a filled ellipse

# imageavif

(PHP 8 >= 8.1.0)

imageavif — Output image to browser or file

### Description

imageavif(
GdImage `$image`,
resource|string|null `$file` = `null`,
int `$quality` = -1,
int `$speed` = -1
): bool

Outputs or saves a AVIF Raster image from the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

`quality`

  `quality` is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, larger file). If `-1` is provided, the default value `52` is used.

`speed`

  `speed` is optional, and ranges from 0 (slow, smaller file) to 10 (fast, larger file). If `-1` is provided, the default value `6` is used.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Errors/Exceptions

Throws a ValueError if `quality` or `speed` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `quality` or `speed` is invalid.

### See Also

- imagepng() - Output a PNG image to either the browser or a file
- imagewbmp() - Output image to browser or file
- imagejpeg() - Output image to browser or file
- imagetypes() - Return the image types supported by this PHP build

# imagebmp

(PHP 7 >= 7.2.0, PHP 8)

imagebmp — Output a BMP image to browser or file

### Description

imagebmp(GdImage `$image`, resource|string|null `$file` = `null`, bool `$compressed` = `true`): bool

Outputs or saves a BMP version of the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

  > Note:

  > `null` is invalid if the `compressed` arguments is not used.

`compressed`

  Whether the BMP should be compressed with run-length encoding (RLE), or not.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | The type of `compressed` is bool now; formerly it was int.

### Examples

Example #1 Saving a BMP file

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'BMP with PHP', $text_color);
// Save the image
imagebmp($im, 'php.bmp');
?>`

# imagechar

(PHP 4, PHP 5, PHP 7, PHP 8)

imagechar — Draw a character horizontally

### Description

imagechar(
GdImage `$image`,
GdFont|int `$font`,
int `$x`,
int `$y`,
string `$char`,
int `$color`
): true

imagechar() draws the first character of `char` in the image identified by `image` with its upper-left at `x`,`y` (top left is 0, 0) with the color `color`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

`x`

  x-coordinate of the start.

`y`

  y-coordinate of the start.

`char`

  The character to draw.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagechar() example

`<?php
$im = imagecreate(100, 100);
$string = 'PHP';
$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// prints a black "P" in the top left corner
imagechar($im, 1, 0, 0, $string, $black);
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagecharup() - Draw a character vertically
- imageloadfont() - Load a new font

# imagecharup

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecharup — Draw a character vertically

### Description

imagecharup(
GdImage `$image`,
GdFont|int `$font`,
int `$x`,
int `$y`,
string `$char`,
int `$color`
): true

Draws the character `char` vertically at the specified coordinate on the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

`x`

  x-coordinate of the start.

`y`

  y-coordinate of the start.

`char`

  The character to draw.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagecharup() example

`<?php
$im = imagecreate(100, 100);
$string = 'Note that the first letter is a N';
$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// prints a black "Z" on a white background
imagecharup($im, 3, 10, 10, $string, $black);
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagechar() - Draw a character horizontally
- imageloadfont() - Load a new font

# imagecolorallocate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorallocate — Allocate a color for an image

### Description

imagecolorallocate(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`
): int|false

Returns a color identifier representing the color composed of the given RGB components.

imagecolorallocate() must be called to create each color that is to be used in the image represented by `image`.

> Note:

> The first call to imagecolorallocate() fills the background color in palette-based images - images created using imagecreate().

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

A color identifier or `false` if the allocation failed.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagecolorallocate() example

`<?php
$im = imagecreate(100, 100);
// sets background to red
$background = imagecolorallocate($im, 255, 0, 0);
// sets some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// hexadecimal way
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
?>`

### See Also

- imagecolorallocatealpha() - Allocate a color for an image
- imagecolordeallocate() - De-allocate a color for an image

# imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imagecolorallocatealpha — Allocate a color for an image

### Description

imagecolorallocatealpha(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`,
int `$alpha`
): int|false

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter `alpha`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

`alpha`

  A value between `0` and `127`. `0` indicates completely opaque while `127` indicates completely transparent.

The `red`, `green` and `blue` parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

A color identifier or `false` if the allocation failed.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Example of using imagecolorallocatealpha()

`<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);
// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);
$yellow_x = 100;
$yellow_y = 75;
$red_x = 120;
$red_y = 165;
$blue_x = 187;
$blue_y = 125;
$radius = 150;
// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue = imagecolorallocatealpha($image, 0, 0, 255, 75);
// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);
// don't forget to output a correct header!
header('Content-Type: image/png');
// and finally, output the result
imagepng($image);
?>`

The above example will output something similar to:

Example #2 Convert typical alpha values for use with imagecolorallocatealpha()

Usually alpha values of `0` designate fully transparent pixels, and the alpha channel has 8 bits. To convert such alpha values to be compatible with imagecolorallocatealpha(), some simple arithmetic is sufficient:

`<?php
$alpha8 = 0; // fully transparent
var_dump(127 - ($alpha8 >> 1));
$alpha8 = 255; // fully opaque
var_dump(127 - ($alpha8 >> 1));
?>`

The above example will output:

    int(127)
    int(0)

### See Also

- imagecolorallocate() - Allocate a color for an image
- imagecolordeallocate() - De-allocate a color for an image

# imagecolorat

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorat — Get the index of the color of a pixel

### Description

imagecolorat(GdImage `$image`, int `$x`, int `$y`): int|false

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

If the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x`

  x-coordinate of the point.

`y`

  y-coordinate of the point.

### Return Values

Returns the index of the color or `false` on failure.

Warning

This function may return Boolean `false`, but may also return a non-Boolean value which evaluates to `false`. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Access distinct RGB values

`<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
var_dump($r, $g, $b);
?>`

The above example will output something similar to:

    int(119)
    int(123)
    int(180)

Example #2 Human-readable RGB values using imagecolorsforindex()

`<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$colors = imagecolorsforindex($im, $rgb);
var_dump($colors);
?>`

The above example will output something similar to:

    array(4) {
      ["red"]=>
      int(119)
      ["green"]=>
      int(123)
      ["blue"]=>
      int(180)
      ["alpha"]=>
      int(127)
    }

### See Also

- imagecolorset() - Set the color for the specified palette index
- imagecolorsforindex() - Get the colors for an index
- imagesetpixel() - Set a single pixel

# imagecolorclosest

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorclosest — Get the index of the closest color to the specified color

### Description

imagecolorclosest(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`
): int

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

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

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

Returns the index of the closest color, in the palette of the image, to the specified one

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Search for a set of colors in an image

`<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);
// Search colors (RGB)
$colors = array(
array(254, 145, 154),
array(153, 145, 188),
array(153, 90, 145),
array(255, 137, 92)
);
// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
$result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
$result = imagecolorsforindex($im, $result);
$result = "({$result['red']}, {$result['green']}, {$result['blue']})";
echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2]); Closest match: $result.\n";
}
?>`

The above example will output something similar to:

    #0: Search (254, 145, 154); Closest match: (252, 150, 148).
    #1: Search (153, 145, 188); Closest match: (148, 150, 196).
    #2: Search (153, 90, 145); Closest match: (148, 90, 156).
    #3: Search (255, 137, 92); Closest match: (252, 150, 92).

### See Also

- imagecolorexact() - Get the index of the specified color
- imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha
- imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

# imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha

### Description

imagecolorclosestalpha(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`,
int `$alpha`
): int

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

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

`alpha`

  A value between `0` and `127`. `0` indicates completely opaque while `127` indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

Returns the index of the closest color in the palette.

### Examples

Example #1 Search for a set of colors in an image

`<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);
// Search colors (RGB)
$colors = array(
array(254, 145, 154, 50),
array(153, 145, 188, 127),
array(153, 90, 145, 0),
array(255, 137, 92, 84)
);
// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
$result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
$result = imagecolorsforindex($im, $result);
$result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";
echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); Closest match: $result.\n";
}
?>`

The above example will output something similar to:

    #0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
    #1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
    #2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
    #3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

### See Also

- imagecolorexactalpha() - Get the index of the specified color + alpha
- imagecolorclosest() - Get the index of the closest color to the specified color
- imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

# imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

### Description

imagecolorclosesthwb(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`
): int

Get the index of the color which has the hue, white and blackness nearest the given color.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

### Return Values

Returns an integer with the index of the color which has the hue, white and blackness nearest the given color.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Example of using imagecolorclosesthwb()

`<?php
$im = imagecreatefromgif('php.gif');
echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);
?>`

The above example will output something similar to:

    HWB: 33

### See Also

- imagecolorclosest() - Get the index of the closest color to the specified color

# imagecolordeallocate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolordeallocate — De-allocate a color for an image

### Description

imagecolordeallocate(GdImage `$image`, int `$color`): true

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`color`

  The color identifier.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagecolordeallocate()

`<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>`

### See Also

- imagecolorallocate() - Allocate a color for an image
- imagecolorallocatealpha() - Allocate a color for an image

# imagecolorexact

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorexact — Get the index of the specified color

### Description

imagecolorexact(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`
): int

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

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

### Return Values

Returns the index of the specified color in the palette, or -1 if the color does not exist.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Get colors from the GD logo

`<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');
$colors = Array();
$colors[] = imagecolorexact($im, 255, 0, 0);
$colors[] = imagecolorexact($im, 0, 0, 0);
$colors[] = imagecolorexact($im, 255, 255, 255);
$colors[] = imagecolorexact($im, 100, 255, 52);
print_r($colors);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 16711680
        [1] => 0
        [2] => 16777215
        [3] => 6618932
    )

### See Also

- imagecolorclosest() - Get the index of the closest color to the specified color

# imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorexactalpha — Get the index of the specified color + alpha

### Description

imagecolorexactalpha(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`,
int `$alpha`
): int

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

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

`alpha`

  A value between `0` and `127`. `0` indicates completely opaque while `127` indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

Returns the index of the specified color+alpha in the palette of the image, or -1 if the color does not exist in the image's palette.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Get colors from the GD logo

`<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');
$colors = Array();
$colors[] = imagecolorexactalpha($im, 255, 0, 0, 0);
$colors[] = imagecolorexactalpha($im, 0, 0, 0, 127);
$colors[] = imagecolorexactalpha($im, 255, 255, 255, 55);
$colors[] = imagecolorexactalpha($im, 100, 255, 52, 20);
print_r($colors);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 16711680
        [1] => 2130706432
        [2] => 939524095
        [3] => 342163252
    )

### See Also

- imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

# imagecolormatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version

### Description

imagecolormatch(GdImage `$image1`, GdImage `$image2`): true

Makes the colors of the palette version of an image more closely match the true color version.

### Parameters

`image1`

  A truecolor image object.

`image2`

  A palette image object pointing to an image that has the same size as `image1`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image1` and `image2` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 imagecolormatch() example

`<?php
// Setup the true color and palette images
$im1 = imagecreatefrompng('./gdlogo.png');
$im2 = imagecreate(imagesx($im1), imagesy($im1));
// Add some colors to $im2
$colors = Array();
$colors[] = imagecolorallocate($im2, 255, 36, 74);
$colors[] = imagecolorallocate($im2, 40, 0, 240);
$colors[] = imagecolorallocate($im2, 82, 100, 255);
$colors[] = imagecolorallocate($im2, 84, 63, 44);
// Match these colors with the true color image
imagecolormatch($im1, $im2);
?>`

### See Also

- imagecreatetruecolor() - Create a new true color image

# imagecolorresolve

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorresolve — Get the index of the specified color or its closest possible alternative

### Description

imagecolorresolve(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`
): int

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

### Return Values

Returns a color index.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagecoloresolve() to get colors from an image

`<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');
// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolve($im, 255, 255, 255);
$colors[] = imagecolorresolve($im, 0, 0, 200);
// Output
print_r($colors);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 89
        [1] => 85
    )

### See Also

- imagecolorclosest() - Get the index of the closest color to the specified color

# imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative

### Description

imagecolorresolvealpha(
GdImage `$image`,
int `$red`,
int `$green`,
int `$blue`,
int `$alpha`
): int

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

`alpha`

  A value between `0` and `127`. `0` indicates completely opaque while `127` indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

### Return Values

Returns a color index.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagecoloresolvealpha() to get colors from an image

`<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');
// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolvealpha($im, 255, 255, 255, 0);
$colors[] = imagecolorresolvealpha($im, 0, 0, 200, 127);
// Output
print_r($colors);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 89
        [1] => 85
    )

### See Also

- imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

# imagecolorset

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorset — Set the color for the specified palette index

### Description

imagecolorset(
GdImage `$image`,
int `$color`,
int `$red`,
int `$green`,
int `$blue`,
int `$alpha` = 0
): ?false

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

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`color`

  An index in the palette.

`red`

  Value of red component.

`green`

  Value of green component.

`blue`

  Value of blue component.

`alpha`

  Value of alpha component.

### Return Values

The function returns `null` on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagecolorset() example

`<?php
// Create a 300x100 image
$im = imagecreate(300, 100);
// Set the background to be red
imagecolorallocate($im, 255, 0, 0);
// Get the color index for the background
$bg = imagecolorat($im, 0, 0);
// Set the background to be blue
imagecolorset($im, $bg, 0, 0, 255);
// Output the image to the browser
header('Content-Type: image/png');
imagepng($im);
?>`

### See Also

- imagecolorat() - Get the index of the color of a pixel

# imagecolorsforindex

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorsforindex — Get the colors for an index

### Description

imagecolorsforindex(GdImage `$image`, int `$color`): array

Gets the color for a specified index.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`color`

  The color index.

### Return Values

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

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | imagecolorsforindex() now throws a ValueError exception if `color` is out of range; previously, `false` was returned instead.

### Examples

Example #1 imagecolorsforindex() example

`<?php
// open an image
$im = imagecreatefrompng('nexen.png');
// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);
// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);
// what is it ?
print_r($color_tran);
?>`

The above example will output something similar to:

    Array
    (
       [red] => 226
       [green] => 222
       [blue] => 252
       [alpha] => 0
    )

### See Also

- imagecolorat() - Get the index of the color of a pixel
- imagecolorexact() - Get the index of the specified color

# imagecolorstotal

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorstotal — Find out the number of colors in an image's palette

### Description

imagecolorstotal(GdImage `$image`): int

Returns the number of colors in an image palette.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Returns the number of colors in the specified image's palette or 0 for truecolor images.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Getting total number of colors in an image using imagecolorstotal()

`<?php
// Create image instance
$im = imagecreatefromgif('php.gif');
echo 'Total colors in image: ' . imagecolorstotal($im);
?>`

The above example will output something similar to:

    Total colors in image: 128

### See Also

- imagecolorat() - Get the index of the color of a pixel
- imagecolorsforindex() - Get the colors for an index
- imageistruecolor() - Finds whether an image is a truecolor image

# imagecolortransparent

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolortransparent — Define a color as transparent

### Description

imagecolortransparent(GdImage `$image`, ?int `$color` = `null`): int

Gets or sets the transparent color in the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`color`

  A color identifier created with imagecolorallocate().

### Return Values

The identifier of the new (or current, if none is specified) transparent color is returned. If `color` is `null`, and the image has no transparent color, the returned identifier will be `-1`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | `color` is now nullable.

### Examples

Example #1 imagecolortransparent() example

`<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);
// Make the background transparent
imagecolortransparent($im, $black);
// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);
// Save the image
imagepng($im, './imagecolortransparent.png');
?>`

The above example will output something similar to:

### Notes

> Note:

> Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.

> Note:

> The transparent color is a property of the image, transparency is not a property of the color. Once you have set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

# imageconvolution

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset

### Description

imageconvolution(
GdImage `$image`,
array `$matrix`,
float `$divisor`,
float `$offset`
): bool

Applies a convolution matrix on the image, using the given coefficient and offset.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`matrix`

  A 3x3 matrix: an array of three arrays of three floats.

`divisor`

  The divisor of the result of the convolution, used for normalization.

`offset`

  Color offset.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Embossing the PHP.net logo

`<?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');
$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);
header('Content-Type: image/png');
imagepng($image, null, 9);
?>`

The above example will output:

Example #2 Gaussian blur

`<?php
$image = imagecreatetruecolor(180,40);
// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);
// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);
header('Content-Type: image/png');
imagepng($image, null, 9);
?>`

The above example will output:

### See Also

- imagefilter() - Applies a filter to an image

# imagecopy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecopy — Copy part of an image

### Description

imagecopy(
GdImage `$dst_image`,
GdImage `$src_image`,
int `$dst_x`,
int `$dst_y`,
int `$src_x`,
int `$src_y`,
int `$src_width`,
int `$src_height`
): true

Copy a part of `src_image` onto `dst_image` starting at the x,y coordinates `src_x`, `src_y` with a width of `src_width` and a height of `src_height`. The portion defined will be copied onto the x,y coordinates, `dst_x` and `dst_y`.

### Parameters

`dst_image`

  Destination image resource.

`src_image`

  Source image resource.

`dst_x`

  x-coordinate of destination point.

`dst_y`

  y-coordinate of destination point.

`src_x`

  x-coordinate of source point.

`src_y`

  y-coordinate of source point.

`src_width`

  Source width.

`src_height`

  Source height.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst_image` and `src_image` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 Cropping the PHP.net logo

`<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
?>`

The above example will output something similar to:

### See Also

- imagecrop() - Crop an image to the given rectangle

# imagecopymerge

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecopymerge — Copy and merge part of an image

### Description

imagecopymerge(
GdImage `$dst_image`,
GdImage `$src_image`,
int `$dst_x`,
int `$dst_y`,
int `$src_x`,
int `$src_y`,
int `$src_width`,
int `$src_height`,
int `$pct`
): true

Copy a part of `src_image` onto `dst_image` starting at the x,y coordinates `src_x`, `src_y` with a width of `src_width` and a height of `src_height`. The portion defined will be copied onto the x,y coordinates, `dst_x` and `dst_y`.

### Parameters

`dst_image`

  Destination image resource.

`src_image`

  Source image resource.

`dst_x`

  x-coordinate of destination point.

`dst_y`

  y-coordinate of destination point.

`src_x`

  x-coordinate of source point.

`src_y`

  y-coordinate of source point.

`src_width`

  Source width.

`src_height`

  Source height.

`pct`

  The two images will be merged according to `pct` which can range from 0 to 100. When `pct` = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst_image` and `src_image` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 Merging two copies of the PHP.net logo with 75% transparency

`<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);
// Output
header('Content-Type: image/gif');
imagegif($dest);
?>`

# imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecopymergegray — Copy and merge part of an image with gray scale

### Description

imagecopymergegray(
GdImage `$dst_image`,
GdImage `$src_image`,
int `$dst_x`,
int `$dst_y`,
int `$src_x`,
int `$src_y`,
int `$src_width`,
int `$src_height`,
int `$pct`
): true

imagecopymergegray() copy a part of `src_image` onto `dst_image` starting at the x,y coordinates `src_x`, `src_y` with a width of `src_width` and a height of `src_height`. The portion defined will be copied onto the x,y coordinates, `dst_x` and `dst_y`.

This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.

### Parameters

`dst_image`

  Destination image resource.

`src_image`

  Source image resource.

`dst_x`

  x-coordinate of destination point.

`dst_y`

  y-coordinate of destination point.

`src_x`

  x-coordinate of source point.

`src_y`

  y-coordinate of source point.

`src_width`

  Source width.

`src_height`

  Source height.

`pct`

  The `src_image` will be changed to grayscale according to `pct` where 0 is fully grayscale and 100 is unchanged. When `pct` = 100 this function behaves identically to imagecopy() for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst_image` and `src_image` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 imagecopymergegray() usage

`<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);
// Output
header('Content-Type: image/gif');
imagegif($dest);
?>`

# imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecopyresampled — Copy and resize part of an image with resampling

### Description

imagecopyresampled(
GdImage `$dst_image`,
GdImage `$src_image`,
int `$dst_x`,
int `$dst_y`,
int `$src_x`,
int `$src_y`,
int `$dst_width`,
int `$dst_height`,
int `$src_width`,
int `$src_height`
): true

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, imagecopyresampled() will take a rectangular area from `src_image` of width `src_width` and height `src_height` at position (`src_x`,`src_y`) and place it in a rectangular area of `dst_image` of width `dst_width` and height `dst_height` at position (`dst_x`,`dst_y`).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if `dst_image` is the same as `src_image`) but if the regions overlap the results will be unpredictable.

### Parameters

`dst_image`

  Destination image resource.

`src_image`

  Source image resource.

`dst_x`

  x-coordinate of destination point.

`dst_y`

  y-coordinate of destination point.

`src_x`

  x-coordinate of source point.

`src_y`

  y-coordinate of source point.

`dst_width`

  Destination width.

`dst_height`

  Destination height.

`src_width`

  Source width.

`src_height`

  Source height.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst_image` and `src_image` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 Simple example

This example will resample an image to half its original size.

`<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>`

The above example will output something similar to:

Example #2 Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

`<?php
// The file
$filename = 'test.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>`

The above example will output something similar to:

### Notes

> Note:

> There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

### See Also

- imagecopyresized() - Copy and resize part of an image
- imagescale() - Scale an image using the given new width and height
- imagecrop() - Crop an image to the given rectangle

# imagecopyresized

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecopyresized — Copy and resize part of an image

### Description

imagecopyresized(
GdImage `$dst_image`,
GdImage `$src_image`,
int `$dst_x`,
int `$dst_y`,
int `$src_x`,
int `$src_y`,
int `$dst_width`,
int `$dst_height`,
int `$src_width`,
int `$src_height`
): true

imagecopyresized() copies a rectangular portion of one image to another image. `dst_image` is the destination image, `src_image` is the source image identifier.

In other words, imagecopyresized() will take a rectangular area from `src_image` of width `src_width` and height `src_height` at position (`src_x`,`src_y`) and place it in a rectangular area of `dst_image` of width `dst_width` and height `dst_height` at position (`dst_x`,`dst_y`).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if `dst_image` is the same as `src_image`) but if the regions overlap the results will be unpredictable.

### Parameters

`dst_image`

  Destination image resource.

`src_image`

  Source image resource.

`dst_x`

  x-coordinate of destination point.

`dst_y`

  y-coordinate of destination point.

`src_x`

  x-coordinate of source point.

`src_y`

  y-coordinate of source point.

`dst_width`

  Destination width.

`dst_height`

  Destination height.

`src_width`

  Source width.

`src_height`

  Source height.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst_image` and `src_image` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 Resizing an image

This example will display the image at half size.

`<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
?>`

The above example will output something similar to:

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

### Notes

> Note:

> There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

### See Also

- imagecopyresampled() - Copy and resize part of an image with resampling
- imagescale() - Scale an image using the given new width and height
- imagecrop() - Crop an image to the given rectangle

# imagecreate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreate — Create a new palette based image

### Description

imagecreate(int `$width`, int `$height`): GdImage|false

imagecreate() returns an image identifier representing a blank image of specified size.

In general, we recommend the use of imagecreatetruecolor() instead of imagecreate() so that image processing occurs on the highest quality image possible. If you want to output a palette image, then imagetruecolortopalette() should be called immediately before saving the image with imagepng() or imagegif().

### Parameters

`width`

  The image width.

`height`

  The image height.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Creating a new GD image stream and outputting an image.

`<?php
header("Content-Type: image/png");
$im = @imagecreate(110, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagecreatetruecolor() - Create a new true color image

# imagecreatefromavif

(PHP 8 >= 8.1.0)

imagecreatefromavif — Create a new image from file or URL

### Description

imagecreatefromavif(string `$filename`): GdImage|false

imagecreatefromavif() returns an image object representing the image obtained from the given filename.

### Parameters

`filename`

  Path to the AVIF raster image.

### Return Values

Returns an image object on success, `false` on errors.

# imagecreatefrombmp

(PHP 7 >= 7.2.0, PHP 8)

imagecreatefrombmp — Create a new image from file or URL

### Description

imagecreatefrombmp(string `$filename`): GdImage|false

imagecreatefrombmp() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the BMP image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Convert an BMP image to a PNG image using imagecreatefrombmp()

`<?php
// Load the BMP file
$im = imagecreatefrombmp('./example.bmp');
// Convert it to a PNG file with default settings
imagepng($im, './example.png');
?>`

# imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd — Create a new image from GD file or URL

### Description

imagecreatefromgd(string `$filename`): GdImage|false

Create a new image from GD file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the GD file.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 imagecreatefromgd() example

`<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');
// Test if the image was loaded
if(!$im)
{
die('Unable to load gd image!');
}
// Do image operations here
// Save the image
imagegd($im, './test_updated.gd');
?>`

### Notes

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

# imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd2 — Create a new image from GD2 file or URL

### Description

imagecreatefromgd2(string `$filename`): GdImage|false

Create a new image from GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the GD2 image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 imagecreatefromgd2() example

`<?php
// Load the gd2 image
$im = imagecreatefromgd2('./test.gd2');
// Apply an effect on the image, in this
// case negate the image
if(function_exists('imagefilter'))
{
imagefilter($im, IMG_FILTER_NEGATE);
}
// Save the image
imagegd2($im, './test_updated.gd2');
?>`

### Notes

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

# imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL

### Description

imagecreatefromgd2part(
string `$filename`,
int `$x`,
int `$y`,
int `$width`,
int `$height`
): GdImage|false

Create a new image from a given part of GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the GD2 image.

`x`

  x-coordinate of source point.

`y`

  y-coordinate of source point.

`width`

  Source width.

`height`

  Source height.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 imagecreatefromgd2part() example

`<?php
// For this example we need the image size before
$image = getimagesize('./test.gd2');
// Create the image instance now we got the image
// sizes
$im = imagecreatefromgd2part('./test.gd2', 4, 4, ($image[0] / 2) - 6, ($image[1] / 2) - 6);
// Do an image operation, in this case we emboss the image
if(function_exists('imagefilter'))
{
imagefilter($im, IMG_FILTER_EMBOSS);
}
// Save optimized image
imagegd2($im, './test_emboss.gd2');
?>`

### Notes

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

# imagecreatefromgif

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromgif — Create a new image from file or URL

### Description

imagecreatefromgif(string `$filename`): GdImage|false

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

Caution

When reading GIF files into memory, only the first frame is returned in the image object. The size of the image is not necessarily what is reported by getimagesize().

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the GIF image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Example to handle an error during loading of a GIF

`<?php
function LoadGif($imgname)
{
/* Attempt to open */
$im = @imagecreatefromgif($imgname);
/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor (150, 30);
$bgc = imagecolorallocate ($im, 255, 255, 255);
$tc = imagecolorallocate ($im, 0, 0, 0);
imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/gif');
$img = LoadGif('bogus.image');
imagegif($img);
?>`

The above example will output something similar to:

# imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromjpeg — Create a new image from file or URL

### Description

imagecreatefromjpeg(string `$filename`): GdImage|false

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the JPEG image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Example to handle an error during loading of a JPEG

`<?php
function LoadJpeg($imgname)
{
/* Attempt to open */
$im = @imagecreatefromjpeg($imgname);
/* See if it failed */
if(!$im)
{
/* Create a black image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/jpeg');
$img = LoadJpeg('bogus.image');
imagejpeg($img);
?>`

The above example will output something similar to:

# imagecreatefrompng

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefrompng — Create a new image from file or URL

### Description

imagecreatefrompng(string `$filename`): GdImage|false

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the PNG image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Example to handle an error during loading of a PNG

`<?php
function LoadPNG($imgname)
{
/* Attempt to open */
$im = @imagecreatefrompng($imgname);
/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/png');
$img = LoadPNG('bogus.image');
imagepng($img);
?>`

The above example will output something similar to:

# imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

imagecreatefromstring — Create a new image from the image stream in the string

### Description

imagecreatefromstring(string `$data`): GdImage|false

imagecreatefromstring() returns an image identifier representing the image obtained from the given `data`. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, GD2, WEBP and AVIF.

### Parameters

`data`

  A string containing the image data.

### Return Values

An image object will be returned on success. `false` is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

### Errors/Exceptions

imagecreatefromstring() raises an E_WARNING level error, if the data is not in a recognized format.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
7.3.0 | WEBP is supported now (if supported by the libgd in use).

### Examples

Example #1 imagecreatefromstring() example

`<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
}
else {
echo 'An error occurred.';
}
?>`

The above example will output something similar to:

### See Also

- imagecreatefromjpeg() - Create a new image from file or URL
- imagecreatefrompng() - Create a new image from file or URL
- imagecreatefromgif() - Create a new image from file or URL
- imagecreatetruecolor() - Create a new true color image

# imagecreatefromtga

(PHP 7 >= 7.4.0, PHP 8)

imagecreatefromtga — Create a new image from file or URL

### Description

imagecreatefromtga(string `$filename`): GdImage|false

imagecreatefromtga() returns an image object representing the image obtained from the given filename.

### Parameters

`filename`

  Path to the Truevision TGA image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

# imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromwbmp — Create a new image from file or URL

### Description

imagecreatefromwbmp(string `$filename`): GdImage|false

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

> Note: WBMP images are Wireless Bitmaps, not Windows Bitmaps. The latter can be loaded with imagecreatefrombmp().

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the WBMP image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Example to handle an error during loading of a WBMP

`<?php
function LoadWBMP($imgname)
{
/* Attempt to open */
$im = @imagecreatefromwbmp($imgname);
/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/vnd.wap.wbmp');
$img = LoadWBMP('bogus.image');
imagewbmp($img);
?>`

# imagecreatefromwebp

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

imagecreatefromwebp — Create a new image from file or URL

### Description

imagecreatefromwebp(string `$filename`): GdImage|false

imagecreatefromwebp() returns an image identifier representing the image obtained from the given filename. Note that animated WebP files cannot be read.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the WebP image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Convert an WebP image to a jpeg image using imagecreatefromwebp()

`<?php
// Load the WebP file
$im = imagecreatefromwebp('./example.webp');
// Convert it to a jpeg file with 100% quality
imagejpeg($im, './example.jpeg', 100);
?>`

# imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromxbm — Create a new image from file or URL

### Description

imagecreatefromxbm(string `$filename`): GdImage|false

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the XBM image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Convert an XBM image to a png image using imagecreatefromxbm()

`<?php
// Load the xbm file
$xbm = imagecreatefromxbm('./example.xbm');
// Convert it to a png file
imagepng($xbm, './example.png');
?>`

# imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromxpm — Create a new image from file or URL

### Description

imagecreatefromxpm(string `$filename`): GdImage|false

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

### Parameters

`filename`

  Path to the XPM image.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Creating an image instance using imagecreatefromxpm()

`<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
die('Support for xpm was not found!');
}
// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');
// Do image operations here
// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
?>`

# imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecreatetruecolor — Create a new true color image

### Description

imagecreatetruecolor(int `$width`, int `$height`): GdImage|false

imagecreatetruecolor() returns an image object representing a black image of the specified size.

### Parameters

`width`

  Image width.

`height`

  Image height.

### Return Values

Returns an image object on success, `false` on errors.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 Creating a new GD image stream and outputting an image.

`<?php
header ('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20)
or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagecreate() - Create a new palette based image

# imagecrop

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagecrop — Crop an image to the given rectangle

### Description

imagecrop(GdImage `$image`, array `$rectangle`): GdImage|false

Crops an image to the given rectangular area and returns the resulting image. The given `image` is not modified.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`rectangle`

  The cropping rectangle as array with keys `x`, `y`, `width` and `height`.

### Return Values

Return cropped image object on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 imagecrop() example

This example shows how to crop an image to a square area.

`<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
imagepng($im2, 'example-cropped.png');
}
?>`

### See Also

- imagecropauto() - Crop an image automatically using one of the available modes

# imagecropauto

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagecropauto — Crop an image automatically using one of the available modes

### Description

imagecropauto(
GdImage `$image`,
int `$mode` = `IMG_CROP_DEFAULT`,
float `$threshold` = 0.5,
int `$color` = -1
): GdImage|false

Automatically crops an image according to the given `mode`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`mode`

  One of the following constants:

  `IMG_CROP_DEFAULT`
    Same as `IMG_CROP_TRANSPARENT`. Before PHP 7.4.0, the bundled libgd fell back to `IMG_CROP_SIDES`, if the image had no transparent color.
  `IMG_CROP_TRANSPARENT`
    Crops out a transparent background.
  `IMG_CROP_BLACK`
    Crops out a black background.
  `IMG_CROP_WHITE`
    Crops out a white background.
  `IMG_CROP_SIDES`
    Uses the 4 corners of the image to attempt to detect the background to crop.
  `IMG_CROP_THRESHOLD`
    Crops an image using the given `threshold` and `color`.
`threshold`

  Specifies the tolerance in percent to be used while comparing the image color and the color to crop. The method used to calculate the color difference is based on the color distance in the RGB(a) cube.

  Used only in `IMG_CROP_THRESHOLD` mode.

  > Note: Before PHP 7.4.0, the bundled libgd used a somewhat different algorithm, so the same `threshold` yielded different results for system and bundled libgd.

`color`

  Either an RGB color value or a palette index.

  Used only in `IMG_CROP_THRESHOLD` mode.

### Return Values

Returns a cropped image object on success or `false` on failure. `false` is also returned if the whole image was cropped.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
7.4.0 | The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd: `IMG_CROP_DEFAULT` no longer falls back to `IMG_CROP_SIDES` and threshold-cropping now uses the same algorithm as system libgd.
7.4.0 | The default value of `mode` has been changed to `IMG_CROP_AUTO`. Formerly, the default value has been `-1` which corresponds to `IMG_CROP_DEFAULT`, but passing `-1` is now deprecated.

### Examples

Example #1 Proper handling of auto-cropping

As noted in the return value section, imagecropauto() returns `false` if the whole image was cropped. In this example we have an image object `$im` which should be automatically cropped only if there is something to crop; otherwise we want to proceed with the original image.

`<?php
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image object was returned
$im = $cropped; // assign the cropped image to $im
}
?>`

### See Also

- imagecrop() - Crop an image to the given rectangle

# imagedashedline

(PHP 4, PHP 5, PHP 7, PHP 8)

imagedashedline — Draw a dashed line

### Description

imagedashedline(
GdImage `$image`,
int `$x1`,
int `$y1`,
int `$x2`,
int `$y2`,
int `$color`
): true

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x1`

  Upper left x coordinate.

`y1`

  Upper left y coordinate 0, 0 is the top left corner of the image.

`x2`

  Bottom right x coordinate.

`y2`

  Bottom right y coordinate.

`color`

  The fill color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagedashedline() example

`<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
// Draw a vertical dashed line
imagedashedline($im, 50, 25, 50, 75, $white);
// Save the image
imagepng($im, './dashedline.png');
?>`

The above example will output something similar to:

Example #2 Alternative to imagedashedline()

`<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
// Define our style: First 4 pixels is white and the
// next 4 is transparent. This creates the dashed line effect
$style = Array(
$white,
$white,
$white,
$white,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT
);
imagesetstyle($im, $style);
// Draw the dashed line
imageline($im, 50, 25, 50, 75, IMG_COLOR_STYLED);
// Save the image
imagepng($im, './imageline.png');
?>`

### See Also

- imagesetstyle() - Set the style for line drawing
- imageline() - Draw a line

# imagedestroy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagedestroy — Destroy an image

Warning

This function has been DEPRECATED as of PHP 8.5.0. Relying on this function is highly discouraged.

### Description

#[\Deprecated]
imagedestroy(GdImage `$image`): true

> Note:

> This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.

Prior to PHP 8.0.0, imagedestroy() freed any memory associated with the `image` resource. As of 8.0.0, the GD extension uses objects instead of resources, and objects cannot be explicitly closed.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.5.0 | This function has been deprecated.
8.0.0 | This function is a NOP now.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagedestroy() prior to PHP 8.0.0

`<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);
// alter or save the image
// frees image from memory
imagedestroy($im);
?>`

# imageellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imageellipse — Draw an ellipse

### Description

imageellipse(
GdImage `$image`,
int `$center_x`,
int `$center_y`,
int `$width`,
int `$height`,
int `$color`
): true

Draws an ellipse centered at the specified coordinates.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`center_x`

  x-coordinate of the center.

`center_y`

  y-coordinate of the center.

`width`

  The ellipse width.

`height`

  The ellipse height.

`color`

  The color of the ellipse. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imageellipse() example

`<?php
// Create a blank image.
$image = imagecreatetruecolor(400, 300);
// Select the background color.
$bg = imagecolorallocate($image, 0, 0, 0);
// Fill the background with the color selected above.
imagefill($image, 0, 0, $bg);
// Choose a color for the ellipse.
$col_ellipse = imagecolorallocate($image, 255, 255, 255);
// Draw the ellipse.
imageellipse($image, 200, 150, 300, 200, $col_ellipse);
// Output the image.
header("Content-type: image/png");
imagepng($image);
?>`

The above example will output something similar to:

### Notes

> Note:

> imageellipse() ignores imagesetthickness().

### See Also

- imagefilledellipse() - Draw a filled ellipse
- imagearc() - Draws an arc

# imagefill

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefill — Flood fill

### Description

imagefill(
GdImage `$image`,
int `$x`,
int `$y`,
int `$color`
): true

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given `color` in the `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x`

  x-coordinate of start point.

`y`

  y-coordinate of start point.

`color`

  The fill color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagefill() example

`<?php
$im = imagecreatetruecolor(100, 100);
// sets background to red
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagecolorallocate() - Allocate a color for an image

# imagefilledarc

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagefilledarc — Draw a partial arc and fill it

### Description

imagefilledarc(
GdImage `$image`,
int `$center_x`,
int `$center_y`,
int `$width`,
int `$height`,
int `$start_angle`,
int `$end_angle`,
int `$color`,
int `$style`
): true

Draws a partial arc centered at the specified coordinate in the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`center_x`

  x-coordinate of the center.

`center_y`

  y-coordinate of the center.

`width`

  The arc width.

`height`

  The arc height.

`start_angle`

  The arc start angle, in degrees.

`end_angle`

  The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

`color`

  A color identifier created with imagecolorallocate().

`style`

  A bitwise OR of the following possibilities:

  1. `IMG_ARC_PIE`
  2. `IMG_ARC_CHORD`
  3. `IMG_ARC_NOFILL`
  4. `IMG_ARC_EDGED`
  `IMG_ARC_PIE` and `IMG_ARC_CHORD` are mutually exclusive; `IMG_ARC_CHORD` just connects the starting and ending angles with a straight line, while `IMG_ARC_PIE` produces a rounded edge. `IMG_ARC_NOFILL` indicates that the arc or chord should be outlined, not filled. `IMG_ARC_EDGED`, used together with `IMG_ARC_NOFILL`, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Creating a 3D looking pie

`<?php
// create image
$image = imagecreatetruecolor(100, 100);
// allocate some colors
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred = imagecolorallocate($image, 0x90, 0x00, 0x00);
// make the 3D effect
for ($i = 60; $i > 50; $i--) {
imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}
imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);
// flush image
header('Content-type: image/png');
imagepng($image);
?>`

The above example will output something similar to:

# imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagefilledellipse — Draw a filled ellipse

### Description

imagefilledellipse(
GdImage `$image`,
int `$center_x`,
int `$center_y`,
int `$width`,
int `$height`,
int `$color`
): true

Draws an ellipse centered at the specified coordinate on the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`center_x`

  x-coordinate of the center.

`center_y`

  y-coordinate of the center.

`width`

  The ellipse width.

`height`

  The ellipse height.

`color`

  The fill color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagefilledellipse() example

`<?php
// create a blank image
$image = imagecreatetruecolor(400, 300);
// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);
// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);
// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);
// output the picture
header("Content-type: image/png");
imagepng($image);
?>`

The above example will output something similar to:

### Notes

> Note:

> imagefilledellipse() ignores imagesetthickness().

### See Also

- imageellipse() - Draw an ellipse
- imagefilledarc() - Draw a partial arc and fill it

# imagefilledpolygon

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilledpolygon — Draw a filled polygon

### Description

Signature as of PHP 8.0.0 (not supported with named arguments)

imagefilledpolygon(GdImage `$image`, array `$points`, int `$color`): bool

Alternative signature (deprecated as of PHP 8.1.0)

imagefilledpolygon(
GdImage `$image`,
array `$points`,
int `$num_points`,
int `$color`
): bool

imagefilledpolygon() creates a filled polygon in the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`points`

  An array containing the `x` and `y` coordinates of the polygons vertices consecutively.

`num_points`

  Total number of points (vertices), which must be at least 3.

  If this parameter is omitted as per the second signature, `points` must have an even number of elements, and `num_points` is assumed to be `count($points)/2`.
`color`

  A color identifier created with imagecolorallocate().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The parameter `num_points` has been deprecated.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagefilledpolygon() example

`<?php
// set up array of points for polygon
$values = array(
40, 50, // Point 1 (x, y)
20, 240, // Point 2 (x, y)
60, 60, // Point 3 (x, y)
240, 20, // Point 4 (x, y)
50, 40, // Point 5 (x, y)
10, 10 // Point 6 (x, y)
);
// create image
$image = imagecreatetruecolor(250, 250);
// allocate colors
$bg = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);
// fill the background
imagefilledrectangle($image, 0, 0, 249, 249, $bg);
// draw a polygon
imagefilledpolygon($image, $values, $blue);
// flush image
header('Content-type: image/png');
imagepng($image);
?>`

The above example will output something similar to:

### See Also

- imagepolygon() - Draws a polygon

# imagefilledrectangle

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilledrectangle — Draw a filled rectangle

### Description

imagefilledrectangle(
GdImage `$image`,
int `$x1`,
int `$y1`,
int `$x2`,
int `$y2`,
int `$color`
): true

Creates a rectangle filled with `color` in the given `image` starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x1`

  x-coordinate for point 1.

`y1`

  y-coordinate for point 1.

`x2`

  x-coordinate for point 2.

`y2`

  y-coordinate for point 2.

`color`

  The fill color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagefilledrectangle() usage

`<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);
// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);
// Save the image
imagepng($im, './imagefilledrectangle.png');
?>`

The above example will output something similar to:

# imagefilltoborder

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilltoborder — Flood fill to specific color

### Description

imagefilltoborder(
GdImage `$image`,
int `$x`,
int `$y`,
int `$border_color`,
int `$color`
): true

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

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x`

  x-coordinate of start.

`y`

  y-coordinate of start.

`border_color`

  The border color. A color identifier created with imagecolorallocate().

`color`

  The fill color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Filling an ellipse with a color

`<?php
// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));
// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));
// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);
// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);
// Output
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

### Notes

The algorithm does not explicitly remember which pixels have already been set, but rather infers that from the color of the pixel, so it cannot distinguish between freshly set pixels and pixels that are already there. That means chosing any fill color that is already used in the image may yield undesired results.

# imagefilter

(PHP 5, PHP 7, PHP 8)

imagefilter — Applies a filter to an image

### Description

imagefilter(GdImage `$image`, int `$filter`, array|int|float|bool `...$args`): bool

imagefilter() applies the given filter `filter` on the `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`filter`

  `filter` can be one of the following:

  - `IMG_FILTER_NEGATE`: Reverses all colors of the image.
  - `IMG_FILTER_GRAYSCALE`: Converts the image into grayscale by changing the red, green and blue components to their weighted sum using the same coefficients as the REC.601 luma (Y') calculation. The alpha components are retained. For palette images the result may differ due to palette limitations.
  - `IMG_FILTER_BRIGHTNESS`: Changes the brightness of the image. Use `args` to set the level of brightness. The range for the brightness is -255 to 255.
  - `IMG_FILTER_CONTRAST`: Changes the contrast of the image. Use `args` to set the level of contrast.
  - `IMG_FILTER_COLORIZE`: Like `IMG_FILTER_GRAYSCALE`, except you can specify the color. Use `args`, `arg2` and `arg3` in the form of `red`, `green`, `blue` and `arg4` for the `alpha` channel. The range for each color is 0 to 255.
  - `IMG_FILTER_EDGEDETECT`: Uses edge detection to highlight the edges in the image.
  - `IMG_FILTER_EMBOSS`: Embosses the image.
  - `IMG_FILTER_GAUSSIAN_BLUR`: Blurs the image using the Gaussian method.
  - `IMG_FILTER_SELECTIVE_BLUR`: Blurs the image.
  - `IMG_FILTER_MEAN_REMOVAL`: Uses mean removal to achieve a "sketchy" effect.
  - `IMG_FILTER_SMOOTH`: Makes the image smoother. Use `args` to set the level of smoothness.
  - `IMG_FILTER_PIXELATE`: Applies pixelation effect to the image, use `args` to set the block size and `arg2` to set the pixelation effect mode.
  - `IMG_FILTER_SCATTER`: Applies scatter effect to the image, use `args` and `arg2` to define the effect strength and additionally `arg3` to only apply the on select pixel colors.
`args`

  - `IMG_FILTER_BRIGHTNESS`: Brightness level.
  - `IMG_FILTER_CONTRAST`: Contrast level.
  - `IMG_FILTER_COLORIZE`: Value of red component.
  - `IMG_FILTER_SMOOTH`: Smoothness level.
  - `IMG_FILTER_PIXELATE`: Block size in pixels.
  - `IMG_FILTER_SCATTER`: Effect substraction level. This must not be higher or equal to the addition level set with `arg2`.
`arg2`

  - `IMG_FILTER_COLORIZE`: Value of green component.
  - `IMG_FILTER_PIXELATE`: Whether to use advanced pixelation effect or not (defaults to `false`).
  - `IMG_FILTER_SCATTER`: Effect addition level.
`arg3`

  - `IMG_FILTER_COLORIZE`: Value of blue component.
  - `IMG_FILTER_SCATTER`: Optional array indexed color values to apply effect at.
`arg4`

  - `IMG_FILTER_COLORIZE`: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws a ValueError if `sub` or `plus` would cause over-/underflow with the `IMG_FILTER_SCATTER` `filter`.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `sub` or `plus` would cause over-/underflow with the `IMG_FILTER_SCATTER` `filter`.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
7.4.0 | Scatter support (`IMG_FILTER_SCATTER`) was added.

### Examples

Example #1 imagefilter() grayscale example

`<?php
$im = imagecreatefrompng('dave.png');
if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
echo 'Image converted to grayscale.';
imagepng($im, 'dave.png');
}
else
{
echo 'Conversion to grayscale failed.';
}
?>`

Example #2 imagefilter() brightness example

`<?php
$im = imagecreatefrompng('sean.png');
if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
echo 'Image brightness changed.';
imagepng($im, 'sean.png');
}
else
{
echo 'Image brightness change failed.';
}
?>`

Example #3 imagefilter() colorize example

`<?php
$im = imagecreatefrompng('philip.png');
/* R, G, B, so 0, 255, 0 is green */
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0))
{
echo 'Image successfully shaded green.';
imagepng($im, 'philip.png');
}
else
{
echo 'Green shading failed.';
}
?>`

Example #4 imagefilter() negate example

`<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
if(function_exists('imagefilter'))
{
return imagefilter($im, IMG_FILTER_NEGATE);
}
for($x = 0; $x < imagesx($im); ++$x)
{
for($y = 0; $y < imagesy($im); ++$y)
{
$index = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($index);
$color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);
imagesetpixel($im, $x, $y, $color);
}
}
return(true);
}
$im = imagecreatefromjpeg('kalle.jpg');
if($im && negate($im))
{
echo 'Image successfully converted to negative colors.';
imagejpeg($im, 'kalle.jpg', 100);
}
else
{
echo 'Converting to negative colors failed.';
}
?>`

Example #5 imagefilter() pixelate example

`<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');
// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));
// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);
// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
// Output the differences
header('Content-Type: image/png');
imagepng($output);
?>`

The above example will output something similar to:

Example #6 imagefilter() scatter example

`<?php
// Load the image
$logo = imagecreatefrompng('./php.png');
// Apply a very soft scatter effect to the image
imagefilter($logo, IMG_FILTER_SCATTER, 3, 5);
// Output the image with the scatter effect
header('Content-Type: image/png');
imagepng($logo);
?>`

The above example will output something similar to:

### Notes

> Note: The result of `IMG_FILTER_SCATTER` is always random.

### See Also

- imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

# imageflip

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageflip — Flips an image using a given mode

### Description

imageflip(GdImage `$image`, int `$mode`): true

Flips the `image` image using the given `mode`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`mode`

  Flip mode, this can be one of the `IMG_FLIP_*` constants:

  Constant | Meaning
  --- | ---
  `IMG_FLIP_HORIZONTAL` | Flips the image horizontally.
  `IMG_FLIP_VERTICAL` | Flips the image vertically.
  `IMG_FLIP_BOTH` | Flips the image both horizontally and vertically.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Flips an image vertically

This example uses the `IMG_FLIP_VERTICAL` constant.

`<?php
// File
$filename = 'phplogo.png';
// Content type
header('Content-type: image/png');
// Load
$im = imagecreatefrompng($filename);
// Flip it vertically
imageflip($im, IMG_FLIP_VERTICAL);
// Output
imagejpeg($im);
?>`

The above example will output something similar to:

Example #2 Flips the image horizontally

This example uses the `IMG_FLIP_HORIZONTAL` constant.

`<?php
// File
$filename = 'phplogo.png';
// Content type
header('Content-type: image/png');
// Load
$im = imagecreatefrompng($filename);
// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);
// Output
imagejpeg($im);
?>`

The above example will output something similar to:

# imagefontheight

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefontheight — Get font height

### Description

imagefontheight(GdFont|int `$font`): int

Returns the pixel height of a character in the specified font.

### Parameters

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

### Return Values

Returns the pixel height of the font.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.

### Examples

Example #1 Using imagefontheight() on built-in fonts

`<?php
echo 'Font height: ' . imagefontheight(4);
?>`

The above example will output something similar to:

    Font height: 16

Example #2 Using imagefontheight() together with imageloadfont()

`<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');
echo 'Font height: ' . imagefontheight($font);
?>`

The above example will output something similar to:

    Font height: 43

### See Also

- imagefontwidth() - Get font width
- imageloadfont() - Load a new font

# imagefontwidth

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefontwidth — Get font width

### Description

imagefontwidth(GdFont|int `$font`): int

Returns the pixel width of a character in font.

### Parameters

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

### Return Values

Returns the pixel width of the font.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.

### Examples

Example #1 Using imagefontwidth() on built-in fonts

`<?php
echo 'Font width: ' . imagefontwidth(4);
?>`

The above example will output something similar to:

    Font width: 8

Example #2 Using imagefontwidth() together with imageloadfont()

`<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');
echo 'Font width: ' . imagefontwidth($font);
?>`

The above example will output something similar to:

    Font width: 23

### See Also

- imagefontheight() - Get font height
- imageloadfont() - Load a new font

# imageftbbox

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imageftbbox — Give the bounding box of a text using fonts via freetype2

### Description

imageftbbox(
float `$size`,
float `$angle`,
string `$font_filename`,
string `$string`,
array `$options` = []
): array|false

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

> Note:

> Prior to PHP 8.0.0, imageftbbox() was an extended variant of imagettfbbox() which additionally supported the `options`. As of PHP 8.0.0, imagettfbbox() is an alias of imageftbbox().

### Parameters

`size`

  The font size in points.

`angle`

  Angle in degrees in which `string` will be measured.

`font_filename`

  The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

`string`

  The string to be measured.

`options`

  Possible array indexes for `options`
  Key | Type | Meaning
  --- | --- | ---
  `linespacing` | float | Defines drawing linespacing

### Return Values

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

0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the `angle`, so "upper left" means in the top left-hand corner seeing the text horizontally.

On failure, `false` is returned.

### Examples

Example #1 imageftbbox() example

`<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);
// Path to our font file
$font = './arial.ttf';
// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');
// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');
// Output to browser
header('Content-Type: image/png');
imagepng($im);
?>`

### Notes

> Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

### See Also

- imagefttext() - Write text to the image using fonts using FreeType 2
- imagettfbbox() - Give the bounding box of a text using TrueType fonts

# imagefttext

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagefttext — Write text to the image using fonts using FreeType 2

### Description

imagefttext(
GdImage `$image`,
float `$size`,
float `$angle`,
int `$x`,
int `$y`,
int `$color`,
string `$font_filename`,
string `$text`,
array `$options` = []
): array|false

> Note:

> Prior to PHP 8.0.0, imagefttext() was an extended variant of imagettftext() which additionally supported the `options`. As of PHP 8.0.0, imagettftext() is an alias of imagefttext().

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`size`

  The font size to use in points.

`angle`

  The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

`x`

  The coordinates given by `x` and `y` will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where `x` and `y` define the upper-left corner of the first character. For example, "top left" is 0, 0.

`y`

  The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

`color`

  The index of the desired color for the text, see imagecolorexact().

`font_filename`

  The path to the TrueType font you wish to use.

  Depending on which version of the GD library PHP is using, when `font_filename` does not begin with a leading `/` then `.ttf` will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

  In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

  `<?php
  // Set the environment variable for GD
  putenv('GDFONTPATH=' . realpath('.'));
  // Name the font to be used (note the lack of the .ttf extension)
  $font = 'SomeFont';
  ?>`
`text`

  Text to be inserted into image.

`options`

  Possible array indexes for `options`
  Key | Type | Meaning
  --- | --- | ---
  `linespacing` | float | Defines drawing linespacing

### Return Values

This function returns an array defining the four points of the box, starting in the lower left and moving counter-clockwise:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | lower right x-coordinate
3 | lower right y-coordinate
4 | upper right x-coordinate
5 | upper right y-coordinate
6 | upper left x-coordinate
7 | upper left y-coordinate

On failure, `false` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagefttext() example

`<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);
// Path to our ttf font file
$font_file = './arial.ttf';
// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');
// Output image to the browser
header('Content-Type: image/png');
imagepng($im);
?>`

### Notes

> Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

### See Also

- imageftbbox() - Give the bounding box of a text using fonts via freetype2
- imagettftext() - Write text to the image using TrueType fonts

# imagegammacorrect

(PHP 4, PHP 5, PHP 7, PHP 8)

imagegammacorrect — Apply a gamma correction to a GD image

### Description

imagegammacorrect(GdImage `$image`, float `$input_gamma`, float `$output_gamma`): true

Applies gamma correction to the given gd `image` given an input and an output gamma.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`input_gamma`

  The input gamma.

`output_gamma`

  The output gamma.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagegammacorrect() usage

`<?php
// Create image instance
$im = imagecreatefromgif('php.gif');
// Correct gamma, out = 1.537
imagegammacorrect($im, 1.0, 1.537);
// Save
imagegif($im, './php_gamma_corrected.gif');
?>`

# imagegd

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagegd — Output GD image to browser or file

### Description

imagegd(GdImage `$image`, ?string `$file` = `null`): bool

Outputs or saves the given `image` in GD format.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.3 | `file` is now nullable.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
7.2.0 | imagegd() now allows to output truecolor images. Formerly, these have been implicitly converted to palette.

### Examples

Example #1 Outputting a GD image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
// Output the image
imagegd($im);
?>`

Example #2 Saving a GD image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
// Save the gd image
// The file format for GD images is .gd, see http://www.libgd.org/GdFileFormats
imagegd($im, 'simple.gd');
?>`

### Notes

> Note:

> The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

### See Also

- imagegd2() - Output GD2 image to browser or file

# imagegd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagegd2 — Output GD2 image to browser or file

### Description

imagegd2(
GdImage `$image`,
?string `$file` = `null`,
int `$chunk_size` = 128,
int `$mode` = `IMG_GD2_RAW`
): bool

Outputs or saves the given `image` in GD2 format.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

`chunk_size`

  Chunk size.

`mode`

  Either `IMG_GD2_RAW` or `IMG_GD2_COMPRESSED`. Default is `IMG_GD2_RAW`.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.3 | `file` is now nullable.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Outputting a GD2 image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
// Output the image
imagegd2($im);
?>`

Example #2 Saving a GD2 image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
// Save the gd2 image
// The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');
?>`

### Notes

> Note:

> The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

### See Also

- imagegd() - Output GD image to browser or file

# imagegetclip

(PHP 7 >= 7.2.0, PHP 8)

imagegetclip — Get the clipping rectangle

### Description

imagegetclip(GdImage `$image`): array

imagegetclip() retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

The function returns an indexed array with the coordinates of the clipping rectangle which has the following entries:

- x-coordinate of the upper left corner
- y-coordinate of the upper left corner
- x-coordinate of the lower right corner
- y-coordinate of the lower right corner

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagegetclip() example

Setting and retrieving the clipping rectangle.

`<?php
$im = imagecreate(100, 100);
imagesetclip($im, 10,10, 89,89);
print_r(imagegetclip($im));`

The above example will output:

    Array
    (
        [0] => 10
        [1] => 10
        [2] => 89
        [3] => 89
    )

### See Also

- imagesetclip() - Set the clipping rectangle

# imagegetinterpolation

(PHP 8)

imagegetinterpolation — Get the interpolation method

### Description

imagegetinterpolation(GdImage `$image`): int

Gets the currently set interpolation method of the `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Returns the interpolation method.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### See Also

- imagesetinterpolation() - Set the interpolation method

# imagegif

(PHP 4, PHP 5, PHP 7, PHP 8)

imagegif — Output image to browser or file

### Description

imagegif(GdImage `$image`, resource|string|null `$file` = `null`): bool

imagegif() creates the GIF file in `file` from the image `image`. The `image` argument is the return from the imagecreate() or `imagecreatefrom*` function.

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

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Outputting an image using imagegif()

`<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);
// Make the background white
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);
// Draw a text string on the image
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);
// Output the image to browser
header('Content-Type: image/gif');
imagegif($im);
?>`

Example #2 Converting a PNG image to GIF using imagegif()

`<?php
// Load the PNG
$png = imagecreatefrompng('./php.png');
// Save the image as a GIF
imagegif($png, './php.gif');
// We're done
echo 'Converted PNG image to GIF with success!';
?>`

### Notes

> Note:

> The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence `header ("Content-Type: image/gif"); imagegif ($im);` by the more flexible sequence:

> `<?php
> // Create a new image instance
> $im = imagecreatetruecolor(100, 100);
> // Do some image operations here
> // Handle output
> if(function_exists('imagegif'))
> {
> // For GIF
> header('Content-Type: image/gif');
> imagegif($im);
> }
> elseif(function_exists('imagejpeg'))
> {
> // For JPEG
> header('Content-Type: image/jpeg');
> imagejpeg($im, NULL, 100);
> }
> elseif(function_exists('imagepng'))
> {
> // For PNG
> header('Content-Type: image/png');
> imagepng($im);
> }
> elseif(function_exists('imagewbmp'))
> {
> // For WBMP
> header('Content-Type: image/vnd.wap.wbmp');
> imagewbmp($im);
> }
> else
> {
> die('No image support in this PHP server');
> }
> ?>`

> Note:

> You can use the function imagetypes() for checking the presence of the various supported image formats:

> `<?php
> if(imagetypes() & IMG_GIF)
> {
> header('Content-Type: image/gif');
> imagegif($im);
> }
> elseif(imagetypes() & IMG_JPG)
> {
> /* ... etc. */
> }
> ?>`

### See Also

- imagepng() - Output a PNG image to either the browser or a file
- imagewbmp() - Output image to browser or file
- imagejpeg() - Output image to browser or file
- imagetypes() - Return the image types supported by this PHP build

# imagegrabscreen

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

imagegrabscreen — Captures the whole screen

### Description

imagegrabscreen(): GdImage|false

Grabs a screenshot of the whole screen.

> Note:

> This function is only available on Windows.

### Parameters

This function has no parameters.

### Return Values

Returns an image object on success, `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

### Examples

Example #1 imagegrabscreen() example

This example demonstrates how to take a screenshot of the current screen and save it as a png image.

`<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
?>`

### See Also

- imagegrabwindow() - Captures a window

# imagegrabwindow

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

imagegrabwindow — Captures a window

### Description

imagegrabwindow(int `$handle`, bool `$client_area` = `false`): GdImage|false

Grabs a window or its client area using a windows handle (HWND property in COM instance)

> Note:

> This function is only available on Windows.

### Parameters

`handle`

  The HWND window ID.

`client_area`

  Include the client area of the application window.

### Return Values

Returns an image object on success, `false` on failure.

### Errors/Exceptions

E_NOTICE is issued if `handle` is invalid window handle. E_WARNING is issued if the Windows API is too old.

### Changelog

Version | Description
--- | ---
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
8.0.0 | `client_area` expects a bool now; previously it expected an int.

### Examples

Example #1 imagegrabwindow() example

Capture a window (IE for example)

`<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
?>`

Capture a window (IE for example) but with its content

`<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://www.libgd.org");
/* Still working? */
while ($browser->Busy) {
com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
?>`

### See Also

- imagegrabscreen() - Captures the whole screen

# imageinterlace

(PHP 4, PHP 5, PHP 7, PHP 8)

imageinterlace — Enable or disable interlace

### Description

imageinterlace(GdImage `$image`, ?bool `$enable` = `null`): bool

imageinterlace() turns the interlace bit on or off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`enable`

  If `true`, the image will be interlaced, if `false` the interlace bit is turned off. Passing `null` will result in the interlacing behavior not being changed.

### Return Values

Returns `true` if the interlace bit is set for the image, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.0.5 | imageinterlace() returns a bool now; previously it returned an int (non-zero for interlaced images, zero otherwise).
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | `enable` expects a bool now; previously it expected an int.

### Examples

Example #1 Turn on interlacing using imageinterlace()

`<?php
// Create an image instance
$im = imagecreatefromgif('php.gif');
// Enable interlancing
imageinterlace($im, true);
// Save the interlaced image
imagegif($im, './php_interlaced.gif');
?>`

# imageistruecolor

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imageistruecolor — Finds whether an image is a truecolor image

### Description

imageistruecolor(GdImage `$image`): bool

imageistruecolor() finds whether the image `image` is a truecolor image.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Returns `true` if the `image` is truecolor, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Simple detection of true color image instances using imageistruecolor()

`<?php
// $im is an image instance
// Check if image is a true color image or not
if(!imageistruecolor($im))
{
// Create a new true color image instance
$tc = imagecreatetruecolor(imagesx($im), imagesy($im));
// Copy over the pixels
imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
$im = $tc;
$tc = NULL;
// OR use imagepalettetotruecolor()
}
// Continue working with image instance
?>`

### See Also

- imagecreatetruecolor() - Create a new true color image
- imagepalettetotruecolor() - Converts a palette based image to true color

# imagejpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagejpeg — Output image to browser or file

### Description

imagejpeg(GdImage `$image`, resource|string|null `$file` = `null`, int `$quality` = -1): bool

imagejpeg() creates a JPEG file from the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

`quality`

  `quality` is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default (`-1`) uses the default IJG quality value (about 75).

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Errors/Exceptions

Throws a ValueError if `quality` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `quality` is invalid.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Outputting a JPEG image to the browser

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($im);
?>`

The above example will output something similar to:

Example #2 Saving a JPEG image to a file

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');
?>`

Example #3 Outputting the image at 75% quality to the browser

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Skip the file parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);
?>`

### Notes

> Note:

> If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

### See Also

- imagepng() - Output a PNG image to either the browser or a file
- imagegif() - Output image to browser or file
- imagewbmp() - Output image to browser or file
- imageinterlace() - Enable or disable interlace
- imagetypes() - Return the image types supported by this PHP build

# imagelayereffect

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagelayereffect — Set the alpha blending flag to use layering effects

### Description

imagelayereffect(GdImage `$image`, int `$effect`): true

Set the alpha blending flag to use layering effects.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`effect`

  One of the following constants:

  `IMG_EFFECT_REPLACE`
    Use pixel replacement (equivalent of passing `true` to imagealphablending())
  `IMG_EFFECT_ALPHABLEND`
    Use normal pixel blending (equivalent of passing `false` to imagealphablending())
  `IMG_EFFECT_NORMAL`
    Same as `IMG_EFFECT_ALPHABLEND`.
  `IMG_EFFECT_OVERLAY`
    Overlay has the effect that black background pixels will remain black, white background pixels will remain white, but grey background pixels will take the colour of the foreground pixel.
  `IMG_EFFECT_MULTIPLY`
    Overlays with a multiply effect.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
7.2.0 | Added `IMG_EFFECT_MULTIPLY` (requires system libgd >= 2.1.1 or the bundled libgd).

### Examples

Example #1 imagelayereffect() example

`<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);
// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));
// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);
// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));
// Output
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

# imageline

(PHP 4, PHP 5, PHP 7, PHP 8)

imageline — Draw a line

### Description

imageline(
GdImage `$image`,
int `$x1`,
int `$y1`,
int `$x2`,
int `$y2`,
int `$color`
): true

Draws a line between the two given points.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x1`

  x-coordinate for first point.

`y1`

  y-coordinate for first point.

`x2`

  x-coordinate for second point.

`y2`

  y-coordinate for second point.

`color`

  The line color. A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Drawing a thick line

`<?php
function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
/* this way it works well only for orthogonal lines
imagesetthickness($image, $thick);
return imageline($image, $x1, $y1, $x2, $y2, $color);
*/
if ($thick == 1) {
return imageline($image, $x1, $y1, $x2, $y2, $color);
}
$t = $thick / 2 - 0.5;
if ($x1 == $x2 || $y1 == $y2) {
return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
}
$k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
$a = $t / sqrt(1 + pow($k, 2));
$points = array(
round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
);
imagefilledpolygon($image, $points, 4, $color);
return imagepolygon($image, $points, 4, $color);
}
?>`

### See Also

- imagecreatetruecolor() - Create a new true color image
- imagecolorallocate() - Allocate a color for an image

# imageloadfont

(PHP 4, PHP 5, PHP 7, PHP 8)

imageloadfont — Load a new font

### Description

imageloadfont(string `$filename`): GdFont|false

imageloadfont() loads a user-defined bitmap and returns its identifier.

### Parameters

`filename`

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

  Font file format
  byte position | C data type | description
  --- | --- | ---
  byte 0-3 | int | number of characters in the font
  byte 4-7 | int | value of first character in the font (often 32 for space)
  byte 8-11 | int | pixel width of each character
  byte 12-15 | int | pixel height of each character
  byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

### Return Values

Returns an GdFont instance, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an GdFont instance now; previously, an int was returned.

### Examples

Example #1 imageloadfont() usage example

`<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);
// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);
// Output to browser
header('Content-type: image/png');
imagepng($im);
?>`

### See Also

- imagefontwidth() - Get font width
- imagefontheight() - Get font height
- imagestring() - Draw a string horizontally

# imageopenpolygon

(PHP 7 >= 7.2.0, PHP 8)

imageopenpolygon — Draws an open polygon

### Description

Signature as of PHP 8.0.0 (not supported with named arguments)

imageopenpolygon(GdImage `$image`, array `$points`, int `$color`): bool

Alternative signature (deprecated as of PHP 8.1.0)

imageopenpolygon(
GdImage `$image`,
array `$points`,
int `$num_points`,
int `$color`
): bool

imageopenpolygon() draws an open polygon on the given `image`. Contrary to imagepolygon(), no line is drawn between the last and the first point.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`points`

  An array containing the polygon's vertices, e.g.:

  points[0] | = x0
  points[1] | = y0
  points[2] | = x1
  points[3] | = y1

`num_points`

  Total number of points (vertices), which must be at least 3.

  If this parameter is omitted as per the second signature, `points` must have an even number of elements, and `num_points` is assumed to be `count($points)/2`.
`color`

  A color identifier created with imagecolorallocate().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The parameter `num_points` has been deprecated.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imageopenpolygon() example

`<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);
// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);
// Draw the polygon
imageopenpolygon($image, array(
0, 0,
100, 200,
300, 200
),
$col_poly);
// Output the picture to the browser
header('Content-type: image/png');
imagepng($image);
?>`

The above example will output something similar to:

### See Also

- imagepolygon() - Draws a polygon

# imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagepalettecopy — Copy the palette from one image to another

### Description

imagepalettecopy(GdImage `$dst`, GdImage `$src`): void

imagepalettecopy() copies the palette from the `src` image to the `dst` image.

### Parameters

`dst`

  The destination image object.

`src`

  The source image object.

### Return Values

No value is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `dst` and `src` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 imagepalettecopy() example

`<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);
// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);
// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);
// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);
// Output image to the browser
header('Content-type: image/png');
imagepng($palette2);
?>`

# imagepalettetotruecolor

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagepalettetotruecolor — Converts a palette based image to true color

### Description

imagepalettetotruecolor(GdImage `$image`): bool

Converts a palette based image, created by functions like imagecreate() to a true color image, like imagecreatetruecolor().

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Returns `true` if the convertion was complete, or if the source image already is a true color image, otherwise `false` is returned.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Converts any image object to true color

`<?php
// Backwards compatiblity
if(!function_exists('imagepalettetotruecolor'))
{
function imagepalettetotruecolor(&$src)
{
if(imageistruecolor($src))
{
return(true);
}
$dst = imagecreatetruecolor(imagesx($src), imagesy($src));
imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
$src = $dst;
return(true);
}
}
// Helper closure
$typeof = function() use($im)
{
echo 'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL;
};
// Create a palette based image
$im = imagecreate(100, 100);
$typeof();
// Convert it to true color
imagepalettetotruecolor($im);
$typeof();
?>`

The above example will output:

    typeof($im) = palette
    typeof($im) = true color

### See Also

- imagecreatetruecolor() - Create a new true color image
- imageistruecolor() - Finds whether an image is a truecolor image

# imagepng

(PHP 4, PHP 5, PHP 7, PHP 8)

imagepng — Output a PNG image to either the browser or a file

### Description

imagepng(
GdImage `$image`,
resource|string|null `$file` = `null`,
int `$quality` = -1,
int `$filters` = -1
): bool

Outputs or saves a PNG image from the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

  > Note:

  > `null` is invalid if the `quality` and `filters` arguments are not used.

`quality`

  Compression level: from 0 (no compression) to 9. The default (`-1`) uses the zlib compression default. For more information see the » zlib manual.

`filters`

  Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the `PNG_FILTER_*` constants. `PNG_NO_FILTER` or `PNG_ALL_FILTERS` may also be used to respectively disable or activate all filters. The default value (`-1`) disables filtering.

  Caution

  The `filters` parameter is ignored by system libgd.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Errors/Exceptions

Throws a ValueError if `quality` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `quality` is invalid.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

`<?php
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im);
?>`

### See Also

- imagegif() - Output image to browser or file
- imagewbmp() - Output image to browser or file
- imagejpeg() - Output image to browser or file
- imagetypes() - Return the image types supported by this PHP build
- imagesavealpha() - Whether to retain full alpha channel information when saving images

# imagepolygon

(PHP 4, PHP 5, PHP 7, PHP 8)

imagepolygon — Draws a polygon

### Description

Signature as of PHP 8.0.0 (not supported with named arguments)

imagepolygon(GdImage `$image`, array `$points`, int `$color`): bool

Alternative signature (deprecated as of PHP 8.1.0)

imagepolygon(
GdImage `$image`,
array `$points`,
int `$num_points`,
int `$color`
): bool

imagepolygon() creates a polygon in the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`points`

  An array containing the polygon's vertices, e.g.:

  points[0] | = x0
  points[1] | = y0
  points[2] | = x1
  points[3] | = y1

`num_points`

  Total number of points (vertices), which must be at least 3.

  If this parameter is omitted as per the second signature, `points` must have an even number of elements, and `num_points` is assumed to be `count($points)/2`.
`color`

  A color identifier created with imagecolorallocate().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The parameter `num_points` has been deprecated.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagepolygon() example

`<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);
// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);
// Draw the polygon
imagepolygon($image, array(
0, 0,
100, 200,
300, 200
),
$col_poly);
// Output the picture to the browser
header('Content-type: image/png');
imagepng($image);
?>`

The above example will output something similar to:

### See Also

- imagefilledpolygon() - Draw a filled polygon
- imageopenpolygon() - Draws an open polygon
- imagecreate() - Create a new palette based image
- imagecreatetruecolor() - Create a new true color image

# imagerectangle

(PHP 4, PHP 5, PHP 7, PHP 8)

imagerectangle — Draw a rectangle

### Description

imagerectangle(
GdImage `$image`,
int `$x1`,
int `$y1`,
int `$x2`,
int `$y2`,
int `$color`
): true

imagerectangle() creates a rectangle starting at the specified coordinates.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x1`

  Upper left x coordinate.

`y1`

  Upper left y coordinate 0, 0 is the top left corner of the image.

`x2`

  Bottom right x coordinate.

`y2`

  Bottom right y coordinate.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Simple imagerectangle() example

`<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);
// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);
// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);
// Output
header('Content-Type: image/jpeg');
imagejpeg($canvas);
?>`

The above example will output something similar to:

# imageresolution

(PHP 7 >= 7.2.0, PHP 8)

imageresolution — Get or set the resolution of the image

### Description

imageresolution(GdImage `$image`, ?int `$resolution_x` = `null`, ?int `$resolution_y` = `null`): array|true

imageresolution() allows to set and get the resolution of an image in DPI (dots per inch). If the optional parameters are `null`, the current resolution is returned as an indexed array. If only `resolution_x` is not `null`, the horizontal and vertical resolution are set to this value. If none of the optional parameters are `null`, the horizontal and vertical resolution are set to these values, respectively.

The resolution is only used as meta information when images are read from and written to formats supporting this kind of information (curently PNG and JPEG). It does not affect any drawing operations. The default resolution for new images is 96 DPI.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`resolution_x`

  The horizontal resolution in DPI.

`resolution_y`

  The vertical resolution in DPI.

### Return Values

When used as getter, it returns an indexed array of the horizontal and vertical resolution on success. When used as setter, it always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `resolution_x` and `resolution_y` are now nullable.

### Examples

Example #1 Setting and getting the resolution of an image

`<?php
$im = imagecreatetruecolor(100, 100);
imageresolution($im, 200);
print_r(imageresolution($im));
imageresolution($im, 300, 72);
print_r(imageresolution($im));
?>`

The above example will output:

    Array
    (
        [0] => 200
        [1] => 200
    )
    Array
    (
        [0] => 300
        [1] => 72
    )

# imagerotate

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagerotate — Rotate an image with a given angle

### Description

imagerotate(GdImage `$image`, float `$angle`, int `$background_color`): GdImage|false

Rotates the `image` image using the given `angle` in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`angle`

  Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.

`background_color`

  Specifies the color of the uncovered zone after the rotation

### Return Values

Returns an image object for the rotated image, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.3.0 | The unused `ignore_transparent` has been completely removed.
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | The unused `ignore_transparent` expects a bool now; previously it expected an int.

### Examples

Example #1 Rotate an image 180 degrees

This example rotates an image 180 degrees - upside down.

`<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
// Output
imagejpeg($rotate);
?>`

The above example will output something similar to:

### Notes

> Note:

> This function is affected by the interpolation method set by imagesetinterpolation().

### See Also

- imagesetinterpolation() - Set the interpolation method

# imagesavealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imagesavealpha — Whether to retain full alpha channel information when saving images

### Description

imagesavealpha(GdImage `$image`, bool `$enable`): true

imagesavealpha() sets the flag which determines whether to retain full alpha channel information (as opposed to single-color transparency) when saving images. This is only supported for image formats which support full alpha channel information, i.e. `PNG`, `WebP` and `AVIF`.

> Note: imagesavealpha() is only meaningful for `PNG` images, since the full alpha channel is always saved for `WebP` and `AVIF`. It is not recommended to rely on this behavior, as it may change in the future. Thus, imagesavealpha() should be called deliberately also for `WebP` and `AVIF` images.

Alphablending has to be disabled (`imagealphablending($im, false)`) to retain the alpha-channel in the first place.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`enable`

  Whether to save the alpha channel or not. Defaults to `false`.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Basic imagesavealpha() Usage

`<?php
// Load a png image with alpha channel
$png = imagecreatefrompng('./alphachannel_example.png');
// Turn off alpha blending
imagealphablending($png, false);
// Do desired operations
// Set alpha flag
imagesavealpha($png, true);
// Output image to browser
header('Content-Type: image/png');
imagepng($png);
?>`

### See Also

- imagealphablending() - Set the blending mode for an image

# imagescale

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagescale — Scale an image using the given new width and height

### Description

imagescale(
GdImage `$image`,
int `$width`,
int `$height` = -1,
int `$mode` = `IMG_BILINEAR_FIXED`
): GdImage|false

imagescale() scales an image using the given interpolation algorithm.

> Note:

> Unlike many of other image functions, imagescale() does not modify the passed `image`; instead, a new image is returned.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`width`

  The width to scale the image to.

`height`

  The height to scale the image to. If omitted or negative, the aspect ratio will be preserved.

`mode`

  One of `IMG_NEAREST_NEIGHBOUR`, `IMG_BILINEAR_FIXED`, `IMG_BICUBIC`, `IMG_BICUBIC_FIXED` or anything else (will use two pass).

  > Note: `IMG_WEIGHTED4` is not yet supported.

### Return Values

Return the scaled image object on success or `false` on failure.

### Errors/Exceptions

Throws a ValueError if `width` or `height` would cause over-/underflow.

Throws a ValueError if `mode` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `width` or `height` would cause over-/underflow.
8.4.0 | Now throws a ValueError if `mode` is invalid.
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### See Also

- imagecopyresized() - Copy and resize part of an image
- imagecopyresampled() - Copy and resize part of an image with resampling

# imagesetbrush

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetbrush — Set the brush image for line drawing

### Description

imagesetbrush(GdImage `$image`, GdImage `$brush`): true

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors `IMG_COLOR_BRUSHED` or `IMG_COLOR_STYLEDBRUSHED`.

Caution

You need not take special action when you are finished with a brush, but if you destroy the brush image (or let PHP destroy it), you must not use the `IMG_COLOR_BRUSHED` or `IMG_COLOR_STYLEDBRUSHED` colors until you have set a new brush image!

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`brush`

  An image object.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` and `brush` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 imagesetbrush() example

`<?php
// Load a mini php logo
$php = imagecreatefrompng('./php.png');
// Create the main image, 100x100
$im = imagecreatetruecolor(100, 100);
// Fill the background with white
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 299, 99, $white);
// Set the brush
imagesetbrush($im, $php);
// Draw a couple of brushes, each overlaying each
imageline($im, 50, 50, 50, 60, IMG_COLOR_BRUSHED);
// Output image to the browser
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

# imagesetclip

(PHP 7 >= 7.2.0, PHP 8)

imagesetclip — Set the clipping rectangle

### Description

imagesetclip(
GdImage `$image`,
int `$x1`,
int `$y1`,
int `$x2`,
int `$y2`
): true

imagesetclip() sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x1`

  The x-coordinate of the upper left corner.

`y1`

  The y-coordinate of the upper left corner.

`x2`

  The x-coordinate of the lower right corner.

`y2`

  The y-coordinate of the lower right corner.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### See Also

- imagegetclip() - Get the clipping rectangle

# imagesetinterpolation

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagesetinterpolation — Set the interpolation method

### Description

imagesetinterpolation(GdImage `$image`, int `$method` = `IMG_BILINEAR_FIXED`): bool

Sets the interpolation method, setting an interpolation method affects the rendering of various functions in GD, such as the imagerotate() function.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`method`

  The interpolation method, which can be one of the following:

  - `IMG_BELL`: Bell filter.
  - `IMG_BESSEL`: Bessel filter.
  - `IMG_BICUBIC`: Bicubic interpolation.
  - `IMG_BICUBIC_FIXED`: Fixed point implementation of the bicubic interpolation.
  - `IMG_BILINEAR_FIXED`: Fixed point implementation of the bilinear interpolation (`default (also on image creation)`).
  - `IMG_BLACKMAN`: Blackman window function.
  - `IMG_BOX`: Box blur filter.
  - `IMG_BSPLINE`: Spline interpolation.
  - `IMG_CATMULLROM`: Cubic Hermite spline interpolation.
  - `IMG_GAUSSIAN`: Gaussian function.
  - `IMG_GENERALIZED_CUBIC`: Generalized cubic spline fractal interpolation.
  - `IMG_HERMITE`: Hermite interpolation.
  - `IMG_HAMMING`: Hamming filter.
  - `IMG_HANNING`: Hanning filter.
  - `IMG_MITCHELL`: Mitchell filter.
  - `IMG_POWER`: Power interpolation.
  - `IMG_QUADRATIC`: Inverse quadratic interpolation.
  - `IMG_SINC`: Sinc function.
  - `IMG_NEAREST_NEIGHBOUR`: Nearest neighbour interpolation.
  - `IMG_WEIGHTED4`: Weighting filter.
  - `IMG_TRIANGLE`: Triangle interpolation.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagesetinterpolation() example

`<?php
// Load an image
$im = imagecreate(500, 500);
// By default interpolation is IMG_BILINEAR_FIXED, switch
// to use the 'Mitchell' filter:
imagesetinterpolation($im, IMG_MITCHELL);
// Continue to work with $im ...
?>`

### Notes

Changing the interpolation method affects the following functions when rendering:

- imageaffine()
- imagerotate()

### See Also

- imagegetinterpolation() - Get the interpolation method

# imagesetpixel

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesetpixel — Set a single pixel

### Description

imagesetpixel(
GdImage `$image`,
int `$x`,
int `$y`,
int `$color`
): true

imagesetpixel() draws a pixel at the specified coordinate.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`x`

  x-coordinate.

`y`

  y-coordinate.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagesetpixel() example

A random drawing that ends with a regular picture.

`<?php
$x = 200;
$y = 200;
$gd = imagecreatetruecolor($x, $y);
$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);
$red = imagecolorallocate($gd, 255, 0, 0);
for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x), round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}
header('Content-Type: image/png');
imagepng($gd);
?>`

The above example will output something similar to:

### See Also

- imagecreatetruecolor() - Create a new true color image
- imagecolorallocate() - Allocate a color for an image
- imagecolorat() - Get the index of the color of a pixel

# imagesetstyle

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetstyle — Set the style for line drawing

### Description

imagesetstyle(GdImage `$image`, array `$style`): bool

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color `IMG_COLOR_STYLED` or lines of images with color `IMG_COLOR_STYLEDBRUSHED`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`style`

  An array of pixel colors. You can use the `IMG_COLOR_TRANSPARENT` constant to add a transparent pixel. Note that `style` must not be an empty array.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Following example script draws a dashed line from upper left to lower right corner of the canvas:

Example #1 imagesetstyle() example

`<?php
header("Content-type: image/jpeg");
$im = imagecreatetruecolor(100, 100);
$w = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);
/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);
$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);
imagejpeg($im);
?>`

The above example will output something similar to:

### See Also

- imagesetbrush() - Set the brush image for line drawing
- imageline() - Draw a line

# imagesetthickness

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetthickness — Set the thickness for line drawing

### Description

imagesetthickness(GdImage `$image`, int `$thickness`): true

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to `thickness` pixels.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`thickness`

  Thickness, in pixels.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagesetthickness() example

`<?php
// Create a 200x100 image
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 99, $white);
// Set the line thickness to 5
imagesetthickness($im, 5);
// Draw the rectangle
imagerectangle($im, 14, 14, 185, 85, $black);
// Output image to the browser
header('Content-Type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

# imagesettile

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesettile — Set the tile image for filling

### Description

imagesettile(GdImage `$image`, GdImage `$tile`): true

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color `IMG_COLOR_TILED`.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Caution

You need not take special action when you are finished with a tile, but if you destroy the tile image (or let PHP destroy it), you must not use the `IMG_COLOR_TILED` color until you have set a new tile image!

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`tile`

  The image object to be used as a tile.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` and `tile` expect GdImage instances now; previously, resources were expected.

### Examples

Example #1 imagesettile() example

`<?php
// Load an external image
$zend = imagecreatefromgif('./zend.gif');
// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);
// Set the tile
imagesettile($im, $zend);
// Make the image repeat
imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED);
// Output image to the browser
header('Content-Type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

# imagestring

(PHP 4, PHP 5, PHP 7, PHP 8)

imagestring — Draw a string horizontally

### Description

imagestring(
GdImage `$image`,
GdFont|int `$font`,
int `$x`,
int `$y`,
string `$string`,
int `$color`
): true

Draws a `string` at the given coordinates.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

`x`

  x-coordinate of the upper left corner.

`y`

  y-coordinate of the upper left corner.

`string`

  The string to be written.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagestring() example

`<?php
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($im);
?>`

The above example will output something similar to:

### See Also

- imagestringup() - Draw a string vertically
- imageloadfont() - Load a new font
- imagettftext() - Write text to the image using TrueType fonts

# imagestringup

(PHP 4, PHP 5, PHP 7, PHP 8)

imagestringup — Draw a string vertically

### Description

imagestringup(
GdImage `$image`,
GdFont|int `$font`,
int `$x`,
int `$y`,
string `$string`,
int `$color`
): true

Draws a `string` vertically at the given coordinates.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`font`

  Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or GdFont instance, returned by imageloadfont().

`x`

  x-coordinate of the bottom left corner.

`y`

  y-coordinate of the bottom left corner.

`string`

  The string to be written.

`color`

  A color identifier created with imagecolorallocate().

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `font` parameter now accepts both an GdFont instance and an int; previously only int was accepted.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 imagestringup() example

`<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);
// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, 'gd library', $textcolor);
// Save the image
imagepng($im, './stringup.png');
?>`

The above example will output something similar to:

### See Also

- imagestring() - Draw a string horizontally
- imageloadfont() - Load a new font

# imagesx

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesx — Get image width

### Description

imagesx(GdImage `$image`): int

Returns the width of the given `image` object.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Return the width of the `image`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagesx()

`<?php
// create a 300*200 image
$img = imagecreatetruecolor(300, 200);
echo imagesx($img); // 300
?>`

### See Also

- imagecreatetruecolor() - Create a new true color image
- getimagesize() - Get the size of an image
- imagesy() - Get image height

# imagesy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesy — Get image height

### Description

imagesy(GdImage `$image`): int

Returns the height of the given `image` object.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

### Return Values

Return the height of the `image`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Using imagesy()

`<?php
// create a 300*200 image
$img = imagecreatetruecolor(300, 200);
echo imagesy($img); // 200
?>`

### See Also

- imagecreatetruecolor() - Create a new true color image
- getimagesize() - Get the size of an image
- imagesx() - Get image width

# imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagetruecolortopalette — Convert a true color image to a palette image

### Description

imagetruecolortopalette(GdImage `$image`, bool `$dither`, int `$num_colors`): bool

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`dither`

  Indicates if the image should be dithered - if it is `true` then dithering will be used which will result in a more speckled image but with better color approximation.

`num_colors`

  Sets the maximum number of colors that should be retained in the palette.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Converting a true color image to a palette-based image

`<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);
// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);
// Save the image
imagepng($im, './paletteimage.png');
?>`

# imagettfbbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imagettfbbox — Give the bounding box of a text using TrueType fonts

### Description

imagettfbbox(
float `$size`,
float `$angle`,
string `$font_filename`,
string `$string`,
array `$options` = []
): array|false

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

> Note:

> Prior to PHP 8.0.0, imageftbbox() was an extended variant of imagettfbbox() which additionally supported the `extrainfo`. As of PHP 8.0.0, imagettfbbox() is an alias of imageftbbox().

### Parameters

`size`

  The font size in points.

`angle`

  Angle in degrees in which `string` will be measured.

`fontfile`

  The path to the TrueType font you wish to use.

  Depending on which version of the GD library PHP is using, when `fontfile` does not begin with a leading `/` then `.ttf` will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

  When using versions of the GD library lower than 2.0.18, a `space` character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: `Warning: Could not find/open font`. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

  In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

  `<?php
  // Set the environment variable for GD
  putenv('GDFONTPATH=' . realpath('.'));
  // Name the font to be used (note the lack of the .ttf extension)
  $font = 'SomeFont';
  ?>`

  > Note:

  > Note that open_basedir does not apply to `fontfile`.

`string`

  The string to be measured.

`options`

  Same as in imagettftext().

### Return Values

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text on success and `false` on error.

key | contents
--- | ---
0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the `angle`, so "upper left" means in the top left-hand corner seeing the text horizontally.

### Changelog

Version | Description
--- | ---
8.0.0 | The `options` has been added.

### Examples

Example #1 imagettfbbox() example

`<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);
// Path to our font file
$font = './arial.ttf';
// First we create our bounding box for the first text
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());
// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());
// Create the next bounding box for the second text
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());
// Set the cordinates so its next to the first text
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());
// Output to browser
header('Content-Type: image/png');
imagepng($im);
?>`

### Notes

> Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

### See Also

- imagettftext() - Write text to the image using TrueType fonts
- imageftbbox() - Give the bounding box of a text using fonts via freetype2

# imagettftext

(PHP 4, PHP 5, PHP 7, PHP 8)

imagettftext — Write text to the image using TrueType fonts

### Description

imagettftext(
GdImage `$image`,
float `$size`,
float `$angle`,
int `$x`,
int `$y`,
int `$color`,
string `$font_filename`,
string `$text`,
array `$options` = []
): array|false

Writes the given `text` into the image using TrueType fonts.

> Note:

> Prior to PHP 8.0.0, imagefttext() was an extended variant of imagettftext() which additionally supported the `extrainfo`. As of PHP 8.0.0, imagettftext() is an alias of imagefttext().

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`size`

  The font size in points.

`angle`

  The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

`x`

  The coordinates given by `x` and `y` will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where `x` and `y` define the upper-left corner of the first character. For example, "top left" is 0, 0.

`y`

  The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

`color`

  The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

`fontfile`

  The path to the TrueType font you wish to use.

  Depending on which version of the GD library PHP is using, when `fontfile` does not begin with a leading `/` then `.ttf` will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

  When using versions of the GD library lower than 2.0.18, a `space` character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: `Warning: Could not find/open font`. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

  In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

  `<?php
  // Set the environment variable for GD
  putenv('GDFONTPATH=' . realpath('.'));
  // Name the font to be used (note the lack of the .ttf extension)
  $font = 'SomeFont';
  ?>`

  > Note:

  > Note that open_basedir does not apply to `fontfile`.

`text`

  The text string in UTF-8 encoding.

  May include decimal numeric character references (of the form: `&#8364;`) to access characters in a font beyond position 127. The hexadecimal format (like `&#xA9;`) is supported. Strings in UTF-8 encoding can be passed directly.

  Named entities, such as `&copy;`, are not supported. Consider using html_entity_decode() to decode these named entities into UTF-8 strings.

  If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

`options`

  An array with `linespacing` key holding a float value.

### Return Values

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally. Returns `false` on error.

### Changelog

Version | Description
--- | ---
8.0.0 | The `options` has been added.

### Examples

Example #1 imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

`<?php
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
?>`

The above example will output something similar to:

### Notes

> Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

### See Also

- imagettfbbox() - Give the bounding box of a text using TrueType fonts
- imagefttext() - Write text to the image using fonts using FreeType 2
- imagestring() - Draw a string horizontally

# imagetypes

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

imagetypes — Return the image types supported by this PHP build

### Description

imagetypes(): int

Returns the image types supported by the current PHP installation.

### Parameters

This function has no parameters.

### Return Values

Returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, `IMG_AVIF` | `IMG_BMP` | `IMG_GIF` | `IMG_JPG` | `IMG_PNG` | `IMG_WBMP` | `IMG_XPM` | `IMG_WEBP`.

### Changelog

Version | Description
--- | ---
8.1.0 | `IMG_AVIF` added.
7.2.0 | `IMG_BMP` added.
7.0.10 | `IMG_WEBP` added.

### Examples

Example #1 Checking for PNG support

`<?php
if (imagetypes() & IMG_PNG) {
echo "PNG Support is enabled";
}
?>`

### See Also

- gd_info() - Retrieve information about the currently installed GD library

# imagewbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagewbmp — Output image to browser or file

### Description

imagewbmp(GdImage `$image`, resource|string|null `$file` = `null`, ?int `$foreground_color` = `null`): bool

imagewbmp() outputs or save a WBMP version of the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

`foreground_color`

  You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | `foreground_color` is nullable now.

### Examples

Example #1 Outputting a WBMP image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');
// Output the image
imagewbmp($im);
?>`

Example #2 Saving the WBMP image

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image
imagewbmp($im, 'simpletext.wbmp');
?>`

Example #3 Outputting the image with a different foreground

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');
// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);
imagewbmp($im, NULL, $foreground_color);
?>`

### See Also

- image2wbmp() - Output image to browser or file
- imagepng() - Output a PNG image to either the browser or a file
- imagegif() - Output image to browser or file
- imagejpeg() - Output image to browser or file
- imagetypes() - Return the image types supported by this PHP build

# imagewebp

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

imagewebp — Output a WebP image to browser or file

### Description

imagewebp(GdImage `$image`, resource|string|null `$file` = `null`, int `$quality` = -1): bool

Outputs or saves a WebP version of the given `image`.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`file`

  The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or `null`, the raw image stream will be output directly.

`quality`

  `quality` ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). If `-1` is provided, the default value `80` is used.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Errors/Exceptions

Throws a ValueError if `quality` is invalid.

### Changelog

Version | Description
--- | ---
8.4.0 | Now throws a ValueError if `quality` is invalid.
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.

### Examples

Example #1 Saving an WebP file

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'WebP with PHP', $text_color);
// Save the image
imagewebp($im, 'php.webp');
?>`

# imagexbm

(PHP 5, PHP 7, PHP 8)

imagexbm — Output an XBM image to browser or file

### Description

imagexbm(GdImage `$image`, ?string `$filename`, ?int `$foreground_color` = `null`): bool

Outputs or save an XBM version of the given `image`.

> Note: imagexbm() doesn't apply any padding, so the image width has to be a multiple of 8. This restriction does no longer apply as of PHP 7.0.9.

### Parameters

`image`

  A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

`filename`

  The path to save the file to, given as string. If `null`, the raw image stream will be output directly.

  The `filename` (without the .xbm extension) is also used for the C identifiers of the XBM, whereby non alphanumeric characters of the current locale are substituted by underscores. If `filename` is set to `null`, `image` is used to build the C identifiers.

`foreground_color`

  You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black. All other colors are treated as background.

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Changelog

Version | Description
--- | ---
8.0.0 | `image` expects a GdImage instance now; previously, a valid `gd` resource was expected.
8.0.0 | `foreground_color` is now nullable.
8.0.0 | The fourth parameter, which was unused, has been removed.

### Examples

Example #1 Saving an XBM file

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image
imagexbm($im, 'simpletext.xbm');
?>`

Example #2 Saving an XBM file with a different foreground color

`<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);
// Save the image
imagexbm($im, NULL, $foreground_color);
?>`

# iptcembed

(PHP 4, PHP 5, PHP 7, PHP 8)

iptcembed — Embeds binary IPTC data into a JPEG image

### Description

iptcembed(string `$iptc_data`, string `$filename`, int `$spool` = 0): string|bool

Embeds binary IPTC data into a JPEG image.

### Parameters

`iptc_data`

  The data to be written.

`filename`

  Path to the JPEG image.

`spool`

  Spool flag. If the spool flag is less than 2 then the JPEG will be returned as a string. Otherwise the JPEG will be printed to STDOUT.

### Return Values

If `spool` is less than 2, the JPEG will be returned, or `false` on failure. Otherwise returns `true` on success or `false` on failure.

### Examples

Example #1 Embedding IPTC data into a JPEG

`<?php
// iptc_make_tag() function by Thies C. Arntzen
function iptc_make_tag($rec, $data, $value)
{
$length = strlen($value);
$retval = chr(0x1C) . chr($rec) . chr($data);
if($length < 0x8000)
{
$retval .= chr($length >> 8) . chr($length & 0xFF);
}
else
{
$retval .= chr(0x80) .
chr(0x04) .
chr(($length >> 24) & 0xFF) .
chr(($length >> 16) & 0xFF) .
chr(($length >> 8) & 0xFF) .
chr($length & 0xFF);
}
return $retval . $value;
}
// Path to jpeg file
$path = './phplogo.jpg';
// Set the IPTC tags
$iptc = array(
'2#120' => 'Test image',
'2#116' => 'Copyright 2008-2009, The PHP Group'
);
// Convert the IPTC tags into binary code
$data = '';
foreach($iptc as $tag => $string)
{
$tag = substr($tag, 2);
$data .= iptc_make_tag(2, $tag, $string);
}
// Embed the IPTC data
$content = iptcembed($data, $path);
// Write the new image data out to the file.
$fp = fopen($path, "wb");
fwrite($fp, $content);
fclose($fp);
?>`

### Notes

> Note:

> This function does not require the GD image library.

# iptcparse

(PHP 4, PHP 5, PHP 7, PHP 8)

iptcparse — Parse a binary IPTC block into single tags

### Description

iptcparse(string `$iptc_block`): array|false

Parses an » IPTC block into its single tags.

### Parameters

`iptc_block`

  A binary IPTC block.

### Return Values

Returns an array using the tagmarker as an index and the value as the value. It returns `false` on error or if no IPTC data was found.

### Examples

Example #1 iptcparse() used together with getimagesize()

`<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
$iptc = iptcparse($info['APP13']);
var_dump($iptc);
}
?>`

### Notes

> Note:

> This function does not require the GD image library.

# jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

jpeg2wbmp — Convert JPEG image file to WBMP image file

Warning

This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

jpeg2wbmp(
string `$jpegname`,
string `$wbmpname`,
int `$dest_height`,
int `$dest_width`,
int `$threshold`
): bool

Converts a JPEG file into a WBMP file.

### Parameters

`jpegname`

  Path to JPEG file.

`wbmpname`

  Path to destination WBMP file.

`dest_height`

  Destination image height.

`dest_width`

  Destination image width.

`threshold`

  Threshold value, between 0 and 8 (inclusive).

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Examples

Example #1 jpeg2wbmp() example

`<?php
// Path to the target jpeg
$path = './test.jpg';
// Get the image sizes
$image = getimagesize($path);
// Convert image
jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5);
?>`

### See Also

- png2wbmp() - Convert PNG image file to WBMP image file

# png2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

png2wbmp — Convert PNG image file to WBMP image file

Warning

This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

png2wbmp(
string `$pngname`,
string `$wbmpname`,
int `$dest_height`,
int `$dest_width`,
int `$threshold`
): bool

Converts a PNG file into a WBMP file.

### Parameters

`pngname`

  Path to PNG file.

`wbmpname`

  Path to destination WBMP file.

`dest_height`

  Destination image height.

`dest_width`

  Destination image width.

`threshold`

  Threshold value, between 0 and 8 (inclusive).

### Return Values

Returns `true` on success or `false` on failure.

Caution

However, if libgd fails to output the image, this function returns `true`.

### Examples

Example #1 png2wbmp() example

`<?php
// Path to the target png
$path = './test.png';
// Get the image sizes
$image = getimagesize($path);
// Convert image
png2wbmp($path, './test.wbmp', $image[1], $image[0], 7);
?>`

### See Also

- jpeg2wbmp() - Convert JPEG image file to WBMP image file

## Table of Contents

- gd_info — Retrieve information about the currently installed GD library
- getimagesize — Get the size of an image
- getimagesizefromstring — Get the size of an image from a string
- image_type_to_extension — Get file extension for image type
- image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
- image2wbmp — Output image to browser or file
- imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
- imageaffinematrixconcat — Concatenate two affine transformation matrices
- imageaffinematrixget — Get an affine transformation matrix
- imagealphablending — Set the blending mode for an image
- imageantialias — Should antialias functions be used or not
- imagearc — Draws an arc
- imageavif — Output image to browser or file
- imagebmp — Output a BMP image to browser or file
- imagechar — Draw a character horizontally
- imagecharup — Draw a character vertically
- imagecolorallocate — Allocate a color for an image
- imagecolorallocatealpha — Allocate a color for an image
- imagecolorat — Get the index of the color of a pixel
- imagecolorclosest — Get the index of the closest color to the specified color
- imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
- imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
- imagecolordeallocate — De-allocate a color for an image
- imagecolorexact — Get the index of the specified color
- imagecolorexactalpha — Get the index of the specified color + alpha
- imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
- imagecolorresolve — Get the index of the specified color or its closest possible alternative
- imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
- imagecolorset — Set the color for the specified palette index
- imagecolorsforindex — Get the colors for an index
- imagecolorstotal — Find out the number of colors in an image's palette
- imagecolortransparent — Define a color as transparent
- imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
- imagecopy — Copy part of an image
- imagecopymerge — Copy and merge part of an image
- imagecopymergegray — Copy and merge part of an image with gray scale
- imagecopyresampled — Copy and resize part of an image with resampling
- imagecopyresized — Copy and resize part of an image
- imagecreate — Create a new palette based image
- imagecreatefromavif — Create a new image from file or URL
- imagecreatefrombmp — Create a new image from file or URL
- imagecreatefromgd — Create a new image from GD file or URL
- imagecreatefromgd2 — Create a new image from GD2 file or URL
- imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
- imagecreatefromgif — Create a new image from file or URL
- imagecreatefromjpeg — Create a new image from file or URL
- imagecreatefrompng — Create a new image from file or URL
- imagecreatefromstring — Create a new image from the image stream in the string
- imagecreatefromtga — Create a new image from file or URL
- imagecreatefromwbmp — Create a new image from file or URL
- imagecreatefromwebp — Create a new image from file or URL
- imagecreatefromxbm — Create a new image from file or URL
- imagecreatefromxpm — Create a new image from file or URL
- imagecreatetruecolor — Create a new true color image
- imagecrop — Crop an image to the given rectangle
- imagecropauto — Crop an image automatically using one of the available modes
- imagedashedline — Draw a dashed line
- imagedestroy — Destroy an image
- imageellipse — Draw an ellipse
- imagefill — Flood fill
- imagefilledarc — Draw a partial arc and fill it
- imagefilledellipse — Draw a filled ellipse
- imagefilledpolygon — Draw a filled polygon
- imagefilledrectangle — Draw a filled rectangle
- imagefilltoborder — Flood fill to specific color
- imagefilter — Applies a filter to an image
- imageflip — Flips an image using a given mode
- imagefontheight — Get font height
- imagefontwidth — Get font width
- imageftbbox — Give the bounding box of a text using fonts via freetype2
- imagefttext — Write text to the image using fonts using FreeType 2
- imagegammacorrect — Apply a gamma correction to a GD image
- imagegd — Output GD image to browser or file
- imagegd2 — Output GD2 image to browser or file
- imagegetclip — Get the clipping rectangle
- imagegetinterpolation — Get the interpolation method
- imagegif — Output image to browser or file
- imagegrabscreen — Captures the whole screen
- imagegrabwindow — Captures a window
- imageinterlace — Enable or disable interlace
- imageistruecolor — Finds whether an image is a truecolor image
- imagejpeg — Output image to browser or file
- imagelayereffect — Set the alpha blending flag to use layering effects
- imageline — Draw a line
- imageloadfont — Load a new font
- imageopenpolygon — Draws an open polygon
- imagepalettecopy — Copy the palette from one image to another
- imagepalettetotruecolor — Converts a palette based image to true color
- imagepng — Output a PNG image to either the browser or a file
- imagepolygon — Draws a polygon
- imagerectangle — Draw a rectangle
- imageresolution — Get or set the resolution of the image
- imagerotate — Rotate an image with a given angle
- imagesavealpha — Whether to retain full alpha channel information when saving images
- imagescale — Scale an image using the given new width and height
- imagesetbrush — Set the brush image for line drawing
- imagesetclip — Set the clipping rectangle
- imagesetinterpolation — Set the interpolation method
- imagesetpixel — Set a single pixel
- imagesetstyle — Set the style for line drawing
- imagesetthickness — Set the thickness for line drawing
- imagesettile — Set the tile image for filling
- imagestring — Draw a string horizontally
- imagestringup — Draw a string vertically
- imagesx — Get image width
- imagesy — Get image height
- imagetruecolortopalette — Convert a true color image to a palette image
- imagettfbbox — Give the bounding box of a text using TrueType fonts
- imagettftext — Write text to the image using TrueType fonts
- imagetypes — Return the image types supported by this PHP build
- imagewbmp — Output image to browser or file
- imagewebp — Output a WebP image to browser or file
- imagexbm — Output an XBM image to browser or file
- iptcembed — Embeds binary IPTC data into a JPEG image
- iptcparse — Parse a binary IPTC block into single tags
- jpeg2wbmp — Convert JPEG image file to WBMP image file
- png2wbmp — Convert PNG image file to WBMP image file

# The GdImage class

(PHP 8)

## Introduction

A fully opaque class which replaces `gd` resources as of PHP 8.0.0.

## Class synopsis

final class GdImage {
}

# The GdFont class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces `gd font` resources as of PHP 8.1.0.

## Class synopsis

final class GdFont {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
  - PNG creation with PHP
  - Adding watermarks to images using alpha channels
  - Using imagecopymerge to create a translucent watermark
- GD and Image Functions
  - gd_info — Retrieve information about the currently installed GD library
  - getimagesize — Get the size of an image
  - getimagesizefromstring — Get the size of an image from a string
  - image_type_to_extension — Get file extension for image type
  - image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  - image2wbmp — Output image to browser or file
  - imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
  - imageaffinematrixconcat — Concatenate two affine transformation matrices
  - imageaffinematrixget — Get an affine transformation matrix
  - imagealphablending — Set the blending mode for an image
  - imageantialias — Should antialias functions be used or not
  - imagearc — Draws an arc
  - imageavif — Output image to browser or file
  - imagebmp — Output a BMP image to browser or file
  - imagechar — Draw a character horizontally
  - imagecharup — Draw a character vertically
  - imagecolorallocate — Allocate a color for an image
  - imagecolorallocatealpha — Allocate a color for an image
  - imagecolorat — Get the index of the color of a pixel
  - imagecolorclosest — Get the index of the closest color to the specified color
  - imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
  - imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
  - imagecolordeallocate — De-allocate a color for an image
  - imagecolorexact — Get the index of the specified color
  - imagecolorexactalpha — Get the index of the specified color + alpha
  - imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
  - imagecolorresolve — Get the index of the specified color or its closest possible alternative
  - imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
  - imagecolorset — Set the color for the specified palette index
  - imagecolorsforindex — Get the colors for an index
  - imagecolorstotal — Find out the number of colors in an image's palette
  - imagecolortransparent — Define a color as transparent
  - imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
  - imagecopy — Copy part of an image
  - imagecopymerge — Copy and merge part of an image
  - imagecopymergegray — Copy and merge part of an image with gray scale
  - imagecopyresampled — Copy and resize part of an image with resampling
  - imagecopyresized — Copy and resize part of an image
  - imagecreate — Create a new palette based image
  - imagecreatefromavif — Create a new image from file or URL
  - imagecreatefrombmp — Create a new image from file or URL
  - imagecreatefromgd — Create a new image from GD file or URL
  - imagecreatefromgd2 — Create a new image from GD2 file or URL
  - imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
  - imagecreatefromgif — Create a new image from file or URL
  - imagecreatefromjpeg — Create a new image from file or URL
  - imagecreatefrompng — Create a new image from file or URL
  - imagecreatefromstring — Create a new image from the image stream in the string
  - imagecreatefromtga — Create a new image from file or URL
  - imagecreatefromwbmp — Create a new image from file or URL
  - imagecreatefromwebp — Create a new image from file or URL
  - imagecreatefromxbm — Create a new image from file or URL
  - imagecreatefromxpm — Create a new image from file or URL
  - imagecreatetruecolor — Create a new true color image
  - imagecrop — Crop an image to the given rectangle
  - imagecropauto — Crop an image automatically using one of the available modes
  - imagedashedline — Draw a dashed line
  - imagedestroy — Destroy an image
  - imageellipse — Draw an ellipse
  - imagefill — Flood fill
  - imagefilledarc — Draw a partial arc and fill it
  - imagefilledellipse — Draw a filled ellipse
  - imagefilledpolygon — Draw a filled polygon
  - imagefilledrectangle — Draw a filled rectangle
  - imagefilltoborder — Flood fill to specific color
  - imagefilter — Applies a filter to an image
  - imageflip — Flips an image using a given mode
  - imagefontheight — Get font height
  - imagefontwidth — Get font width
  - imageftbbox — Give the bounding box of a text using fonts via freetype2
  - imagefttext — Write text to the image using fonts using FreeType 2
  - imagegammacorrect — Apply a gamma correction to a GD image
  - imagegd — Output GD image to browser or file
  - imagegd2 — Output GD2 image to browser or file
  - imagegetclip — Get the clipping rectangle
  - imagegetinterpolation — Get the interpolation method
  - imagegif — Output image to browser or file
  - imagegrabscreen — Captures the whole screen
  - imagegrabwindow — Captures a window
  - imageinterlace — Enable or disable interlace
  - imageistruecolor — Finds whether an image is a truecolor image
  - imagejpeg — Output image to browser or file
  - imagelayereffect — Set the alpha blending flag to use layering effects
  - imageline — Draw a line
  - imageloadfont — Load a new font
  - imageopenpolygon — Draws an open polygon
  - imagepalettecopy — Copy the palette from one image to another
  - imagepalettetotruecolor — Converts a palette based image to true color
  - imagepng — Output a PNG image to either the browser or a file
  - imagepolygon — Draws a polygon
  - imagerectangle — Draw a rectangle
  - imageresolution — Get or set the resolution of the image
  - imagerotate — Rotate an image with a given angle
  - imagesavealpha — Whether to retain full alpha channel information when saving images
  - imagescale — Scale an image using the given new width and height
  - imagesetbrush — Set the brush image for line drawing
  - imagesetclip — Set the clipping rectangle
  - imagesetinterpolation — Set the interpolation method
  - imagesetpixel — Set a single pixel
  - imagesetstyle — Set the style for line drawing
  - imagesetthickness — Set the thickness for line drawing
  - imagesettile — Set the tile image for filling
  - imagestring — Draw a string horizontally
  - imagestringup — Draw a string vertically
  - imagesx — Get image width
  - imagesy — Get image height
  - imagetruecolortopalette — Convert a true color image to a palette image
  - imagettfbbox — Give the bounding box of a text using TrueType fonts
  - imagettftext — Write text to the image using TrueType fonts
  - imagetypes — Return the image types supported by this PHP build
  - imagewbmp — Output image to browser or file
  - imagewebp — Output a WebP image to browser or file
  - imagexbm — Output an XBM image to browser or file
  - iptcembed — Embeds binary IPTC data into a JPEG image
  - iptcparse — Parse a binary IPTC block into single tags
  - jpeg2wbmp — Convert JPEG image file to WBMP image file
  - png2wbmp — Convert PNG image file to WBMP image file
- GdImage — The GdImage class
- GdFont — The GdFont class

# Gmagick

# Introduction

Warning

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.

Gmagick is a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.

GraphicsMagick prides itself as the swiss army knife of image processing. It works with over 88 major formats including important formats like DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Gmagick consists of a main Gmagick class, a GmagickDraw class which is in effect a drawing wand and a GmagickPixel class of which instances represent a single pixel of an image (color, opacity).

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

This extension works best with GraphicsMagick version 1.4+. Gmagick should work with earlier versions up to GraphicsMagick 1.2.6 but some features and formats are not supported for these versions. Windows version of GraphicsMagick is available from the GraphicsMagick website. To read about the difference between ImageMagick and GraphicsMagick, check the » FAQ.

## Installation

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: » https://pecl.php.net/package/gmagick.

> Note: The official name of this extension is gmagick.

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

Colortype constants
`Gmagick::COLOR_BLACK` (int)
  Black
`Gmagick::COLOR_BLUE` (int)
  Blue
`Gmagick::COLOR_CYAN` (int)
  Cyan
`Gmagick::COLOR_GREEN` (int)
  Green
`Gmagick::COLOR_RED` (int)
  Red
`Gmagick::COLOR_YELLOW` (int)
  Yellow
`Gmagick::COLOR_MAGENTA` (int)
  Magenta
`Gmagick::COLOR_OPACITY` (int)
  Opacity
`Gmagick::COLOR_ALPHA` (int)
  Alpha
`Gmagick::COLOR_FUZZ` (int)
  Fuzz

Composite Operator Constants
`Gmagick::COMPOSITE_DEFAULT` (int)
  The default composite operator
`Gmagick::COMPOSITE_UNDEFINED` (int)
  Undefined composite operator
`Gmagick::COMPOSITE_NO` (int)
  No composite operator defined
`Gmagick::COMPOSITE_ADD` (int)
  The result of image + image
`Gmagick::COMPOSITE_ATOP` (int)
  The result is the same shape as image, with composite image obscuring image where the image shapes overlap
`Gmagick::COMPOSITE_BLEND` (int)
  Blends the image
`Gmagick::COMPOSITE_BUMPMAP` (int)
  The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
`Gmagick::COMPOSITE_CLEAR` (int)
  Makes the target image transparent
`Gmagick::COMPOSITE_COLORBURN` (int)
  Darkens the destination image to reflect the source image
`Gmagick::COMPOSITE_COLORDODGE` (int)
  Brightens the destination image to reflect the source image
`Gmagick::COMPOSITE_COLORIZE` (int)
  Colorizes the target image using the composite image
`Gmagick::COMPOSITE_COPYBLACK` (int)
  Copies black from the source to target
`Gmagick::COMPOSITE_COPYBLUE` (int)
  Copies blue from the source to target
`Gmagick::COMPOSITE_COPY` (int)
  Copies the source image on the target image
`Gmagick::COMPOSITE_COPYCYAN` (int)
  Copies cyan from the source to target
`Gmagick::COMPOSITE_COPYGREEN` (int)
  Copies green from the source to target
`Gmagick::COMPOSITE_COPYMAGENTA` (int)
  Copies magenta from the source to target
`Gmagick::COMPOSITE_COPYOPACITY` (int)
  Copies opacity from the source to target
`Gmagick::COMPOSITE_COPYRED` (int)
  Copies red from the source to target
`Gmagick::COMPOSITE_COPYYELLOW` (int)
  Copies yellow from the source to target
`Gmagick::COMPOSITE_DARKEN` (int)
  Darkens the target image
`Gmagick::COMPOSITE_DSTATOP` (int)
  The part of the destination lying inside of the source is composited over the source and replaces the destination
`Gmagick::COMPOSITE_DST` (int)
  The target is left untouched
`Gmagick::COMPOSITE_DSTIN` (int)
  The parts inside the source replace the target
`Gmagick::COMPOSITE_DSTOUT` (int)
  The parts outside the source replace the target
`Gmagick::COMPOSITE_DSTOVER` (int)
  Target replaces the source
`Gmagick::COMPOSITE_DIFFERENCE` (int)
  Subtracts the darker of the two constituent colors from the lighter
`Gmagick::COMPOSITE_DISPLACE` (int)
  Shifts target image pixels as defined by the source
`Gmagick::COMPOSITE_DISSOLVE` (int)
  Dissolves the source in to the target
`Gmagick::COMPOSITE_EXCLUSION` (int)
  Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
`Gmagick::COMPOSITE_HARDLIGHT` (int)
  Multiplies or screens the colors, dependent on the source color value
`Gmagick::COMPOSITE_HUE` (int)
  Modifies the hue of the target as defined by source
`Gmagick::COMPOSITE_IN` (int)
  Composites source into the target
`Gmagick::COMPOSITE_LIGHTEN` (int)
  Lightens the target as defined by source
`Gmagick::COMPOSITE_LUMINIZE` (int)
  Luminizes the target as defined by source
`Gmagick::COMPOSITE_MINUS` (int)
  Subtracts the source from the target
`Gmagick::COMPOSITE_MODULATE` (int)
  Modulates the target brightness, saturation and hue as defined by source
`Gmagick::COMPOSITE_MULTIPLY` (int)
  Multiplies the target to the source
`Gmagick::COMPOSITE_OUT` (int)
  Composites outer parts of the source on the target
`Gmagick::COMPOSITE_OVER` (int)
  Composites source over the target
`Gmagick::COMPOSITE_OVERLAY` (int)
  Overlays the source on the target
`Gmagick::COMPOSITE_PLUS` (int)
  Adds the source to the target
`Gmagick::COMPOSITE_REPLACE` (int)
  Replaces the target with the source
`Gmagick::COMPOSITE_SATURATE` (int)
  Saturates the target as defined by the source
`Gmagick::COMPOSITE_SCREEN` (int)
  The source and destination are complemented and then multiplied and then replace the destination
`Gmagick::COMPOSITE_SOFTLIGHT` (int)
  Darkens or lightens the colors, dependent on the source
`Gmagick::COMPOSITE_SRCATOP` (int)
  The part of the source lying inside of the destination is composited onto the destination
`Gmagick::COMPOSITE_SRC` (int)
  The source is copied to the destination
`Gmagick::COMPOSITE_SRCIN` (int)
  The part of the source lying inside of the destination replaces the destination
`Gmagick::COMPOSITE_SRCOUT` (int)
  The part of the source lying outside of the destination replaces the destination
`Gmagick::COMPOSITE_SRCOVER` (int)
  The source replaces the destination
`Gmagick::COMPOSITE_SUBTRACT` (int)
  Subtract the colors in the source image from the destination image
`Gmagick::COMPOSITE_THRESHOLD` (int)
  The source is composited on the target as defined by source threshold
`Gmagick::COMPOSITE_XOR` (int)
  The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source

Montage Mode constants
`Gmagick::MONTAGEMODE_FRAME` (int)
`Gmagick::MONTAGEMODE_UNFRAME` (int)
`Gmagick::MONTAGEMODE_CONCATENATE` (int)

Style constants
`Gmagick::STYLE_NORMAL` (int)
`Gmagick::STYLE_ITALIC` (int)
`Gmagick::STYLE_OBLIQUE` (int)
`Gmagick::STYLE_ANY` (int)

Filter constants
`Gmagick::FILTER_UNDEFINED` (int)
`Gmagick::FILTER_POINT` (int)
`Gmagick::FILTER_BOX` (int)
`Gmagick::FILTER_TRIANGLE` (int)
`Gmagick::FILTER_HERMITE` (int)
`Gmagick::FILTER_HANNING` (int)
`Gmagick::FILTER_HAMMING` (int)
`Gmagick::FILTER_BLACKMAN` (int)
`Gmagick::FILTER_GAUSSIAN` (int)
`Gmagick::FILTER_QUADRATIC` (int)
`Gmagick::FILTER_CUBIC` (int)
`Gmagick::FILTER_CATROM` (int)
`Gmagick::FILTER_MITCHELL` (int)
`Gmagick::FILTER_LANCZOS` (int)
`Gmagick::FILTER_BESSEL` (int)
`Gmagick::FILTER_SINC` (int)

Image type constants
`Gmagick::IMGTYPE_UNDEFINED` (int)
`Gmagick::IMGTYPE_BILEVEL` (int)
`Gmagick::IMGTYPE_GRAYSCALE` (int)
`Gmagick::IMGTYPE_GRAYSCALEMATTE` (int)
`Gmagick::IMGTYPE_PALETTE` (int)
`Gmagick::IMGTYPE_PALETTEMATTE` (int)
`Gmagick::IMGTYPE_TRUECOLOR` (int)
`Gmagick::IMGTYPE_TRUECOLORMATTE` (int)
`Gmagick::IMGTYPE_COLORSEPARATION` (int)
`Gmagick::IMGTYPE_COLORSEPARATIONMATTE` (int)
`Gmagick::IMGTYPE_OPTIMIZE` (int)

Resolution constants
`Gmagick::RESOLUTION_UNDEFINED` (int)
`Gmagick::RESOLUTION_PIXELSPERINCH` (int)
`Gmagick::RESOLUTION_PIXELSPERCENTIMETER` (int)

Compression constants
`Gmagick::COMPRESSION_UNDEFINED` (int)
`Gmagick::COMPRESSION_NO` (int)
`Gmagick::COMPRESSION_BZIP` (int)
`Gmagick::COMPRESSION_FAX` (int)
`Gmagick::COMPRESSION_GROUP4` (int)
`Gmagick::COMPRESSION_JPEG` (int)
`Gmagick::COMPRESSION_JPEG2000` (int)
`Gmagick::COMPRESSION_LOSSLESSJPEG` (int)
`Gmagick::COMPRESSION_LZW` (int)
`Gmagick::COMPRESSION_RLE` (int)
`Gmagick::COMPRESSION_ZIP` (int)

Paint constants
`Gmagick::PAINT_POINT` (int)
`Gmagick::PAINT_REPLACE` (int)
`Gmagick::PAINT_FLOODFILL` (int)
`Gmagick::PAINT_FILLTOBORDER` (int)
`Gmagick::PAINT_RESET` (int)

Gravity constants
`Gmagick::GRAVITY_NORTHWEST` (int)
`Gmagick::GRAVITY_NORTH` (int)
`Gmagick::GRAVITY_NORTHEAST` (int)
`Gmagick::GRAVITY_WEST` (int)
`Gmagick::GRAVITY_CENTER` (int)
`Gmagick::GRAVITY_EAST` (int)
`Gmagick::GRAVITY_SOUTHWEST` (int)
`Gmagick::GRAVITY_SOUTH` (int)
`Gmagick::GRAVITY_SOUTHEAST` (int)

Stretch constants
`Gmagick::STRETCH_NORMAL` (int)
`Gmagick::STRETCH_ULTRACONDENSED` (int)
`Gmagick::STRETCH_CONDENSED` (int)
`Gmagick::STRETCH_SEMICONDENSED` (int)
`Gmagick::STRETCH_SEMIEXPANDED` (int)
`Gmagick::STRETCH_EXPANDED` (int)
`Gmagick::STRETCH_EXTRAEXPANDED` (int)
`Gmagick::STRETCH_ULTRAEXPANDED` (int)
`Gmagick::STRETCH_ANY` (int)

Align constants
`Gmagick::ALIGN_UNDEFINED` (int)
`Gmagick::ALIGN_LEFT` (int)
`Gmagick::ALIGN_CENTER` (int)
`Gmagick::ALIGN_RIGHT` (int)

Decoration constants
`Gmagick::DECORATION_NO` (int)
`Gmagick::DECORATION_UNDERLINE` (int)
`Gmagick::DECORATION_OVERLINE` (int)
`Gmagick::DECORATION_LINETROUGH` (int)

Noise constants
`Gmagick::NOISE_UNIFORM` (int)
`Gmagick::NOISE_GAUSSIAN` (int)
`Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN` (int)
`Gmagick::NOISE_IMPULSE` (int)
`Gmagick::NOISE_LAPLACIAN` (int)
`Gmagick::NOISE_POISSON` (int)

Channel constants
`Gmagick::CHANNEL_UNDEFINED` (int)
`Gmagick::CHANNEL_RED` (int)
`Gmagick::CHANNEL_GRAY` (int)
`Gmagick::CHANNEL_CYAN` (int)
`Gmagick::CHANNEL_GREEN` (int)
`Gmagick::CHANNEL_MAGENTA` (int)
`Gmagick::CHANNEL_BLUE` (int)
`Gmagick::CHANNEL_YELLOW` (int)
`Gmagick::CHANNEL_ALPHA` (int)
`Gmagick::CHANNEL_OPACITY` (int)
`Gmagick::CHANNEL_MATTE` (int)
`Gmagick::CHANNEL_BLACK` (int)
`Gmagick::CHANNEL_INDEX` (int)
`Gmagick::CHANNEL_ALL` (int)

Metric constants
`Gmagick::METRIC_UNDEFINED` (int)
`Gmagick::METRIC_MEANABSOLUTEERROR` (int)
`Gmagick::METRIC_MEANSQUAREERROR` (int)
`Gmagick::METRIC_PEAKABSOLUTEERROR` (int)
`Gmagick::METRIC_PEAKSIGNALTONOISERATIO` (int)
`Gmagick::METRIC_ROOTMEANSQUAREDERROR` (int)

Pixel constants
`Gmagick::PIXEL_CHAR` (int)
`Gmagick::PIXEL_DOUBLE` (int)
`Gmagick::PIXEL_FLOAT` (int)
`Gmagick::PIXEL_INTEGER` (int)
`Gmagick::PIXEL_LONG` (int)
`Gmagick::PIXEL_QUANTUM` (int)
`Gmagick::PIXEL_SHORT` (int)

Colorspace constants
`Gmagick::COLORSPACE_UNDEFINED` (int)
`Gmagick::COLORSPACE_RGB` (int)
`Gmagick::COLORSPACE_GRAY` (int)
`Gmagick::COLORSPACE_TRANSPARENT` (int)
`Gmagick::COLORSPACE_OHTA` (int)
`Gmagick::COLORSPACE_LAB` (int)
`Gmagick::COLORSPACE_XYZ` (int)
`Gmagick::COLORSPACE_YCBCR` (int)
`Gmagick::COLORSPACE_YCC` (int)
`Gmagick::COLORSPACE_YIQ` (int)
`Gmagick::COLORSPACE_YPBPR` (int)
`Gmagick::COLORSPACE_YUV` (int)
`Gmagick::COLORSPACE_CMYK` (int)
`Gmagick::COLORSPACE_SRGB` (int)
`Gmagick::COLORSPACE_HSB` (int)
`Gmagick::COLORSPACE_HSL` (int)
`Gmagick::COLORSPACE_HWB` (int)
`Gmagick::COLORSPACE_REC601LUMA` (int)
`Gmagick::COLORSPACE_REC709LUMA` (int)
`Gmagick::COLORSPACE_LOG` (int)

Virtual Pixel Method constants
`Gmagick::VIRTUALPIXELMETHOD_UNDEFINED` (int)
`Gmagick::VIRTUALPIXELMETHOD_BACKGROUND` (int)
`Gmagick::VIRTUALPIXELMETHOD_CONSTANT` (int)
`Gmagick::VIRTUALPIXELMETHOD_EDGE` (int)
`Gmagick::VIRTUALPIXELMETHOD_MIRROR` (int)
`Gmagick::VIRTUALPIXELMETHOD_TILE` (int)
`Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT` (int)

Preview constants
`Gmagick::PREVIEW_UNDEFINED` (int)
`Gmagick::PREVIEW_ROTATE` (int)
`Gmagick::PREVIEW_SHEAR` (int)
`Gmagick::PREVIEW_ROLL` (int)
`Gmagick::PREVIEW_HUE` (int)
`Gmagick::PREVIEW_SATURATION` (int)
`Gmagick::PREVIEW_BRIGHTNESS` (int)
`Gmagick::PREVIEW_GAMMA` (int)
`Gmagick::PREVIEW_SPIFF` (int)
`Gmagick::PREVIEW_DULL` (int)
`Gmagick::PREVIEW_GRAYSCALE` (int)
`Gmagick::PREVIEW_QUANTIZE` (int)
`Gmagick::PREVIEW_DESPECKLE` (int)
`Gmagick::PREVIEW_REDUCENOISE` (int)
`Gmagick::PREVIEW_ADDNOISE` (int)
`Gmagick::PREVIEW_SHARPEN` (int)
`Gmagick::PREVIEW_BLUR` (int)
`Gmagick::PREVIEW_THRESHOLD` (int)
`Gmagick::PREVIEW_EDGEDETECT` (int)
`Gmagick::PREVIEW_SPREAD` (int)
`Gmagick::PREVIEW_SOLARIZE` (int)
`Gmagick::PREVIEW_SHADE` (int)
`Gmagick::PREVIEW_RAISE` (int)
`Gmagick::PREVIEW_SEGMENT` (int)
`Gmagick::PREVIEW_SWIRL` (int)
`Gmagick::PREVIEW_IMPLODE` (int)
`Gmagick::PREVIEW_WAVE` (int)
`Gmagick::PREVIEW_OILPAINT` (int)
`Gmagick::PREVIEW_CHARCOALDRAWING` (int)
`Gmagick::PREVIEW_JPEG` (int)

Rendering Intent constants
`Gmagick::RENDERINGINTENT_UNDEFINED` (int)
`Gmagick::RENDERINGINTENT_SATURATION` (int)
`Gmagick::RENDERINGINTENT_PERCEPTUAL` (int)
`Gmagick::RENDERINGINTENT_ABSOLUTE` (int)
`Gmagick::RENDERINGINTENT_RELATIVE` (int)

Fillrule constants
`Gmagick::FILLRULE_UNDEFINED` (int)
`Gmagick::FILLRULE_EVENODD` (int)
`Gmagick::FILLRULE_NONZERO` (int)

Pathunit constants
`Gmagick::PATHUNITS_UNDEFINED` (int)
`Gmagick::PATHUNITS_USERSPACE` (int)
`Gmagick::PATHUNITS_USERSPACEONUSE` (int)
`Gmagick::PATHUNITS_OBJECTBOUNDINGBOX` (int)

Linecap constants
`Gmagick::LINECAP_UNDEFINED` (int)
`Gmagick::LINECAP_BUTT` (int)
`Gmagick::LINECAP_ROUND` (int)
`Gmagick::LINECAP_SQUARE` (int)

Line Join constants
`Gmagick::LINEJOIN_UNDEFINED` (int)
`Gmagick::LINEJOIN_MITER` (int)
`Gmagick::LINEJOIN_ROUND` (int)
`Gmagick::LINEJOIN_BEVEL` (int)

Resourcetype constants
`Gmagick::RESOURCETYPE_UNDEFINED` (int)
`Gmagick::RESOURCETYPE_AREA` (int)
`Gmagick::RESOURCETYPE_DISK` (int)
`Gmagick::RESOURCETYPE_FILE` (int)
`Gmagick::RESOURCETYPE_MAP` (int)
`Gmagick::RESOURCETYPE_MEMORY` (int)

Orientation constants
`Gmagick::ORIENTATION_UNDEFINED` (int)
`Gmagick::ORIENTATION_TOPLEFT` (int)
`Gmagick::ORIENTATION_TOPRIGHT` (int)
`Gmagick::ORIENTATION_BOTTOMRIGHT` (int)
`Gmagick::ORIENTATION_BOTTOMLEFT` (int)
`Gmagick::ORIENTATION_LEFTTOP` (int)
`Gmagick::ORIENTATION_RIGHTTOP` (int)
`Gmagick::ORIENTATION_RIGHTBOTTOM` (int)
`Gmagick::ORIENTATION_LEFTBOTTOM` (int)

Interlace constants
`Gmagick::INTERLACE_UNDEFINED` (int)
`Gmagick::INTERLACE_NO` (int)
`Gmagick::INTERLACE_NONE` (int)
`Gmagick::INTERLACE_LINE` (int)
`Gmagick::INTERLACE_PLANE` (int)
`Gmagick::INTERLACE_PARTITION` (int)

# Examples

The following shows some common Gmagick image operations.

Example #1 Gmagick Example

`<?php
//Instantiate a new Gmagick object
$image = new Gmagick('example.jpg');
//Make thumbnail from image loaded. 0 for either axes preserves aspect ratio
$image->thumbnailimage(100, 0);
//Create a border around the image, then simulate how the image will look like as an oil painting
//Notice the chaining of mutator methods which is supported in gmagick
$image->borderimage("yellow", 8, 8)->oilpaintimage(0.3);
//Write the current image at the current state to a file
$image->write('example_thumbnail.jpg');
?>`

# The Gmagick class

(PECL gmagick >= Unknown)

## Introduction

## Class synopsis

class Gmagick {
/* Methods */
public __construct(string `$filename` = ?)
public addimage(Gmagick `$source`): Gmagick
public addnoiseimage(int `$noise_type`): Gmagick
public annotateimage(
GmagickDraw `$GmagickDraw`,
float `$x`,
float `$y`,
float `$angle`,
string `$text`
): Gmagick
public blurimage(float `$radius`, float `$sigma`, int `$channel` = ?): Gmagick
public borderimage(GmagickPixel `$color`, int `$width`, int `$height`): Gmagick
public charcoalimage(float `$radius`, float `$sigma`): Gmagick
public chopimage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): Gmagick
public clear(): Gmagick
public commentimage(string `$comment`): Gmagick
public compositeimage(
Gmagick `$source`,
int `$COMPOSE`,
int `$x`,
int `$y`
): Gmagick
public cropimage(
int `$width` ,
int `$height` ,
int `$x`,
int `$y`
): Gmagick
public cropthumbnailimage(int `$width`, int `$height`): Gmagick
public current(): Gmagick
public cyclecolormapimage(int `$displace`): Gmagick
public deconstructimages(): Gmagick
public despeckleimage(): Gmagick
public destroy(): bool
public drawimage(GmagickDraw `$GmagickDraw`): Gmagick
public edgeimage(float `$radius`): Gmagick
public embossimage(float `$radius`, float `$sigma`): Gmagick
public enhanceimage(): Gmagick
public equalizeimage(): Gmagick
public flipimage(): Gmagick
public flopimage(): Gmagick
public frameimage(
GmagickPixel `$color`,
int `$width`,
int `$height`,
int `$inner_bevel`,
int `$outer_bevel`
): Gmagick
public gammaimage(float `$gamma`): Gmagick
public getcopyright(): string
public getfilename(): string
public getimagebackgroundcolor(): GmagickPixel
public getimageblueprimary(): array
public getimagebordercolor(): GmagickPixel
public getimagechanneldepth(int `$channel_type`): int
public getimagecolors(): int
public getimagecolorspace(): int
public getimagecompose(): int
public getimagedelay(): int
public getimagedepth(): int
public getimagedispose(): int
public getimageextrema(): array
public getimagefilename(): string
public getimageformat(): string
public getimagegamma(): float
public getimagegreenprimary(): array
public getimageheight(): int
public getimagehistogram(): array
public getimageindex(): int
public getimageinterlacescheme(): int
public getimageiterations(): int
public getimagematte(): int
public getimagemattecolor(): GmagickPixel
public getimageprofile(string `$name`): string
public getimageredprimary(): array
public getimagerenderingintent(): int
public getimageresolution(): array
public getimagescene(): int
public getimagesignature(): string
public getimagetype(): int
public getimageunits(): int
public getimagewhitepoint(): array
public getimagewidth(): int
public getpackagename(): string
public getquantumdepth(): array
public getreleasedate(): string
public getsamplingfactors(): array
public getsize(): array
public getversion(): array
public hasnextimage(): mixed
public haspreviousimage(): mixed
public implodeimage(float `$radius`): mixed
public labelimage(string `$label`): mixed
public levelimage(
float `$blackPoint`,
float `$gamma`,
float `$whitePoint`,
int `$channel` = Gmagick::CHANNEL_DEFAULT
): mixed
public magnifyimage(): mixed
public mapimage(gmagick `$gmagick`, bool `$dither`): Gmagick
public medianfilterimage(float `$radius`): void
public minifyimage(): Gmagick
public modulateimage(float `$brightness`, float `$saturation`, float `$hue`): Gmagick
public motionblurimage(float `$radius`, float `$sigma`, float `$angle`): Gmagick
public newimage(
int `$width`,
int `$height`,
string `$background`,
string `$format` = ?
): Gmagick
public nextimage(): bool
public normalizeimage(int `$channel` = ?): Gmagick
public oilpaintimage( float `$radius` ): Gmagick
public previousimage(): bool
public profileimage(string `$name`, string `$profile`): Gmagick
public quantizeimage(
int `$numColors`,
int `$colorspace`,
int `$treeDepth`,
bool `$dither`,
bool `$measureError`
): Gmagick
public quantizeimages(
int `$numColors`,
int `$colorspace`,
int `$treeDepth`,
bool `$dither`,
bool `$measureError`
): Gmagick
public queryfontmetrics(GmagickDraw `$draw`, string `$text`): array
public queryfonts(string `$pattern` = "*"): array
public queryformats(string `$pattern` = "*"): array
public radialblurimage(float `$angle`, int `$channel` = Gmagick::CHANNEL_DEFAULT): Gmagick
public raiseimage(
int `$width`,
int `$height`,
int `$x`,
int `$y`,
bool `$raise`
): Gmagick
public read(string `$filename`): Gmagick
public readimage(string `$filename`): Gmagick
public readimageblob(string `$imageContents`, string `$filename` = ?): Gmagick
public readimagefile(resource `$fp`, string `$filename` = ?): Gmagick
public reducenoiseimage(float `$radius`): Gmagick
public removeimage(): Gmagick
public removeimageprofile(string `$name`): string
public resampleimage(
float `$xResolution`,
float `$yResolution`,
int `$filter`,
float `$blur`
): Gmagick
public resizeimage(
int `$width`,
int `$height`,
int `$filter`,
float `$blur`,
bool `$fit` = `false`
): Gmagick
public rollimage(int `$x`, int `$y`): Gmagick
public rotateimage(mixed `$color`, float `$degrees`): Gmagick
public scaleimage(int `$width`, int `$height`, bool `$fit` = `false`): Gmagick
public separateimagechannel(int `$channel`): Gmagick
setCompressionQuality( int `$quality` ): Gmagick
public setfilename(string `$filename`): Gmagick
public setimagebackgroundcolor(GmagickPixel `$color`): Gmagick
public setimageblueprimary(float `$x`, float `$y`): Gmagick
public setimagebordercolor(GmagickPixel `$color`): Gmagick
public setimagechanneldepth(int `$channel`, int `$depth`): Gmagick
public setimagecolorspace(int `$colorspace`): Gmagick
public setimagecompose(int `$composite`): Gmagick
public setimagedelay(int `$delay`): Gmagick
public setimagedepth(int `$depth`): Gmagick
public setimagedispose(int `$disposeType`): Gmagick
public setimagefilename(string `$filename`): Gmagick
public setimageformat(string `$imageFormat`): Gmagick
public setimagegamma(float `$gamma`): Gmagick
public setimagegreenprimary(float `$x`, float `$y`): Gmagick
public setimageindex(int `$index`): Gmagick
public setimageinterlacescheme(int `$interlace`): Gmagick
public setimageiterations(int `$iterations`): Gmagick
public setimageprofile(string `$name`, string `$profile`): Gmagick
public setimageredprimary(float `$x`, float `$y`): Gmagick
public setimagerenderingintent(int `$rendering_intent`): Gmagick
public setimageresolution(float `$xResolution`, float `$yResolution`): Gmagick
public setimagescene(int `$scene`): Gmagick
public setimagetype(int `$imgType`): Gmagick
public setimageunits(int `$resolution`): Gmagick
public setimagewhitepoint(float `$x`, float `$y`): Gmagick
public setsamplingfactors(array `$factors`): Gmagick
public setsize(int `$columns`, int `$rows`): Gmagick
public shearimage(mixed `$color`, float `$xShear`, float `$yShear`): Gmagick
public solarizeimage(int `$threshold`): Gmagick
public spreadimage(float `$radius`): Gmagick
public stripimage(): Gmagick
public swirlimage(float `$degrees`): Gmagick
public thumbnailimage(int `$width`, int `$height`, bool `$fit` = `false`): Gmagick
public trimimage(float `$fuzz`): Gmagick
public writeimage(string `$filename`, bool `$all_frames` = `false`): Gmagick
}

# Gmagick::addimage

(PECL gmagick >= Unknown)

Gmagick::addimage — Adds new image to Gmagick object image list

### Description

public Gmagick::addimage(Gmagick `$source`): Gmagick

Adds new image to Gmagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

### Parameters

`source`
  The source Gmagick object

### Return Values

The Gmagick object with image added

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::addnoiseimage

(PECL gmagick >= Unknown)

Gmagick::addnoiseimage — Adds random noise to the image

### Description

public Gmagick::addnoiseimage(int `$noise_type`): Gmagick

Adds random noise to the image.

### Parameters

`noise_type`
  The type of the noise. Refer to this list of noise constants.

### Return Values

The Gmagick object with noise added.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::annotateimage

(PECL gmagick >= Unknown)

Gmagick::annotateimage — Annotates an image with text

### Description

public Gmagick::annotateimage(
GmagickDraw `$GmagickDraw`,
float `$x`,
float `$y`,
float `$angle`,
string `$text`
): Gmagick

Annotates an image with text.

### Parameters

`GmagickDraw`
  The GmagickDraw object that contains settings for drawing the text.
`x`
  Horizontal offset in pixels to the left of text.
`y`
  Vertical offset in pixels to the baseline of text.
`angle`
  The angle at which to write the text.
`text`
  The string to draw.

### Return Values

The Gmagick object with annotation made.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::blurimage

(PECL gmagick >= Unknown)

Gmagick::blurimage — Adds blur filter to image

### Description

public Gmagick::blurimage(float `$radius`, float `$sigma`, int `$channel` = ?): Gmagick

Adds blur filter to image.

### Parameters

`radius`
  Blur radius
`sigma`
  Standard deviation

### Return Values

The blurred Gmagick object

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::borderimage

(PECL gmagick >= Unknown)

Gmagick::borderimage — Surrounds the image with a border

### Description

public Gmagick::borderimage(GmagickPixel `$color`, int `$width`, int `$height`): Gmagick

Surrounds the image with a border of the color defined by the bordercolor GmagickPixel object or a color string.

### Parameters

`color`
  GmagickPixel object or a string containing the border color.
`width`
  Border width.
`height`
  Border height.

### Return Values

The Gmagick object with border defined.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::charcoalimage

(PECL gmagick >= Unknown)

Gmagick::charcoalimage — Simulates a charcoal drawing

### Description

public Gmagick::charcoalimage(float `$radius`, float `$sigma`): Gmagick

Simulates a charcoal drawing.

### Parameters

`radius`
  The radius of the Gaussian, in pixels, not counting the center pixel.
`sigma`
  The standard deviation of the Gaussian, in pixels.

### Return Values

The Gmagick object with charcoal simulation.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::chopimage

(PECL gmagick >= Unknown)

Gmagick::chopimage — Removes a region of an image and trims

### Description

public Gmagick::chopimage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): Gmagick

Removes a region of an image and collapses the image to occupy the removed portion.

### Parameters

`width`
  Width of the chopped area.
`height`
  Height of the chopped area.
`x`
  X origo of the chopped area.
`y`
  Y origo of the chopped area.

### Return Values

The chopped Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

### Description

public Gmagick::clear(): Gmagick

Clears all resources associated to Gmagick object.

### Parameters

This function has no parameters.

### Return Values

The cleared Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::commentimage

(PECL gmagick >= Unknown)

Gmagick::commentimage — Adds a comment to your image

### Description

public Gmagick::commentimage(string `$comment`): Gmagick

Adds a comment to your image.

### Parameters

`comment`
  The comment to add.

### Return Values

The Gmagick object with comment added.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::compositeimage

(PECL gmagick >= Unknown)

Gmagick::compositeimage — Composite one image onto another

### Description

public Gmagick::compositeimage(
Gmagick `$source`,
int `$COMPOSE`,
int `$x`,
int `$y`
): Gmagick

Composite one image onto another at the specified offset.

### Parameters

`source`
  Gmagick object which holds the composite image.
`COMPOSE`
  Composite operator.
`x`
  The column offset of the composited image.
`y`
  The row offset of the composited image.

### Return Values

The Gmagick object with compositions.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::__construct

(PECL gmagick >= Unknown)

Gmagick::__construct — The Gmagick constructor

### Description

public Gmagick::__construct(string `$filename` = ?)

The Gmagick constructor.

### Parameters

`filename`
  The path to an image to load or array of paths.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::cropimage

(PECL gmagick >= Unknown)

Gmagick::cropimage — Extracts a region of the image

### Description

public Gmagick::cropimage(
int `$width` ,
int `$height` ,
int `$x`,
int `$y`
): Gmagick

Extracts a region of the image.

### Parameters

`width`
  The width of the crop.
`height`
  The height of the crop.
`x`
  The X coordinate of the cropped region's top left corner.
`y`
  The Y coordinate of the cropped region's top left corner.

### Return Values

The cropped Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::cropthumbnailimage

(PECL gmagick >= Unknown)

Gmagick::cropthumbnailimage — Creates a crop thumbnail

### Description

public Gmagick::cropthumbnailimage(int `$width`, int `$height`): Gmagick

Creates a fixed size thumbnail by first scaling the image down and cropping a specified area from the center.

### Parameters

`width`
  The width of the thumbnail.
`height`
  The Height of the thumbnail.

### Return Values

The cropped Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

### Description

public Gmagick::current(): Gmagick

Returns reference to the current gmagick object with image pointer at the correct sequence.

### Parameters

This function has no parameters.

### Return Values

Returns self on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::cyclecolormapimage

(PECL gmagick >= Unknown)

Gmagick::cyclecolormapimage — Displaces an image's colormap

### Description

public Gmagick::cyclecolormapimage(int `$displace`): Gmagick

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

### Parameters

`displace`
  The amount to displace the colormap.

### Return Values

Returns self on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

### Description

public Gmagick::deconstructimages(): Gmagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

### Parameters

This function has no parameters.

### Return Values

Returns a new Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

### Description

public Gmagick::despeckleimage(): Gmagick

Reduces the speckle noise in an image while preserving the edges of the original image.

### Parameters

This function has no parameters.

### Return Values

The despeckled Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

### Examples

Example #1 Gmagick::despeckleimage() example

`<?php
/* ... */
?>`

The above example will output something similar to:

    ...

# Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

### Description

public Gmagick::destroy(): bool

Destroys the Gmagick object and frees all resources associated with it

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::drawimage

(PECL gmagick >= Unknown)

Gmagick::drawimage — Renders the GmagickDraw object on the current image

### Description

public Gmagick::drawimage(GmagickDraw `$GmagickDraw`): Gmagick

Renders the GmagickDraw object on the current image.

### Parameters

`GmagickDraw`
  The drawing operations to render on the image.

### Return Values

The drawn Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::edgeimage

(PECL gmagick >= Unknown)

Gmagick::edgeimage — Enhance edges within the image

### Description

public Gmagick::edgeimage(float `$radius`): Gmagick

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

### Parameters

`radius`
  The radius of the operation.

### Return Values

The Gmagick object with edges enhanced.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::embossimage

(PECL gmagick >= Unknown)

Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect

### Description

public Gmagick::embossimage(float `$radius`, float `$sigma`): Gmagick

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

### Parameters

`radius`
  The radius of the effect.
`sigma`
  The sigma of the effect.

### Return Values

The embossed Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

### Description

public Gmagick::enhanceimage(): Gmagick

Applies a digital filter that improves the quality of a noisy image.

### Parameters

This function has no parameters.

### Return Values

The enhanced Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

### Description

public Gmagick::equalizeimage(): Gmagick

Equalizes the image histogram.

### Parameters

This function has no parameters.

### Return Values

The equalized Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

### Description

public Gmagick::flipimage(): Gmagick

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

### Parameters

This function has no parameters.

### Return Values

The flipped Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

### See Also

- Gmagick::flopimage() - Creates a horizontal mirror image

# Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — Creates a horizontal mirror image

### Description

public Gmagick::flopimage(): Gmagick

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

### Parameters

This function has no parameters.

### Return Values

The flopped Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

### See Also

- Gmagick::flipimage() - Creates a vertical mirror image

# Gmagick::frameimage

(PECL gmagick >= Unknown)

Gmagick::frameimage — Adds a simulated three-dimensional border

### Description

public Gmagick::frameimage(
GmagickPixel `$color`,
int `$width`,
int `$height`,
int `$inner_bevel`,
int `$outer_bevel`
): Gmagick

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

### Parameters

`color`
  GmagickPixel object or a float representing the matte color.
`width`
  The width of the border.
`height`
  The height of the border.
`inner_bevel`
  The inner bevel width.
`outer_bevel`
  The outer bevel width.

### Return Values

The framed Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::gammaimage

(PECL gmagick >= Unknown)

Gmagick::gammaimage — Gamma-corrects an image

### Description

public Gmagick::gammaimage(float `$gamma`): Gmagick

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

### Parameters

`gamma`
  The amount of gamma-correction.

### Return Values

The gamma corrected Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

### Description

public Gmagick::getcopyright(): string

Returns the GraphicsMagick API copyright as a string.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

### Description

public Gmagick::getfilename(): string

Returns the filename associated with an image sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a string on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

### Description

public Gmagick::getimagebackgroundcolor(): GmagickPixel

Returns the image background color.

### Parameters

This function has no parameters.

### Return Values

Returns an GmagickPixel set to the background color of the image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

### Description

public Gmagick::getimageblueprimary(): array

Returns the chromaticity blue primary point for the image.

### Parameters

`x`
  The chromaticity blue primary x-point.
`y`
  The chromaticity blue primary y-point.

### Return Values

Array consisting of "x" and "y" coordinates of point.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

### Description

public Gmagick::getimagebordercolor(): GmagickPixel

Returns the image border color.

### Parameters

This function has no parameters.

### Return Values

GmagickPixel object representing the color of the border.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::getimagechanneldepth — Gets the depth for a particular image channel

### Description

public Gmagick::getimagechanneldepth(int `$channel_type`): int

Gets the depth for a particular image channel.

### Parameters

This function has no parameters.

### Return Values

Depth of image channel

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

### Description

public Gmagick::getimagecolors(): int

Returns the color of the specified colormap index.

### Parameters

This function has no parameters.

### Return Values

The number of colors in image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

### Description

public Gmagick::getimagecolorspace(): int

Gets the image colorspace.

### Parameters

This function has no parameters.

### Return Values

Colorspace

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

### Description

public Gmagick::getimagecompose(): int

Returns the composite operator associated with the image.

### Parameters

This function has no parameters.

### Return Values

Returns the composite operator associated with the image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

### Description

public Gmagick::getimagedelay(): int

Gets the image delay

### Parameters

This function has no parameters.

### Return Values

Returns the composite operator associated with the image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

### Description

public Gmagick::getimagedepth(): int

Gets the depth of the image.

### Parameters

This function has no parameters.

### Return Values

Image depth

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

### Description

public Gmagick::getimagedispose(): int

Gets the image disposal method

### Parameters

This function has no parameters.

### Return Values

Returns the dispose method on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

### Description

public Gmagick::getimageextrema(): array

Returns an associative array with the keys "min" and "max". Throws an GmagickException on error.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the keys "min" and "max".

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

### Description

public Gmagick::getimagefilename(): string

Returns the filename of a particular image in a sequence

### Parameters

This function has no parameters.

### Return Values

Returns a string with the filename of the image

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

### Description

public Gmagick::getimageformat(): string

Returns the format of a particular image in a sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the image format on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

### Description

public Gmagick::getimagegamma(): float

Gets the image gamma

### Parameters

This function has no parameters.

### Return Values

Returns the image gamma on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

### Description

public Gmagick::getimagegreenprimary(): array

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns an array with the keys "x" and "y" on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

### Description

public Gmagick::getimageheight(): int

Returns the image height

### Parameters

This function has no parameters.

### Return Values

Returns the image height in pixels.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

### Description

public Gmagick::getimagehistogram(): array

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

### Parameters

This function has no parameters.

### Return Values

Returns the image histogram as an array of GmagickPixel objects.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

### Description

public Gmagick::getimageindex(): int

Returns the index of the current active image within the Gmagick object.

### Parameters

This function has no parameters.

### Return Values

Index of current active image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

### Description

public Gmagick::getimageinterlacescheme(): int

Gets the image interlace scheme.

### Parameters

This function has no parameters.

### Return Values

Returns the interlace scheme as an integer on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

### Description

public Gmagick::getimageiterations(): int

Gets the image iterations.

### Parameters

This function has no parameters.

### Return Values

Returns the image iterations as an integer.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Check if the image has a matte channel

### Description

public Gmagick::getimagematte(): int

Returns `true` if the image has a matte channel, otherwise `false`.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the image has a matte channel, otherwise `false`.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

### Description

public Gmagick::getimagemattecolor(): GmagickPixel

Returns GmagickPixel object on success. Throw an GmagickException on error.

### Parameters

This function has no parameters.

### Return Values

Returns GmagickPixel object on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageprofile

(PECL gmagick >= Unknown)

Gmagick::getimageprofile — Returns the named image profile

### Description

public Gmagick::getimageprofile(string `$name`): string

Returns the named image profile.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the image profile.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

### Description

public Gmagick::getimageredprimary(): array

Returns the chromaticity red primary point as an array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y".

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

### Description

public Gmagick::getimagerenderingintent(): int

Gets the image rendering intent

### Parameters

This function has no parameters.

### Return Values

Extracts a region of the image and returns it as a new wand

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

### Description

public Gmagick::getimageresolution(): array

Returns the resolution as an array.

### Parameters

This function has no parameters.

### Return Values

Returns the resolution as an array.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

### Description

public Gmagick::getimagescene(): int

Gets the image scene.

### Parameters

This function has no parameters.

### Return Values

Returns the image scene.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

### Description

public Gmagick::getimagesignature(): string

Generates an SHA-256 message digest for the image pixel stream.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the SHA-256 hash of the file.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type

### Description

public Gmagick::getimagetype(): int

Gets the potential image type.

### Parameters

This function has no parameters.

### Return Values

Returns the potential image type.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

### Description

public Gmagick::getimageunits(): int

Gets the image units of resolution.

### Parameters

This function has no parameters.

### Return Values

Returns the image units of resolution.

# Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

### Description

public Gmagick::getimagewhitepoint(): array

Returns the chromaticity white point as an associative array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

### Description

public Gmagick::getimagewidth(): int

Returns the width of the image.

### Parameters

This function has no parameters.

### Return Values

Returns the image width.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name

### Description

public Gmagick::getpackagename(): string

Returns the GraphicsMagick package name.

### Parameters

This function has no parameters.

### Return Values

Returns the GraphicsMagick package name as a string.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string

### Description

public Gmagick::getquantumdepth(): array

Returns the Gmagick quantum depth as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the Gmagick quantum depth as a string.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string

### Description

public Gmagick::getreleasedate(): string

Returns the GraphicsMagick release date as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the GraphicsMagick release date as a string.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor

### Description

public Gmagick::getsamplingfactors(): array

Gets the horizontal and vertical sampling factor.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

### Description

public Gmagick::getsize(): array

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

### Parameters

This function has no parameters.

### Return Values

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

### Description

public Gmagick::getversion(): array

Returns the GraphicsMagick API version as a string and as a number.

### Parameters

This function has no parameters.

### Return Values

Returns the GraphicsMagick API version as a string and as a number.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

### Description

public Gmagick::hasnextimage(): mixed

Returns `true` if the object has more images when traversing the list in the forward direction.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the object has more images when traversing the list in the forward direction, returns `false` if there are none.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

### Description

public Gmagick::haspreviousimage(): mixed

Returns `true` if the object has more images when traversing the list in the reverse direction.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the object has more images when traversing the list in the reverse direction, returns `false` if there are none.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::implodeimage

(PECL gmagick >= Unknown)

Gmagick::implodeimage — Creates a new image as a copy

### Description

public Gmagick::implodeimage(float `$radius`): mixed

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

### Parameters

`radius`
  The radius of the implode.

### Return Values

Returns imploded Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::labelimage

(PECL gmagick >= Unknown)

Gmagick::labelimage — Adds a label to an image

### Description

public Gmagick::labelimage(string `$label`): mixed

Adds a label to an image.

### Parameters

`label`
  The label to add

### Return Values

Gmagick with label.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::levelimage

(PECL gmagick >= Unknown)

Gmagick::levelimage — Adjusts the levels of an image

### Description

public Gmagick::levelimage(
float `$blackPoint`,
float `$gamma`,
float `$whitePoint`,
int `$channel` = Gmagick::CHANNEL_DEFAULT
): mixed

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

### Parameters

`blackPoint`
  The image black point.
`gamma`
  The gamma value.
`whitePoint`
  The image white point.
`channel`
  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Gmagick object with image leveled.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

### Description

public Gmagick::magnifyimage(): mixed

Conveniently scales an image proportionally to twice its original size.

### Parameters

This function has no parameters.

### Return Values

Magnified Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::mapimage

(PECL gmagick >= Unknown)

Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image

### Description

public Gmagick::mapimage(gmagick `$gmagick`, bool `$dither`): Gmagick

Replaces the colors of an image with the closest color from a reference image.

### Parameters

`gmagick`
  The reference image.
`dither`
  Set this integer value to something other than zero to dither the mapped image.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::medianfilterimage

(PECL gmagick >= Unknown)

Gmagick::medianfilterimage — Applies a digital filter

### Description

public Gmagick::medianfilterimage(float `$radius`): void

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

### Parameters

`radius`
  The radius of the pixel neighborhood.

### Return Values

Gmagick object with median filter applied.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

### Description

public Gmagick::minifyimage(): Gmagick

A convenient method that scales an image proportionally to one-half its original size.

### Parameters

This function has no parameters.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::modulateimage

(PECL gmagick >= Unknown)

Gmagick::modulateimage — Control the brightness, saturation, and hue

### Description

public Gmagick::modulateimage(float `$brightness`, float `$saturation`, float `$hue`): Gmagick

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

### Parameters

`brightness`
  The percent change in brighness (-100 thru +100).
`saturation`
  The percent change in saturation (-100 thru +100)
`hue`
  The percent change in hue (-100 thru +100)

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::motionblurimage

(PECL gmagick >= Unknown)

Gmagick::motionblurimage — Simulates motion blur

### Description

public Gmagick::motionblurimage(float `$radius`, float `$sigma`, float `$angle`): Gmagick

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Gmagick::motionblurimage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

### Parameters

`radius`
  The radius of the Gaussian, in pixels, not counting the center pixel.
`sigma`
  The standard deviation of the Gaussian, in pixels.
`angle`
  Apply the effect along this angle.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::newimage

(PECL gmagick >= Unknown)

Gmagick::newimage — Creates a new image

### Description

public Gmagick::newimage(
int `$width`,
int `$height`,
string `$background`,
string `$format` = ?
): Gmagick

Creates a new image with the specified background color.

### Parameters

`width`
  Width of the new image.
`height`
  Height of the new image.
`background`
  The background color used for this image (as float).
`format`
  Image format.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

### Description

public Gmagick::nextimage(): bool

Associates the next image in the image list with an Gmagick object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::normalizeimage

(PECL gmagick >= Unknown)

Gmagick::normalizeimage — Enhances the contrast of a color image

### Description

public Gmagick::normalizeimage(int `$channel` = ?): Gmagick

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

### Parameters

`channel`
  Identify which channel to normalize.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::oilpaintimage

(PECL gmagick >= Unknown)

Gmagick::oilpaintimage — Simulates an oil painting

### Description

public Gmagick::oilpaintimage( float `$radius` ): Gmagick

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

### Parameters

`radius`
  The radius of the circular neighborhood.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

### Description

public Gmagick::previousimage(): bool

Associates the previous image in an image list with the Gmagick object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success or `false` on failure.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::profileimage

(PECL gmagick >= Unknown)

Gmagick::profileimage — Adds or removes a profile from an image

### Description

public Gmagick::profileimage(string `$name`, string `$profile`): Gmagick

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is `null`, it is removed from the image otherwise added. Use a name of `*` and a profile of `null` to remove all profiles from the image.

### Parameters

`name`
  Name of profile to add or remove: ICC, IPTC, or generic profile.
`profile`
  The profile.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::quantizeimage

(PECL gmagick >= Unknown)

Gmagick::quantizeimage — Analyzes the colors within a reference image

### Description

public Gmagick::quantizeimage(
int `$numColors`,
int `$colorspace`,
int `$treeDepth`,
bool `$dither`,
bool `$measureError`
): Gmagick

Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

### Parameters

`numColors`
  The number of colors.
`colorspace`
  Perform color reduction in this colorspace, typically RGBColorspace.
`treeDepth`
  Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.
`dither`
  A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.
`measureError`
  A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::quantizeimages

(PECL gmagick >= Unknown)

Gmagick::quantizeimages — The quantizeimages purpose

### Description

public Gmagick::quantizeimages(
int `$numColors`,
int `$colorspace`,
int `$treeDepth`,
bool `$dither`,
bool `$measureError`
): Gmagick

Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

### Parameters

`numColors`
  The number of colors.
`colorspace`
  Perform color reduction in this colorspace, typically RGBColorspace.
`treeDepth`
  Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.
`dither`
  A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.
`measureError`
  A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::queryfontmetrics

(PECL gmagick >= Unknown)

Gmagick::queryfontmetrics — Returns an array representing the font metrics

### Description

public Gmagick::queryfontmetrics(GmagickDraw `$draw`, string `$text`): array

MagickQueryFontMetrics() returns an array representing the font metrics.

### Parameters

This function has no parameters.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::queryfonts

(PECL gmagick >= Unknown)

Gmagick::queryfonts — Returns the configured fonts

### Description

public Gmagick::queryfonts(string `$pattern` = "*"): array

Returns fonts supported by Gmagick.

### Parameters

This function has no parameters.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::queryformats

(PECL gmagick >= Unknown)

Gmagick::queryformats — Returns formats supported by Gmagick

### Description

public Gmagick::queryformats(string `$pattern` = "*"): array

Returns formats supported by Gmagick.

### Parameters

`pattern`
  Specifies a string containing a pattern.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::radialblurimage

(PECL gmagick >= Unknown)

Gmagick::radialblurimage — Radial blurs an image

### Description

public Gmagick::radialblurimage(float `$angle`, int `$channel` = Gmagick::CHANNEL_DEFAULT): Gmagick

Radial blurs an image.

### Parameters

`angle`
  The angle of the blur in degrees.
`channel`
  Related channel.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::raiseimage

(PECL gmagick >= Unknown)

Gmagick::raiseimage — Creates a simulated 3d button-like effect

### Description

public Gmagick::raiseimage(
int `$width`,
int `$height`,
int `$x`,
int `$y`,
bool `$raise`
): Gmagick

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

### Parameters

`width`
  Width of the area to raise.
`height`
  Height of the area to raise.
`x`
  X coordinate.
`y`
  Y coordinate.
`raise`
  A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::read

(PECL gmagick >= Unknown)

Gmagick::read — Reads image from filename

### Description

public Gmagick::read(string `$filename`): Gmagick

Reads image from filename.

### Parameters

`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::readimage

(PECL gmagick >= Unknown)

Gmagick::readimage — Reads image from filename

### Description

public Gmagick::readimage(string `$filename`): Gmagick

Reads image from filename.

### Parameters

`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::readimageblob

(PECL gmagick >= Unknown)

Gmagick::readimageblob — Reads image from a binary string

### Description

public Gmagick::readimageblob(string `$imageContents`, string `$filename` = ?): Gmagick

Reads image from a binary string.

### Parameters

`imageContents`
  Content of image.
`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::readimagefile

(PECL gmagick >= Unknown)

Gmagick::readimagefile — The readimagefile purpose

### Description

public Gmagick::readimagefile(resource `$fp`, string `$filename` = ?): Gmagick

Reads an image or image sequence from an open file descriptor.

### Parameters

`fp`
  The file descriptor.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::reducenoiseimage

(PECL gmagick >= Unknown)

Gmagick::reducenoiseimage — Smooths the contours of an image

### Description

public Gmagick::reducenoiseimage(float `$radius`): Gmagick

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Gmagick::reducenoiseimage() selects a suitable radius for you.

### Parameters

`radius`
  The radius of the pixel neighborhood.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

### Description

public Gmagick::removeimage(): Gmagick

Removes an image from the image list.

### Parameters

This function has no parameters.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::removeimageprofile

(PECL gmagick >= Unknown)

Gmagick::removeimageprofile — Removes the named image profile and returns it

### Description

public Gmagick::removeimageprofile(string `$name`): string

Removes the named image profile and returns it.

### Parameters

`name`
  Name of profile to return: ICC, IPTC, or generic profile.

### Return Values

The named profile.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::resampleimage

(PECL gmagick >= Unknown)

Gmagick::resampleimage — Resample image to desired resolution

### Description

public Gmagick::resampleimage(
float `$xResolution`,
float `$yResolution`,
int `$filter`,
float `$blur`
): Gmagick

Resample image to desired resolution.

### Parameters

`xResolution`
  The new image x resolution.
`yResolution`
  The new image y resolution.
`filter`
  Image filter to use.
`blur`
  The blur factor where larger than 1 is blurry, smaller than 1 is sharp.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::resizeimage

(PECL gmagick >= Unknown)

Gmagick::resizeimage — Scales an image

### Description

public Gmagick::resizeimage(
int `$width`,
int `$height`,
int `$filter`,
float `$blur`,
bool `$fit` = `false`
): Gmagick

Scales an image to the desired dimensions with a filter.

### Parameters

`width`
  The number of columns in the scaled image.
`height`
  The number of rows in the scaled image.
`filter`
  Image filter to use.
`blur`
  The blur factor where larger than 1 is blurry, lesser than 1 is sharp.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::rollimage

(PECL gmagick >= Unknown)

Gmagick::rollimage — Offsets an image

### Description

public Gmagick::rollimage(int `$x`, int `$y`): Gmagick

Offsets an image as defined by x and y.

### Parameters

`x`
  The x offset.
`y`
  The y offset.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::rotateimage

(PECL gmagick >= Unknown)

Gmagick::rotateimage — Rotates an image

### Description

public Gmagick::rotateimage(mixed `$color`, float `$degrees`): Gmagick

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

### Parameters

`color`
  The background pixel.
`degrees`
  The number of degrees to rotate the image.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::scaleimage

(PECL gmagick >= Unknown)

Gmagick::scaleimage — Scales the size of an image

### Description

public Gmagick::scaleimage(int `$width`, int `$height`, bool `$fit` = `false`): Gmagick

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

### Parameters

`width`
  The number of columns in the scaled image.
`height`
  The number of rows in the scaled image.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

### Description

public Gmagick::separateimagechannel(int `$channel`): Gmagick

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

### Parameters

`channel`
  One of the Channel constant (`Gmagick::CHANNEL_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setCompressionQuality

(No version information available, might only be in Git)

Gmagick::setCompressionQuality — Sets the object's default compression quality

### Description

Gmagick::setCompressionQuality( int `$quality` ): Gmagick

Sets the object's default compression quality.

### Parameters

`quality`
  The GraphicsMagick default value is 75.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

### Examples

Example #1 Gmagick::setCompressionQuality()

`<?php
$gm = new Gmagick();
$gm->read("magick:rose");
$gm->setCompressionQuality(2);
?>`

# Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

### Description

public Gmagick::setfilename(string `$filename`): Gmagick

Sets the filename before you read or write an image file.

### Parameters

`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::setimagebackgroundcolor — Sets the image background color

### Description

public Gmagick::setimagebackgroundcolor(GmagickPixel `$color`): Gmagick

Sets the image background color.

### Parameters

`color`
  The background pixel wand.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point

### Description

public Gmagick::setimageblueprimary(float `$x`, float `$y`): Gmagick

Sets the image chromaticity blue primary point.

### Parameters

`x`
  The blue primary x-point.
`y`
  The blue primary y-point.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::setimagebordercolor — Sets the image border color

### Description

public Gmagick::setimagebordercolor(GmagickPixel `$color`): Gmagick

Sets the image border color.

### Parameters

`color`
  The border pixel wand.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::setimagechanneldepth — Sets the depth of a particular image channel

### Description

public Gmagick::setimagechanneldepth(int `$channel`, int `$depth`): Gmagick

Sets the depth of a particular image channel.

### Parameters

`channel`
  One of the Channel constant (`Gmagick::CHANNEL_*`).
`depth`
  The image depth in bits.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

### Description

public Gmagick::setimagecolorspace(int `$colorspace`): Gmagick

Sets the image colorspace.

### Parameters

`colorspace`
  One of the Colorspace constant (`Gmagick::COLORSPACE_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagecompose

(PECL gmagick >= Unknown)

Gmagick::setimagecompose — Sets the image composite operator

### Description

public Gmagick::setimagecompose(int `$composite`): Gmagick

Sets the image composite operator.

### Parameters

`composite`
  The image composite operator.

### Return Values

The Gmagick object on success

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagedelay

(PECL gmagick >= Unknown)

Gmagick::setimagedelay — Sets the image delay

### Description

public Gmagick::setimagedelay(int `$delay`): Gmagick

Sets the image delay.

### Parameters

`delay`
  The image delay in 1/100th of a second.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagedepth

(PECL gmagick >= Unknown)

Gmagick::setimagedepth — Sets the image depth

### Description

public Gmagick::setimagedepth(int `$depth`): Gmagick

Sets the image depth.

### Parameters

`depth`
  The image depth in bits: 8, 16, or 32.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagedispose

(PECL gmagick >= Unknown)

Gmagick::setimagedispose — Sets the image disposal method

### Description

public Gmagick::setimagedispose(int `$disposeType`): Gmagick

Sets the image disposal method.

### Parameters

`disposeType`
  The image disposal type.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagefilename

(PECL gmagick >= Unknown)

Gmagick::setimagefilename — Sets the filename of a particular image in a sequence

### Description

public Gmagick::setimagefilename(string `$filename`): Gmagick

Sets the filename of a particular image in a sequence.

### Parameters

`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageformat

(PECL gmagick >= Unknown)

Gmagick::setimageformat — Sets the format of a particular image

### Description

public Gmagick::setimageformat(string `$imageFormat`): Gmagick

Sets the format of a particular image in a sequence.

### Parameters

`imageFormat`
  The image format.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagegamma

(PECL gmagick >= Unknown)

Gmagick::setimagegamma — Sets the image gamma

### Description

public Gmagick::setimagegamma(float `$gamma`): Gmagick

Sets the image gamma.

### Parameters

`gamma`
  The image gamma.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point

### Description

public Gmagick::setimagegreenprimary(float `$x`, float `$y`): Gmagick

Sets the image chromaticity green primary point.

### Parameters

`x`
  The chromaticity green primary x-point.
`y`
  The chromaticity green primary y-point.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageindex

(PECL gmagick >= Unknown)

Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter

### Description

public Gmagick::setimageindex(int `$index`): Gmagick

Set the iterator to the position in the image list specified with the index parameter.

### Parameters

`index`
  The scene number.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image

### Description

public Gmagick::setimageinterlacescheme(int `$interlace`): Gmagick

Sets the interlace scheme of the image.

### Parameters

`interlace`
  One of the Interlace constant (`Gmagick::INTERLACE_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageiterations

(PECL gmagick >= Unknown)

Gmagick::setimageiterations — Sets the image iterations

### Description

public Gmagick::setimageiterations(int `$iterations`): Gmagick

Sets the image iterations.

### Parameters

`iterations`
  The image delay in 1/100th of a second.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageprofile

(PECL gmagick >= Unknown)

Gmagick::setimageprofile — Adds a named profile to the Gmagick object

### Description

public Gmagick::setimageprofile(string `$name`, string `$profile`): Gmagick

Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::profileimage() method in that it does not apply any CMS color profiles.

### Parameters

`name`
  Name of profile to add or remove: ICC, IPTC, or generic profile.
`profile`
  The profile.

### Return Values

The Gmagick object on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageredprimary

(PECL gmagick >= Unknown)

Gmagick::setimageredprimary — Sets the image chromaticity red primary point

### Description

public Gmagick::setimageredprimary(float `$x`, float `$y`): Gmagick

Sets the image chromaticity red primary point.

### Parameters

`x`
  The red primary x-point.
`y`
  The red primary y-point.

### Return Values

The Gmagick object on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::setimagerenderingintent — Sets the image rendering intent

### Description

public Gmagick::setimagerenderingintent(int `$rendering_intent`): Gmagick

Sets the image rendering intent.

### Parameters

`rendering_intent`
  One of the Rendering Intent constant (`Gmagick::RENDERINGINTENT_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageresolution

(PECL gmagick >= Unknown)

Gmagick::setimageresolution — Sets the image resolution

### Description

public Gmagick::setimageresolution(float `$xResolution`, float `$yResolution`): Gmagick

Sets the image resolution.

### Parameters

`xResolution`
  The image x resolution.
`yResolution`
  The image y resolution.

### Return Values

The Gmagick object on success.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagescene

(PECL gmagick >= Unknown)

Gmagick::setimagescene — Sets the image scene

### Description

public Gmagick::setimagescene(int `$scene`): Gmagick

Sets the image scene.

### Parameters

`scene`
  The image scene number.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

### Description

public Gmagick::setimagetype(int `$imgType`): Gmagick

Sets the image type.

### Parameters

`imgType`
  One of the Image type constant (`Gmagick::IMGTYPE_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimageunits

(PECL gmagick >= Unknown)

Gmagick::setimageunits — Sets the image units of resolution

### Description

public Gmagick::setimageunits(int `$resolution`): Gmagick

Sets the image units of resolution.

### Parameters

`resolution`
  One of the Resolution constant (`Gmagick::RESOLUTION_*`).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::setimagewhitepoint — Sets the image chromaticity white point

### Description

public Gmagick::setimagewhitepoint(float `$x`, float `$y`): Gmagick

Sets the image chromaticity white point.

### Parameters

`x`
  The white x-point.
`y`
  The white y-point.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::setsamplingfactors — Sets the image sampling factors

### Description

public Gmagick::setsamplingfactors(array `$factors`): Gmagick

Sets the image sampling factors.

### Parameters

`factors`
  An array of floats representing the sampling factor for each color component (in RGB order).

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::setsize

(PECL gmagick >= Unknown)

Gmagick::setsize — Sets the size of the Gmagick object

### Description

public Gmagick::setsize(int `$columns`, int `$rows`): Gmagick

Sets the size of the Gmagick object. Set it before you read a raw image format such as `Gmagick::COLORSPACE_RGB`, `Gmagick::COLORSPACE_GRAY`, or `Gmagick::COLORSPACE_CMYK`.

### Parameters

`columns`
  The width in pixels.
`rows`
  The height in pixels.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::shearimage

(PECL gmagick >= Unknown)

Gmagick::shearimage — Creating a parallelogram

### Description

public Gmagick::shearimage(mixed `$color`, float `$xShear`, float `$yShear`): Gmagick

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

### Parameters

`color`
  The background pixel wand.
`xShear`
  The number of degrees to shear the image.
`yShear`
  The number of degrees to shear the image.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::solarizeimage

(PECL gmagick >= Unknown)

Gmagick::solarizeimage — Applies a solarizing effect to the image

### Description

public Gmagick::solarizeimage(int `$threshold`): Gmagick

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

### Parameters

`threshold`
  Define the extent of the solarization.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::spreadimage

(PECL gmagick >= Unknown)

Gmagick::spreadimage — Randomly displaces each pixel in a block

### Description

public Gmagick::spreadimage(float `$radius`): Gmagick

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

### Parameters

`radius`
  Choose a random pixel in a neighborhood of this extent.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

### Description

public Gmagick::stripimage(): Gmagick

Strips an image of all profiles and comments.

### Parameters

This function has no parameters.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::swirlimage

(PECL gmagick >= Unknown)

Gmagick::swirlimage — Swirls the pixels about the center of the image

### Description

public Gmagick::swirlimage(float `$degrees`): Gmagick

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

### Parameters

`degrees`
  Define the tightness of the swirling effect.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::thumbnailimage

(PECL gmagick >= Unknown)

Gmagick::thumbnailimage — Changes the size of an image

### Description

public Gmagick::thumbnailimage(int `$width`, int `$height`, bool `$fit` = `false`): Gmagick

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If `true` is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

### Parameters

`width`
  Image width.
`height`
  Image height.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::trimimage

(PECL gmagick >= Unknown)

Gmagick::trimimage — Remove edges from the image

### Description

public Gmagick::trimimage(float `$fuzz`): Gmagick

Remove edges that are the background color from the image.

### Parameters

`fuzz`
  By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

# Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Alias of Gmagick::writeimage()

### Description

This method is an alias of: Gmagick::writeimage().

# Gmagick::writeimage

(PECL gmagick >= Unknown)

Gmagick::writeimage — Writes an image to the specified filename

### Description

public Gmagick::writeimage(string `$filename`, bool `$all_frames` = `false`): Gmagick

Writes an image to the specified filename. If the filename parameter is `null`, the image is written to the filename set by Gmagick::readimage() or Gmagick::setimagefilename().

### Parameters

`filename`
  The image filename.

### Return Values

The Gmagick object.

### Errors/Exceptions

Throws an GmagickException on error.

## Table of Contents

- Gmagick::addimage — Adds new image to Gmagick object image list
- Gmagick::addnoiseimage — Adds random noise to the image
- Gmagick::annotateimage — Annotates an image with text
- Gmagick::blurimage — Adds blur filter to image
- Gmagick::borderimage — Surrounds the image with a border
- Gmagick::charcoalimage — Simulates a charcoal drawing
- Gmagick::chopimage — Removes a region of an image and trims
- Gmagick::clear — Clears all resources associated to Gmagick object
- Gmagick::commentimage — Adds a comment to your image
- Gmagick::compositeimage — Composite one image onto another
- Gmagick::__construct — The Gmagick constructor
- Gmagick::cropimage — Extracts a region of the image
- Gmagick::cropthumbnailimage — Creates a crop thumbnail
- Gmagick::current — The current purpose
- Gmagick::cyclecolormapimage — Displaces an image's colormap
- Gmagick::deconstructimages — Returns certain pixel differences between images
- Gmagick::despeckleimage — The despeckleimage purpose
- Gmagick::destroy — The destroy purpose
- Gmagick::drawimage — Renders the GmagickDraw object on the current image
- Gmagick::edgeimage — Enhance edges within the image
- Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
- Gmagick::enhanceimage — Improves the quality of a noisy image
- Gmagick::equalizeimage — Equalizes the image histogram
- Gmagick::flipimage — Creates a vertical mirror image
- Gmagick::flopimage — Creates a horizontal mirror image
- Gmagick::frameimage — Adds a simulated three-dimensional border
- Gmagick::gammaimage — Gamma-corrects an image
- Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
- Gmagick::getfilename — The filename associated with an image sequence
- Gmagick::getimagebackgroundcolor — Returns the image background color
- Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
- Gmagick::getimagebordercolor — Returns the image border color
- Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
- Gmagick::getimagecolors — Returns the color of the specified colormap index
- Gmagick::getimagecolorspace — Gets the image colorspace
- Gmagick::getimagecompose — Returns the composite operator associated with the image
- Gmagick::getimagedelay — Gets the image delay
- Gmagick::getimagedepth — Gets the depth of the image
- Gmagick::getimagedispose — Gets the image disposal method
- Gmagick::getimageextrema — Gets the extrema for the image
- Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
- Gmagick::getimageformat — Returns the format of a particular image in a sequence
- Gmagick::getimagegamma — Gets the image gamma
- Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
- Gmagick::getimageheight — Returns the image height
- Gmagick::getimagehistogram — Gets the image histogram
- Gmagick::getimageindex — Gets the index of the current active image
- Gmagick::getimageinterlacescheme — Gets the image interlace scheme
- Gmagick::getimageiterations — Gets the image iterations
- Gmagick::getimagematte — Check if the image has a matte channel
- Gmagick::getimagemattecolor — Returns the image matte color
- Gmagick::getimageprofile — Returns the named image profile
- Gmagick::getimageredprimary — Returns the chromaticity red primary point
- Gmagick::getimagerenderingintent — Gets the image rendering intent
- Gmagick::getimageresolution — Gets the image X and Y resolution
- Gmagick::getimagescene — Gets the image scene
- Gmagick::getimagesignature — Generates an SHA-256 message digest
- Gmagick::getimagetype — Gets the potential image type
- Gmagick::getimageunits — Gets the image units of resolution
- Gmagick::getimagewhitepoint — Returns the chromaticity white point
- Gmagick::getimagewidth — Returns the width of the image
- Gmagick::getpackagename — Returns the GraphicsMagick package name
- Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string
- Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string
- Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor
- Gmagick::getsize — Returns the size associated with the Gmagick object
- Gmagick::getversion — Returns the GraphicsMagick API version
- Gmagick::hasnextimage — Checks if the object has more images
- Gmagick::haspreviousimage — Checks if the object has a previous image
- Gmagick::implodeimage — Creates a new image as a copy
- Gmagick::labelimage — Adds a label to an image
- Gmagick::levelimage — Adjusts the levels of an image
- Gmagick::magnifyimage — Scales an image proportionally 2x
- Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image
- Gmagick::medianfilterimage — Applies a digital filter
- Gmagick::minifyimage — Scales an image proportionally to half its size
- Gmagick::modulateimage — Control the brightness, saturation, and hue
- Gmagick::motionblurimage — Simulates motion blur
- Gmagick::newimage — Creates a new image
- Gmagick::nextimage — Moves to the next image
- Gmagick::normalizeimage — Enhances the contrast of a color image
- Gmagick::oilpaintimage — Simulates an oil painting
- Gmagick::previousimage — Move to the previous image in the object
- Gmagick::profileimage — Adds or removes a profile from an image
- Gmagick::quantizeimage — Analyzes the colors within a reference image
- Gmagick::quantizeimages — The quantizeimages purpose
- Gmagick::queryfontmetrics — Returns an array representing the font metrics
- Gmagick::queryfonts — Returns the configured fonts
- Gmagick::queryformats — Returns formats supported by Gmagick
- Gmagick::radialblurimage — Radial blurs an image
- Gmagick::raiseimage — Creates a simulated 3d button-like effect
- Gmagick::read — Reads image from filename
- Gmagick::readimage — Reads image from filename
- Gmagick::readimageblob — Reads image from a binary string
- Gmagick::readimagefile — The readimagefile purpose
- Gmagick::reducenoiseimage — Smooths the contours of an image
- Gmagick::removeimage — Removes an image from the image list
- Gmagick::removeimageprofile — Removes the named image profile and returns it
- Gmagick::resampleimage — Resample image to desired resolution
- Gmagick::resizeimage — Scales an image
- Gmagick::rollimage — Offsets an image
- Gmagick::rotateimage — Rotates an image
- Gmagick::scaleimage — Scales the size of an image
- Gmagick::separateimagechannel — Separates a channel from the image
- Gmagick::setCompressionQuality — Sets the object's default compression quality
- Gmagick::setfilename — Sets the filename before you read or write the image
- Gmagick::setimagebackgroundcolor — Sets the image background color
- Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point
- Gmagick::setimagebordercolor — Sets the image border color
- Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
- Gmagick::setimagecolorspace — Sets the image colorspace
- Gmagick::setimagecompose — Sets the image composite operator
- Gmagick::setimagedelay — Sets the image delay
- Gmagick::setimagedepth — Sets the image depth
- Gmagick::setimagedispose — Sets the image disposal method
- Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
- Gmagick::setimageformat — Sets the format of a particular image
- Gmagick::setimagegamma — Sets the image gamma
- Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point
- Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
- Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image
- Gmagick::setimageiterations — Sets the image iterations
- Gmagick::setimageprofile — Adds a named profile to the Gmagick object
- Gmagick::setimageredprimary — Sets the image chromaticity red primary point
- Gmagick::setimagerenderingintent — Sets the image rendering intent
- Gmagick::setimageresolution — Sets the image resolution
- Gmagick::setimagescene — Sets the image scene
- Gmagick::setimagetype — Sets the image type
- Gmagick::setimageunits — Sets the image units of resolution
- Gmagick::setimagewhitepoint — Sets the image chromaticity white point
- Gmagick::setsamplingfactors — Sets the image sampling factors
- Gmagick::setsize — Sets the size of the Gmagick object
- Gmagick::shearimage — Creating a parallelogram
- Gmagick::solarizeimage — Applies a solarizing effect to the image
- Gmagick::spreadimage — Randomly displaces each pixel in a block
- Gmagick::stripimage — Strips an image of all profiles and comments
- Gmagick::swirlimage — Swirls the pixels about the center of the image
- Gmagick::thumbnailimage — Changes the size of an image
- Gmagick::trimimage — Remove edges from the image
- Gmagick::write — Alias of Gmagick::writeimage
- Gmagick::writeimage — Writes an image to the specified filename

# The GmagickDraw class

(PECL gmagick >= Unknown)

## Introduction

## Class synopsis

class GmagickDraw {
/* Methods */
public annotate(float `$x`, float `$y`, string `$text`): GmagickDraw
public arc(
float `$sx`,
float `$sy`,
float `$ex`,
float `$ey`,
float `$sd`,
float `$ed`
): GmagickDraw
public bezier(array `$coordinate_array`): GmagickDraw
public ellipse(
float `$ox`,
float `$oy`,
float `$rx`,
float `$ry`,
float `$start`,
float `$end`
): GmagickDraw
public getfillcolor(): GmagickPixel
public getfillopacity(): float
public getfont(): mixed
public getfontsize(): float
public getfontstyle(): int
public getfontweight(): int
public getstrokecolor(): GmagickPixel
public getstrokeopacity(): float
public getstrokewidth(): float
public gettextdecoration(): int
public gettextencoding(): mixed
public line(
float `$sx`,
float `$sy`,
float `$ex`,
float `$ey`
): GmagickDraw
public point(float `$x`, float `$y`): GmagickDraw
public polygon(array `$coordinates`): GmagickDraw
public polyline(array `$coordinate_array`): GmagickDraw
public rectangle(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`
): GmagickDraw
public rotate(float `$degrees`): GmagickDraw
public roundrectangle(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$rx`,
float `$ry`
): GmagickDraw
public scale(float `$x`, float `$y`): GmagickDraw
public setfillcolor(mixed `$color`): GmagickDraw
public setfillopacity(float `$fill_opacity`): GmagickDraw
public setfont(string `$font`): GmagickDraw
public setfontsize(float `$pointsize`): GmagickDraw
public setfontstyle(int `$style`): GmagickDraw
public setfontweight(int `$weight`): GmagickDraw
public setstrokecolor(mixed `$color`): GmagickDraw
public setstrokeopacity(float `$stroke_opacity`): GmagickDraw
public setstrokewidth(float `$width`): GmagickDraw
public settextdecoration(int `$decoration`): GmagickDraw
public settextencoding(string `$encoding`): GmagickDraw
}

# GmagickDraw::annotate

(PECL gmagick >= Unknown)

GmagickDraw::annotate — Draws text on the image

### Description

public GmagickDraw::annotate(float `$x`, float `$y`, string `$text`): GmagickDraw

Draws text on the image.

### Parameters

`x`
  x ordinate to left of text
`y`
  y ordinate to text baseline
`text`
  text to draw

### Return Values

The GmagickDraw object.

# GmagickDraw::arc

(PECL gmagick >= Unknown)

GmagickDraw::arc — Draws an arc

### Description

public GmagickDraw::arc(
float `$sx`,
float `$sy`,
float `$ex`,
float `$ey`,
float `$sd`,
float `$ed`
): GmagickDraw

Draws an arc falling within a specified bounding rectangle on the image.

### Parameters

`sx`
  starting x ordinate of bounding rectangle
`sy`
  starting y ordinate of bounding rectangle
`ex`
  ending x ordinate of bounding rectangle
`ey`
  ending y ordinate of bounding rectangle
`sd`
  starting degrees of rotation
`ed`
  ending degrees of rotation

### Return Values

The GmagickDraw object.

# GmagickDraw::bezier

(PECL gmagick >= Unknown)

GmagickDraw::bezier — Draws a bezier curve

### Description

public GmagickDraw::bezier(array `$coordinate_array`): GmagickDraw

Draws a bezier curve through a set of points on the image.

### Parameters

`coordinate_array`
  Coordinates array

### Return Values

The GmagickDraw object.

# GmagickDraw::ellipse

(PECL gmagick >= Unknown)

GmagickDraw::ellipse — Draws an ellipse on the image

### Description

public GmagickDraw::ellipse(
float `$ox`,
float `$oy`,
float `$rx`,
float `$ry`,
float `$start`,
float `$end`
): GmagickDraw

Draws an ellipse on the image.

### Parameters

`ox`
  origin x ordinate
`oy`
  origin y ordinate
`rx`
  radius in x
`ry`
  radius in y
`start`
  starting rotation in degrees
`end`
  ending rotation in degrees

### Return Values

The GmagickDraw object.

# GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

### Description

public GmagickDraw::getfillcolor(): GmagickPixel

Returns the fill color used for drawing filled objects.

### Parameters

This function has no parameters.

### Return Values

The GmagickPixel fill color used for drawing filled objects.

# GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

### Description

public GmagickDraw::getfillopacity(): float

Returns the opacity used when drawing

### Parameters

This function has no parameters.

### Return Values

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

# GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

### Description

public GmagickDraw::getfont(): mixed

Returns a string specifying the font used when annotating with text.

### Parameters

This function has no parameters.

### Return Values

Returns a string on success and `false` if no font is set.

# GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

### Description

public GmagickDraw::getfontsize(): float

Returns the font pointsize used when annotating with text.

### Parameters

This function has no parameters.

### Return Values

Returns the font size associated with the current GmagickDraw object.

# GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

### Description

public GmagickDraw::getfontstyle(): int

Returns the font style used when annotating with text.

### Parameters

This function has no parameters.

### Return Values

Returns the font style constant (STYLE_) associated with the GmagickDraw object or `0` if no style is set.

# GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

### Description

public GmagickDraw::getfontweight(): int

Returns the font weight used when annotating with text.

### Parameters

This function has no parameters.

### Return Values

Returns an int on success and 0 if no weight is set.

# GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

### Description

public GmagickDraw::getstrokecolor(): GmagickPixel

Returns the color used for stroking object outlines.

### Parameters

This function has no parameters.

### Return Values

Returns an GmagickPixel object which describes the color.

# GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

### Description

public GmagickDraw::getstrokeopacity(): float

Returns the opacity of stroked object outlines.

### Parameters

This function has no parameters.

### Return Values

Returns a float describing the opacity.

# GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

### Description

public GmagickDraw::getstrokewidth(): float

Returns the width of the stroke used to draw object outlines.

### Parameters

This function has no parameters.

### Return Values

Returns a float describing the stroke width.

# GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

### Description

public GmagickDraw::gettextdecoration(): int

Returns the decoration applied when annotating with text.

### Parameters

This function has no parameters.

### Return Values

Returns one of the DECORATION_ constants and 0 if no decoration is set.

# GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

### Description

public GmagickDraw::gettextencoding(): mixed

Returns a string which specifies the code set used for text annotations.

### Parameters

This function has no parameters.

### Return Values

Returns a string specifying the code set or `false` if text encoding is not set.

# GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — Draws a line

### Description

public GmagickDraw::line(
float `$sx`,
float `$sy`,
float `$ex`,
float `$ey`
): GmagickDraw

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

### Parameters

`sx`
  starting x ordinate
`sy`
  starting y ordinate
`ex`
  ending x ordinate
`ey`
  ending y ordinate

### Return Values

The GmagickDraw object.

# GmagickDraw::point

(PECL gmagick >= Unknown)

GmagickDraw::point — Draws a point

### Description

public GmagickDraw::point(float `$x`, float `$y`): GmagickDraw

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

### Parameters

`x`
  target x coordinate
`y`
  target y coordinate

### Return Values

The GmagickDraw object.

# GmagickDraw::polygon

(PECL gmagick >= Unknown)

GmagickDraw::polygon — Draws a polygon

### Description

public GmagickDraw::polygon(array `$coordinates`): GmagickDraw

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

### Parameters

`coordinates`
  coordinate array

### Return Values

The GmagickDraw object.

# GmagickDraw::polyline

(PECL gmagick >= Unknown)

GmagickDraw::polyline — Draws a polyline

### Description

public GmagickDraw::polyline(array `$coordinate_array`): GmagickDraw

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

### Parameters

`coordinate_array`
  The array of coordinates

### Return Values

The GmagickDraw object.

# GmagickDraw::rectangle

(PECL gmagick >= Unknown)

GmagickDraw::rectangle — Draws a rectangle

### Description

public GmagickDraw::rectangle(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`
): GmagickDraw

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

### Parameters

`x1`
  x ordinate of first coordinate
`y1`
  y ordinate of first coordinate
`x2`
  x ordinate of second coordinate
`y2`
  y ordinate of second coordinate

### Return Values

The GmagickDraw object.

# GmagickDraw::rotate

(PECL gmagick >= Unknown)

GmagickDraw::rotate — Applies the specified rotation to the current coordinate space

### Description

public GmagickDraw::rotate(float `$degrees`): GmagickDraw

Applies the specified rotation to the current coordinate space.

### Parameters

`degrees`
  degrees of rotation

### Return Values

The GmagickDraw object.

# GmagickDraw::roundrectangle

(PECL gmagick >= Unknown)

GmagickDraw::roundrectangle — Draws a rounded rectangle

### Description

public GmagickDraw::roundrectangle(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$rx`,
float `$ry`
): GmagickDraw

Draws a rounded rectangle given two coordinates, x and y corner radiuses and using the current stroke, stroke width, and fill settings.

### Parameters

`x1`
  x ordinate of first coordinate
`y1`
  y ordinate of first coordinate
`x2`
  x ordinate of second coordinate
`y2`
  y ordinate of second coordinate
`rx`
  radius of corner in horizontal direction
`ry`
  radius of corner in vertical direction

### Return Values

The GmagickDraw object.

# GmagickDraw::scale

(PECL gmagick >= Unknown)

GmagickDraw::scale — Adjusts the scaling factor

### Description

public GmagickDraw::scale(float `$x`, float `$y`): GmagickDraw

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

### Parameters

`x`
  horizontal scale factor
`y`
  vertical scale factor

### Return Values

The GmagickDraw object.

# GmagickDraw::setfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects

### Description

public GmagickDraw::setfillcolor(mixed `$color`): GmagickDraw

Sets the fill color to be used for drawing filled objects.

### Parameters

`color`
  GmagickPixel or string indicating color to use for filling.

### Return Values

The GmagickDraw object on success.

# GmagickDraw::setfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::setfillopacity — The setfillopacity purpose

### Description

public GmagickDraw::setfillopacity(float `$fill_opacity`): GmagickDraw

Sets the opacity to use when drawing using the fill color or fill texture. Setting it to 1.0 will make fill full opaque.

### Parameters

`fill_opacity`
  Fill opacity

### Return Values

The GmagickDraw object.

# GmagickDraw::setfont

(PECL gmagick >= Unknown)

GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text

### Description

public GmagickDraw::setfont(string `$font`): GmagickDraw

Sets the fully-specified font to use when annotating with text

### Parameters

`font`
  font name

### Return Values

The GmagickDraw object.

# GmagickDraw::setfontsize

(PECL gmagick >= Unknown)

GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text

### Description

public GmagickDraw::setfontsize(float `$pointsize`): GmagickDraw

Sets the font pointsize to use when annotating with text.

### Parameters

`pointsize`
  Text pointsize

### Return Values

The GmagickDraw object.

# GmagickDraw::setfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::setfontstyle — Sets the font style to use when annotating with text

### Description

public GmagickDraw::setfontstyle(int `$style`): GmagickDraw

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

### Parameters

`style`
  Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

### Return Values

The GmagickDraw object.

# GmagickDraw::setfontweight

(PECL gmagick >= Unknown)

GmagickDraw::setfontweight — Sets the font weight

### Description

public GmagickDraw::setfontweight(int `$weight`): GmagickDraw

Sets the font weight to use when annotating with text.

### Parameters

`weight`
  Font weight (valid range 100-900)

### Return Values

The GmagickDraw object.

# GmagickDraw::setstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines

### Description

public GmagickDraw::setstrokecolor(mixed `$color`): GmagickDraw

Sets the color used for stroking object outlines.

### Parameters

`color`
  GmagickPixel or string representing the color for the stroke.

### Return Values

The GmagickDraw object on success.

# GmagickDraw::setstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines

### Description

public GmagickDraw::setstrokeopacity(float `$stroke_opacity`): GmagickDraw

Specifies the opacity of stroked object outlines.

### Parameters

`stroke_opacity`
  Stroke opacity. The value 1.0 is opaque.

### Return Values

The GmagickDraw object.

# GmagickDraw::setstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines

### Description

public GmagickDraw::setstrokewidth(float `$width`): GmagickDraw

Sets the width of the stroke used to draw object outlines

### Parameters

`width`
  Stroke width

### Return Values

The GmagickDraw object.

# GmagickDraw::settextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::settextdecoration — Specifies a decoration

### Description

public GmagickDraw::settextdecoration(int `$decoration`): GmagickDraw

Specifies a decoration to be applied when annotating with text.

### Parameters

`int`
  Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

### Return Values

The GmagickDraw object.

# GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies the text code set

### Description

public GmagickDraw::settextencoding(string `$encoding`): GmagickDraw

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

### Parameters

`encoding`
  Character string specifying text encoding

### Return Values

The GmagickDraw object.

## Table of Contents

- GmagickDraw::annotate — Draws text on the image
- GmagickDraw::arc — Draws an arc
- GmagickDraw::bezier — Draws a bezier curve
- GmagickDraw::ellipse — Draws an ellipse on the image
- GmagickDraw::getfillcolor — Returns the fill color
- GmagickDraw::getfillopacity — Returns the opacity used when drawing
- GmagickDraw::getfont — Returns the font
- GmagickDraw::getfontsize — Returns the font pointsize
- GmagickDraw::getfontstyle — Returns the font style
- GmagickDraw::getfontweight — Returns the font weight
- GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
- GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
- GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
- GmagickDraw::gettextdecoration — Returns the text decoration
- GmagickDraw::gettextencoding — Returns the code set used for text annotations
- GmagickDraw::line — Draws a line
- GmagickDraw::point — Draws a point
- GmagickDraw::polygon — Draws a polygon
- GmagickDraw::polyline — Draws a polyline
- GmagickDraw::rectangle — Draws a rectangle
- GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
- GmagickDraw::roundrectangle — Draws a rounded rectangle
- GmagickDraw::scale — Adjusts the scaling factor
- GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects
- GmagickDraw::setfillopacity — The setfillopacity purpose
- GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text
- GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text
- GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
- GmagickDraw::setfontweight — Sets the font weight
- GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines
- GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines
- GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines
- GmagickDraw::settextdecoration — Specifies a decoration
- GmagickDraw::settextencoding — Specifies the text code set

# The GmagickPixel class

(PECL gmagick >= Unknown)

## Introduction

## Class synopsis

class GmagickPixel {
/* Methods */
public __construct(string `$color` = ?)
public getcolor(bool `$as_array` = `false`, bool `$normalize_array` = `false`): mixed
public getcolorcount(): int
public getcolorvalue(int `$color`): float
public setcolor(string `$color`): GmagickPixel
public setcolorvalue(int `$color`, float `$value`): GmagickPixel
}

# GmagickPixel::__construct

(PECL gmagick >= Unknown)

GmagickPixel::__construct — The GmagickPixel constructor

### Description

public GmagickPixel::__construct(string `$color` = ?)

Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

### Parameters

`color`
  The optional color string to use as the initial value of this object.

# GmagickPixel::getcolor

(PECL gmagick >= Unknown)

GmagickPixel::getcolor — Returns the color

### Description

public GmagickPixel::getcolor(bool `$as_array` = `false`, bool `$normalize_array` = `false`): mixed

Returns the color described by the GmagickPixel object, as a string or an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

### Parameters

`as_array`
  `true` to indicate return of array instead of string.
`normalize_array`
  `true` to normalize the color values.

### Return Values

A string or an array of channel values, each normalized if `true` is given as `normalize_array`. Throws GmagickPixelException on error.

# GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

### Description

public GmagickPixel::getcolorcount(): int

Returns the color count associated with this color.

### Parameters

This function has no parameters.

### Return Values

Returns the color count as an integer on success, throws GmagickPixelException on failure.

# GmagickPixel::getcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel

### Description

public GmagickPixel::getcolorvalue(int `$color`): float

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

### Parameters

`color`
  The channel to check, specified as one of the Gmagick channel constants.

### Return Values

The value of the channel, as a normalized floating-point number, throwing GmagickPixelException on error.

# GmagickPixel::setcolor

(PECL gmagick >= Unknown)

GmagickPixel::setcolor — Sets the color

### Description

public GmagickPixel::setcolor(string `$color`): GmagickPixel

Sets the color described by the GmagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

### Parameters

`color`
  The color definition to use in order to initialise the GmagickPixel object.

### Return Values

The GmagickPixel object.

# GmagickPixel::setcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

### Description

public GmagickPixel::setcolorvalue(int `$color`, float `$value`): GmagickPixel

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to a GmagickPixel object.

### Parameters

`color`
  One of the Gmagick channel color constants.
`value`
  The value to set this channel to, ranging from 0 to 1.

### Return Values

The GmagickPixel object.

## Table of Contents

- GmagickPixel::__construct — The GmagickPixel constructor
- GmagickPixel::getcolor — Returns the color
- GmagickPixel::getcolorcount — Returns the color count associated with this color
- GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
- GmagickPixel::setcolor — Sets the color
- GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Examples
- Gmagick — The Gmagick class
  - Gmagick::addimage — Adds new image to Gmagick object image list
  - Gmagick::addnoiseimage — Adds random noise to the image
  - Gmagick::annotateimage — Annotates an image with text
  - Gmagick::blurimage — Adds blur filter to image
  - Gmagick::borderimage — Surrounds the image with a border
  - Gmagick::charcoalimage — Simulates a charcoal drawing
  - Gmagick::chopimage — Removes a region of an image and trims
  - Gmagick::clear — Clears all resources associated to Gmagick object
  - Gmagick::commentimage — Adds a comment to your image
  - Gmagick::compositeimage — Composite one image onto another
  - Gmagick::__construct — The Gmagick constructor
  - Gmagick::cropimage — Extracts a region of the image
  - Gmagick::cropthumbnailimage — Creates a crop thumbnail
  - Gmagick::current — The current purpose
  - Gmagick::cyclecolormapimage — Displaces an image's colormap
  - Gmagick::deconstructimages — Returns certain pixel differences between images
  - Gmagick::despeckleimage — The despeckleimage purpose
  - Gmagick::destroy — The destroy purpose
  - Gmagick::drawimage — Renders the GmagickDraw object on the current image
  - Gmagick::edgeimage — Enhance edges within the image
  - Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
  - Gmagick::enhanceimage — Improves the quality of a noisy image
  - Gmagick::equalizeimage — Equalizes the image histogram
  - Gmagick::flipimage — Creates a vertical mirror image
  - Gmagick::flopimage — Creates a horizontal mirror image
  - Gmagick::frameimage — Adds a simulated three-dimensional border
  - Gmagick::gammaimage — Gamma-corrects an image
  - Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
  - Gmagick::getfilename — The filename associated with an image sequence
  - Gmagick::getimagebackgroundcolor — Returns the image background color
  - Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
  - Gmagick::getimagebordercolor — Returns the image border color
  - Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
  - Gmagick::getimagecolors — Returns the color of the specified colormap index
  - Gmagick::getimagecolorspace — Gets the image colorspace
  - Gmagick::getimagecompose — Returns the composite operator associated with the image
  - Gmagick::getimagedelay — Gets the image delay
  - Gmagick::getimagedepth — Gets the depth of the image
  - Gmagick::getimagedispose — Gets the image disposal method
  - Gmagick::getimageextrema — Gets the extrema for the image
  - Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
  - Gmagick::getimageformat — Returns the format of a particular image in a sequence
  - Gmagick::getimagegamma — Gets the image gamma
  - Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
  - Gmagick::getimageheight — Returns the image height
  - Gmagick::getimagehistogram — Gets the image histogram
  - Gmagick::getimageindex — Gets the index of the current active image
  - Gmagick::getimageinterlacescheme — Gets the image interlace scheme
  - Gmagick::getimageiterations — Gets the image iterations
  - Gmagick::getimagematte — Check if the image has a matte channel
  - Gmagick::getimagemattecolor — Returns the image matte color
  - Gmagick::getimageprofile — Returns the named image profile
  - Gmagick::getimageredprimary — Returns the chromaticity red primary point
  - Gmagick::getimagerenderingintent — Gets the image rendering intent
  - Gmagick::getimageresolution — Gets the image X and Y resolution
  - Gmagick::getimagescene — Gets the image scene
  - Gmagick::getimagesignature — Generates an SHA-256 message digest
  - Gmagick::getimagetype — Gets the potential image type
  - Gmagick::getimageunits — Gets the image units of resolution
  - Gmagick::getimagewhitepoint — Returns the chromaticity white point
  - Gmagick::getimagewidth — Returns the width of the image
  - Gmagick::getpackagename — Returns the GraphicsMagick package name
  - Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string
  - Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string
  - Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor
  - Gmagick::getsize — Returns the size associated with the Gmagick object
  - Gmagick::getversion — Returns the GraphicsMagick API version
  - Gmagick::hasnextimage — Checks if the object has more images
  - Gmagick::haspreviousimage — Checks if the object has a previous image
  - Gmagick::implodeimage — Creates a new image as a copy
  - Gmagick::labelimage — Adds a label to an image
  - Gmagick::levelimage — Adjusts the levels of an image
  - Gmagick::magnifyimage — Scales an image proportionally 2x
  - Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image
  - Gmagick::medianfilterimage — Applies a digital filter
  - Gmagick::minifyimage — Scales an image proportionally to half its size
  - Gmagick::modulateimage — Control the brightness, saturation, and hue
  - Gmagick::motionblurimage — Simulates motion blur
  - Gmagick::newimage — Creates a new image
  - Gmagick::nextimage — Moves to the next image
  - Gmagick::normalizeimage — Enhances the contrast of a color image
  - Gmagick::oilpaintimage — Simulates an oil painting
  - Gmagick::previousimage — Move to the previous image in the object
  - Gmagick::profileimage — Adds or removes a profile from an image
  - Gmagick::quantizeimage — Analyzes the colors within a reference image
  - Gmagick::quantizeimages — The quantizeimages purpose
  - Gmagick::queryfontmetrics — Returns an array representing the font metrics
  - Gmagick::queryfonts — Returns the configured fonts
  - Gmagick::queryformats — Returns formats supported by Gmagick
  - Gmagick::radialblurimage — Radial blurs an image
  - Gmagick::raiseimage — Creates a simulated 3d button-like effect
  - Gmagick::read — Reads image from filename
  - Gmagick::readimage — Reads image from filename
  - Gmagick::readimageblob — Reads image from a binary string
  - Gmagick::readimagefile — The readimagefile purpose
  - Gmagick::reducenoiseimage — Smooths the contours of an image
  - Gmagick::removeimage — Removes an image from the image list
  - Gmagick::removeimageprofile — Removes the named image profile and returns it
  - Gmagick::resampleimage — Resample image to desired resolution
  - Gmagick::resizeimage — Scales an image
  - Gmagick::rollimage — Offsets an image
  - Gmagick::rotateimage — Rotates an image
  - Gmagick::scaleimage — Scales the size of an image
  - Gmagick::separateimagechannel — Separates a channel from the image
  - Gmagick::setCompressionQuality — Sets the object's default compression quality
  - Gmagick::setfilename — Sets the filename before you read or write the image
  - Gmagick::setimagebackgroundcolor — Sets the image background color
  - Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point
  - Gmagick::setimagebordercolor — Sets the image border color
  - Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
  - Gmagick::setimagecolorspace — Sets the image colorspace
  - Gmagick::setimagecompose — Sets the image composite operator
  - Gmagick::setimagedelay — Sets the image delay
  - Gmagick::setimagedepth — Sets the image depth
  - Gmagick::setimagedispose — Sets the image disposal method
  - Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
  - Gmagick::setimageformat — Sets the format of a particular image
  - Gmagick::setimagegamma — Sets the image gamma
  - Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point
  - Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
  - Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image
  - Gmagick::setimageiterations — Sets the image iterations
  - Gmagick::setimageprofile — Adds a named profile to the Gmagick object
  - Gmagick::setimageredprimary — Sets the image chromaticity red primary point
  - Gmagick::setimagerenderingintent — Sets the image rendering intent
  - Gmagick::setimageresolution — Sets the image resolution
  - Gmagick::setimagescene — Sets the image scene
  - Gmagick::setimagetype — Sets the image type
  - Gmagick::setimageunits — Sets the image units of resolution
  - Gmagick::setimagewhitepoint — Sets the image chromaticity white point
  - Gmagick::setsamplingfactors — Sets the image sampling factors
  - Gmagick::setsize — Sets the size of the Gmagick object
  - Gmagick::shearimage — Creating a parallelogram
  - Gmagick::solarizeimage — Applies a solarizing effect to the image
  - Gmagick::spreadimage — Randomly displaces each pixel in a block
  - Gmagick::stripimage — Strips an image of all profiles and comments
  - Gmagick::swirlimage — Swirls the pixels about the center of the image
  - Gmagick::thumbnailimage — Changes the size of an image
  - Gmagick::trimimage — Remove edges from the image
  - Gmagick::write — Alias of Gmagick::writeimage
  - Gmagick::writeimage — Writes an image to the specified filename
- GmagickDraw — The GmagickDraw class
  - GmagickDraw::annotate — Draws text on the image
  - GmagickDraw::arc — Draws an arc
  - GmagickDraw::bezier — Draws a bezier curve
  - GmagickDraw::ellipse — Draws an ellipse on the image
  - GmagickDraw::getfillcolor — Returns the fill color
  - GmagickDraw::getfillopacity — Returns the opacity used when drawing
  - GmagickDraw::getfont — Returns the font
  - GmagickDraw::getfontsize — Returns the font pointsize
  - GmagickDraw::getfontstyle — Returns the font style
  - GmagickDraw::getfontweight — Returns the font weight
  - GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
  - GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
  - GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
  - GmagickDraw::gettextdecoration — Returns the text decoration
  - GmagickDraw::gettextencoding — Returns the code set used for text annotations
  - GmagickDraw::line — Draws a line
  - GmagickDraw::point — Draws a point
  - GmagickDraw::polygon — Draws a polygon
  - GmagickDraw::polyline — Draws a polyline
  - GmagickDraw::rectangle — Draws a rectangle
  - GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
  - GmagickDraw::roundrectangle — Draws a rounded rectangle
  - GmagickDraw::scale — Adjusts the scaling factor
  - GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects
  - GmagickDraw::setfillopacity — The setfillopacity purpose
  - GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text
  - GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text
  - GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
  - GmagickDraw::setfontweight — Sets the font weight
  - GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines
  - GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines
  - GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines
  - GmagickDraw::settextdecoration — Specifies a decoration
  - GmagickDraw::settextencoding — Specifies the text code set
- GmagickPixel — The GmagickPixel class
  - GmagickPixel::__construct — The GmagickPixel constructor
  - GmagickPixel::getcolor — Returns the color
  - GmagickPixel::getcolorcount — Returns the color count associated with this color
  - GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
  - GmagickPixel::setcolor — Sets the color
  - GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

# Image Processing (ImageMagick)

# Introduction

Warning

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.

Imagick is a native php extension to create and modify images using the ImageMagick API.

## About ImageMagick

ImageMagick is a software suite to create, edit, and compose bitmap images. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.

ImageMagick Studio LLC is a non-profit organization dedicated to making software imaging solutions freely available.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

## Installation requirements on non-Windows platforms

ImageMagick >= 6.2.4 is required. The amount of file formats supported by Imagick depends entirely upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

## Installation

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: » https://pecl.php.net/package/imagick.

> Note: The official name of this extension is imagick.

Windows users can download prebuilt DLL from the » PECL website. These packages already contain the extension DLL (php_imagick.dll) which needs to be put into the extension_dir. They also contain the ImageMagick DLLs, which need to be put somewhere in the PATH. As of Imagick 3.6.0, they also contain XML configuration files in config; to use these instead of the built-in defaults, they need to put into `%USERPROFILE%/.config/ImageMagick`, or alternatively in the path given by the environment variable MAGICK_CONFIGURE_PATH. Refer to the » ImageMagick configuration files documentation for further details.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Imagick configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
imagick.locale_fix | `false` | `INI_ALL` | Available since Imagick 2.1.0
imagick.progress_monitor | `false` | `INI_SYSTEM` | Available since Imagick 2.2.2
imagick.skip_version_check | `false` | `INI_SYSTEM` | Available since Imagick 3.3.0

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`imagick.locale_fix` bool

  Fixes a drawing bug with locales that use '`,`' as float separators.

`imagick.progress_monitor` bool

  Used to enable the image progress monitor.

`imagick.skip_version_check` bool

  When Imagick is loaded, it checks the version number of ImageMagick that it was compiled against, with the version number that is currently being used and will give a warning if they don't match. This warning can be suppressed by enabling this ini setting.

  Using a version of Imagick that was compiled against a different version of ImageMagick than the one being used is not recommended. Although it may appear to work, it can lead to random crashes or other undefined behaviour.

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

`COLOR_*` constants

Colortype constants. These constants are mainly used with ImagickPixel.

`imagick::COLOR_BLACK` (int)
  Black color
`imagick::COLOR_BLUE` (int)
  Blue color
`imagick::COLOR_CYAN` (int)
  Cyan color
`imagick::COLOR_GREEN` (int)
  Green color
`imagick::COLOR_RED` (int)
  Red color
`imagick::COLOR_YELLOW` (int)
  Yellow color
`imagick::COLOR_MAGENTA` (int)
  Magenta color
`imagick::COLOR_OPACITY` (int)
  Color's opacity
`imagick::COLOR_ALPHA` (int)
  Color's alpha
`imagick::COLOR_FUZZ` (int)
  Color's fuzz

`DISPOSE_*` constants

Dispose type constants

`imagick::DISPOSE_UNRECOGNIZED` (int)
  Unrecognized dispose type
`imagick::DISPOSE_UNDEFINED` (int)
  Undefined dispose type
`imagick::DISPOSE_NONE` (int)
  No dispose type defined
`imagick::DISPOSE_BACKGROUND` (int)
  Dispose background
`imagick::DISPOSE_PREVIOUS` (int)
  Dispose previous

`COMPOSITE_*` constants
`imagick::COMPOSITE_DEFAULT` (int)
  The default composite operator
`imagick::COMPOSITE_UNDEFINED` (int)
  Undefined composite operator
`imagick::COMPOSITE_NO` (int)
  No composite operator defined
`imagick::COMPOSITE_ADD` (int)
  The result of image + image
`imagick::COMPOSITE_ATOP` (int)
  The result is the same shape as image, with composite image obscuring image where the image shapes overlap
`imagick::COMPOSITE_BLEND` (int)
  Blends the image
`imagick::COMPOSITE_BUMPMAP` (int)
  The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
`imagick::COMPOSITE_CLEAR` (int)
  Makes the target image transparent
`imagick::COMPOSITE_COLORBURN` (int)
  Darkens the destination image to reflect the source image
`imagick::COMPOSITE_COLORDODGE` (int)
  Brightens the destination image to reflect the source image
`imagick::COMPOSITE_COLORIZE` (int)
  Colorizes the target image using the composite image
`imagick::COMPOSITE_COPYBLACK` (int)
  Copies black from the source to target
`imagick::COMPOSITE_COPYBLUE` (int)
  Copies blue from the source to target
`imagick::COMPOSITE_COPY` (int)
  Copies the source image on the target image
`imagick::COMPOSITE_COPYCYAN` (int)
  Copies cyan from the source to target
`imagick::COMPOSITE_COPYGREEN` (int)
  Copies green from the source to target
`imagick::COMPOSITE_COPYMAGENTA` (int)
  Copies magenta from the source to target
`imagick::COMPOSITE_COPYOPACITY` (int)
  Copies opacity from the source to target
`imagick::COMPOSITE_COPYRED` (int)
  Copies red from the source to target
`imagick::COMPOSITE_COPYYELLOW` (int)
  Copies yellow from the source to target
`imagick::COMPOSITE_DARKEN` (int)
  Darkens the target image
`imagick::COMPOSITE_DSTATOP` (int)
  The part of the destination lying inside of the source is composited over the source and replaces the destination
`imagick::COMPOSITE_DST` (int)
  The target is left untouched
`imagick::COMPOSITE_DSTIN` (int)
  The parts inside the source replace the target
`imagick::COMPOSITE_DSTOUT` (int)
  The parts outside the source replace the target
`imagick::COMPOSITE_DSTOVER` (int)
  Target replaces the source
`imagick::COMPOSITE_DIFFERENCE` (int)
  Subtracts the darker of the two constituent colors from the lighter
`imagick::COMPOSITE_DISPLACE` (int)
  Shifts target image pixels as defined by the source
`imagick::COMPOSITE_DISSOLVE` (int)
  Dissolves the source in to the target
`imagick::COMPOSITE_EXCLUSION` (int)
  Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
`imagick::COMPOSITE_HARDLIGHT` (int)
  Multiplies or screens the colors, dependent on the source color value
`imagick::COMPOSITE_HUE` (int)
  Modifies the hue of the target as defined by source
`imagick::COMPOSITE_IN` (int)
  Composites source into the target
`imagick::COMPOSITE_LIGHTEN` (int)
  Lightens the target as defined by source
`imagick::COMPOSITE_LUMINIZE` (int)
  Luminizes the target as defined by source
`imagick::COMPOSITE_MINUS` (int)
  Subtracts the source from the target
`imagick::COMPOSITE_MODULATE` (int)
  Modulates the target brightness, saturation and hue as defined by source
`imagick::COMPOSITE_MULTIPLY` (int)
  Multiplies the target to the source
`imagick::COMPOSITE_OUT` (int)
  Composites outer parts of the source on the target
`imagick::COMPOSITE_OVER` (int)
  Composites source over the target
`imagick::COMPOSITE_OVERLAY` (int)
  Overlays the source on the target
`imagick::COMPOSITE_PLUS` (int)
  Adds the source to the target
`imagick::COMPOSITE_REPLACE` (int)
  Replaces the target with the source
`imagick::COMPOSITE_SATURATE` (int)
  Saturates the target as defined by the source
`imagick::COMPOSITE_SCREEN` (int)
  The source and destination are complemented and then multiplied and then replace the destination
`imagick::COMPOSITE_SOFTLIGHT` (int)
  Darkens or lightens the colors, dependent on the source
`imagick::COMPOSITE_SRCATOP` (int)
  The part of the source lying inside of the destination is composited onto the destination
`imagick::COMPOSITE_SRC` (int)
  The source is copied to the destination
`imagick::COMPOSITE_SRCIN` (int)
  The part of the source lying inside of the destination replaces the destination
`imagick::COMPOSITE_SRCOUT` (int)
  The part of the source lying outside of the destination replaces the destination
`imagick::COMPOSITE_SRCOVER` (int)
  The source replaces the destination
`imagick::COMPOSITE_SUBTRACT` (int)
  Subtract the colors in the source image from the destination image
`imagick::COMPOSITE_THRESHOLD` (int)
  The source is composited on the target as defined by source threshold
`imagick::COMPOSITE_XOR` (int)
  The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source

`MONTAGEMODE_*` constants

`imagick::MONTAGEMODE_FRAME` (int)
`imagick::MONTAGEMODE_UNFRAME` (int)
`imagick::MONTAGEMODE_CONCATENATE` (int)

`STYLE_*` constants

`imagick::STYLE_NORMAL` (int)
`imagick::STYLE_ITALIC` (int)
`imagick::STYLE_OBLIQUE` (int)
`imagick::STYLE_ANY` (int)

`FILTER_*` constants

`imagick::FILTER_UNDEFINED` (int)
`imagick::FILTER_POINT` (int)
`imagick::FILTER_BOX` (int)
`imagick::FILTER_TRIANGLE` (int)
`imagick::FILTER_HERMITE` (int)
`imagick::FILTER_HANNING` (int)
`imagick::FILTER_HAMMING` (int)
`imagick::FILTER_BLACKMAN` (int)
`imagick::FILTER_GAUSSIAN` (int)
`imagick::FILTER_QUADRATIC` (int)
`imagick::FILTER_CUBIC` (int)
`imagick::FILTER_CATROM` (int)
`imagick::FILTER_MITCHELL` (int)
`imagick::FILTER_LANCZOS` (int)
`imagick::FILTER_BESSEL` (int)
`imagick::FILTER_SINC` (int)

`IMGTYPE_*` constants

`imagick::IMGTYPE_UNDEFINED` (int)
`imagick::IMGTYPE_BILEVEL` (int)
`imagick::IMGTYPE_GRAYSCALE` (int)
`imagick::IMGTYPE_GRAYSCALEMATTE` (int)
`imagick::IMGTYPE_PALETTE` (int)
`imagick::IMGTYPE_PALETTEMATTE` (int)
`imagick::IMGTYPE_TRUECOLOR` (int)
`imagick::IMGTYPE_TRUECOLORMATTE` (int)
`imagick::IMGTYPE_COLORSEPARATION` (int)
`imagick::IMGTYPE_COLORSEPARATIONMATTE` (int)
`imagick::IMGTYPE_OPTIMIZE` (int)

`RESOLUTION_*` constants

`imagick::RESOLUTION_UNDEFINED` (int)
`imagick::RESOLUTION_PIXELSPERINCH` (int)
`imagick::RESOLUTION_PIXELSPERCENTIMETER` (int)

`COMPRESSION_*` constants

`imagick::COMPRESSION_UNDEFINED` (int)
`imagick::COMPRESSION_NO` (int)
`imagick::COMPRESSION_BZIP` (int)
`imagick::COMPRESSION_FAX` (int)
`imagick::COMPRESSION_GROUP4` (int)
`imagick::COMPRESSION_JPEG` (int)
`imagick::COMPRESSION_JPEG2000` (int)
`imagick::COMPRESSION_LOSSLESSJPEG` (int)
`imagick::COMPRESSION_LZW` (int)
`imagick::COMPRESSION_RLE` (int)
`imagick::COMPRESSION_ZIP` (int)
`imagick::COMPRESSION_DXT1` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
`imagick::COMPRESSION_DXT3` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
`imagick::COMPRESSION_DXT5` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.

`PAINT_*` constants

`imagick::PAINT_POINT` (int)
`imagick::PAINT_REPLACE` (int)
`imagick::PAINT_FLOODFILL` (int)
`imagick::PAINT_FILLTOBORDER` (int)
`imagick::PAINT_RESET` (int)

`GRAVITY_*` constants

`imagick::GRAVITY_NORTHWEST` (int)
`imagick::GRAVITY_NORTH` (int)
`imagick::GRAVITY_NORTHEAST` (int)
`imagick::GRAVITY_WEST` (int)
`imagick::GRAVITY_CENTER` (int)
`imagick::GRAVITY_EAST` (int)
`imagick::GRAVITY_SOUTHWEST` (int)
`imagick::GRAVITY_SOUTH` (int)
`imagick::GRAVITY_SOUTHEAST` (int)

`STRETCH_*` constants

`imagick::STRETCH_NORMAL` (int)
`imagick::STRETCH_ULTRACONDENSED` (int)
`imagick::STRETCH_CONDENSED` (int)
`imagick::STRETCH_SEMICONDENSED` (int)
`imagick::STRETCH_SEMIEXPANDED` (int)
`imagick::STRETCH_EXPANDED` (int)
`imagick::STRETCH_EXTRAEXPANDED` (int)
`imagick::STRETCH_ULTRAEXPANDED` (int)
`imagick::STRETCH_ANY` (int)

`ALIGN_*` constants

`imagick::ALIGN_UNDEFINED` (int)
`imagick::ALIGN_LEFT` (int)
`imagick::ALIGN_CENTER` (int)
`imagick::ALIGN_RIGHT` (int)

`DECORATION_*` constants

`imagick::DECORATION_NO` (int)
`imagick::DECORATION_UNDERLINE` (int)
`imagick::DECORATION_OVERLINE` (int)
`imagick::DECORATION_LINETROUGH` (int)

`NOISE_*` constants

`imagick::NOISE_UNIFORM` (int)
`imagick::NOISE_GAUSSIAN` (int)
`imagick::NOISE_MULTIPLICATIVEGAUSSIAN` (int)
`imagick::NOISE_IMPULSE` (int)
`imagick::NOISE_LAPLACIAN` (int)
`imagick::NOISE_POISSON` (int)
`imagick::NOISE_RANDOM` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.

`CHANNEL_*` constants

`imagick::CHANNEL_UNDEFINED` (int)
`imagick::CHANNEL_RED` (int)
`imagick::CHANNEL_GRAY` (int)
`imagick::CHANNEL_CYAN` (int)
`imagick::CHANNEL_GREEN` (int)
`imagick::CHANNEL_MAGENTA` (int)
`imagick::CHANNEL_BLUE` (int)
`imagick::CHANNEL_YELLOW` (int)
`imagick::CHANNEL_ALPHA` (int)
`imagick::CHANNEL_OPACITY` (int)
`imagick::CHANNEL_MATTE` (int)
`imagick::CHANNEL_BLACK` (int)
`imagick::CHANNEL_INDEX` (int)
`imagick::CHANNEL_ALL` (int)
`imagick::CHANNEL_DEFAULT` (int)

`METRIC_*` constants

`imagick::METRIC_UNDEFINED` (int)
`imagick::METRIC_MEANABSOLUTEERROR` (int)
`imagick::METRIC_MEANSQUAREERROR` (int)
`imagick::METRIC_PEAKABSOLUTEERROR` (int)
`imagick::METRIC_PEAKSIGNALTONOISERATIO` (int)
`imagick::METRIC_ROOTMEANSQUAREDERROR` (int)

`PIXEL_*` constants

`imagick::PIXEL_CHAR` (int)
`imagick::PIXEL_DOUBLE` (int)
`imagick::PIXEL_FLOAT` (int)
`imagick::PIXEL_INTEGER` (int)
  Only available for ImageMagick < 7.
`imagick::PIXEL_LONG` (int)
`imagick::PIXEL_QUANTUM` (int)
`imagick::PIXEL_SHORT` (int)

`EVALUATE_*` constants

`imagick::EVALUATE_UNDEFINED` (int)
`imagick::EVALUATE_ADD` (int)
`imagick::EVALUATE_AND` (int)
`imagick::EVALUATE_DIVIDE` (int)
`imagick::EVALUATE_LEFTSHIFT` (int)
`imagick::EVALUATE_MAX` (int)
`imagick::EVALUATE_MIN` (int)
`imagick::EVALUATE_MULTIPLY` (int)
`imagick::EVALUATE_OR` (int)
`imagick::EVALUATE_RIGHTSHIFT` (int)
`imagick::EVALUATE_SET` (int)
`imagick::EVALUATE_SUBTRACT` (int)
`imagick::EVALUATE_XOR` (int)
`imagick::EVALUATE_POW` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_LOG` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_THRESHOLD` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_THRESHOLDBLACK` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_THRESHOLDWHITE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_GAUSSIANNOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_IMPULSENOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_LAPLACIANNOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_MULTIPLICATIVENOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_POISSONNOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_UNIFORMNOISE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_COSINE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_SINE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
`imagick::EVALUATE_ADDMODULUS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.

`COLORSPACE_*` constants

`imagick::COLORSPACE_UNDEFINED` (int)
`imagick::COLORSPACE_RGB` (int)
`imagick::COLORSPACE_GRAY` (int)
`imagick::COLORSPACE_TRANSPARENT` (int)
`imagick::COLORSPACE_OHTA` (int)
`imagick::COLORSPACE_LAB` (int)
`imagick::COLORSPACE_XYZ` (int)
`imagick::COLORSPACE_YCBCR` (int)
`imagick::COLORSPACE_YCC` (int)
`imagick::COLORSPACE_YIQ` (int)
`imagick::COLORSPACE_YPBPR` (int)
`imagick::COLORSPACE_YUV` (int)
`imagick::COLORSPACE_CMYK` (int)
`imagick::COLORSPACE_SRGB` (int)
`imagick::COLORSPACE_HSB` (int)
`imagick::COLORSPACE_HSL` (int)
`imagick::COLORSPACE_HWB` (int)
`imagick::COLORSPACE_REC601LUMA` (int)
`imagick::COLORSPACE_REC709LUMA` (int)
`imagick::COLORSPACE_LOG` (int)
`imagick::COLORSPACE_CMY` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.

`VIRTUALPIXELMETHOD_*` constants

`imagick::VIRTUALPIXELMETHOD_UNDEFINED` (int)
`imagick::VIRTUALPIXELMETHOD_BACKGROUND` (int)
`imagick::VIRTUALPIXELMETHOD_CONSTANT` (int)
`imagick::VIRTUALPIXELMETHOD_EDGE` (int)
`imagick::VIRTUALPIXELMETHOD_MIRROR` (int)
`imagick::VIRTUALPIXELMETHOD_TILE` (int)
`imagick::VIRTUALPIXELMETHOD_TRANSPARENT` (int)
`imagick::VIRTUALPIXELMETHOD_MASK` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
`imagick::VIRTUALPIXELMETHOD_BLACK` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
`imagick::VIRTUALPIXELMETHOD_GRAY` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
`imagick::VIRTUALPIXELMETHOD_WHITE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
`imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
`imagick::VIRTUALPIXELMETHOD_VERTICALTILE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.

`PREVIEW_*` constants

`imagick::PREVIEW_UNDEFINED` (int)
`imagick::PREVIEW_ROTATE` (int)
`imagick::PREVIEW_SHEAR` (int)
`imagick::PREVIEW_ROLL` (int)
`imagick::PREVIEW_HUE` (int)
`imagick::PREVIEW_SATURATION` (int)
`imagick::PREVIEW_BRIGHTNESS` (int)
`imagick::PREVIEW_GAMMA` (int)
`imagick::PREVIEW_SPIFF` (int)
`imagick::PREVIEW_DULL` (int)
`imagick::PREVIEW_GRAYSCALE` (int)
`imagick::PREVIEW_QUANTIZE` (int)
`imagick::PREVIEW_DESPECKLE` (int)
`imagick::PREVIEW_REDUCENOISE` (int)
`imagick::PREVIEW_ADDNOISE` (int)
`imagick::PREVIEW_SHARPEN` (int)
`imagick::PREVIEW_BLUR` (int)
`imagick::PREVIEW_THRESHOLD` (int)
`imagick::PREVIEW_EDGEDETECT` (int)
`imagick::PREVIEW_SPREAD` (int)
`imagick::PREVIEW_SOLARIZE` (int)
`imagick::PREVIEW_SHADE` (int)
`imagick::PREVIEW_RAISE` (int)
`imagick::PREVIEW_SEGMENT` (int)
`imagick::PREVIEW_SWIRL` (int)
`imagick::PREVIEW_IMPLODE` (int)
`imagick::PREVIEW_WAVE` (int)
`imagick::PREVIEW_OILPAINT` (int)
`imagick::PREVIEW_CHARCOALDRAWING` (int)
`imagick::PREVIEW_JPEG` (int)

`RENDERINGINTENT_*` constants

`imagick::RENDERINGINTENT_UNDEFINED` (int)
`imagick::RENDERINGINTENT_SATURATION` (int)
`imagick::RENDERINGINTENT_PERCEPTUAL` (int)
`imagick::RENDERINGINTENT_ABSOLUTE` (int)
`imagick::RENDERINGINTENT_RELATIVE` (int)

`INTERLACE_*` constants

`imagick::INTERLACE_UNDEFINED` (int)
`imagick::INTERLACE_NO` (int)
`imagick::INTERLACE_LINE` (int)
`imagick::INTERLACE_PLANE` (int)
`imagick::INTERLACE_PARTITION` (int)
`imagick::INTERLACE_GIF` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
`imagick::INTERLACE_JPEG` (int)
`imagick::INTERLACE_PNG` (int)

`FILLRULE_*` constants

`imagick::FILLRULE_UNDEFINED` (int)
`imagick::FILLRULE_EVENODD` (int)
`imagick::FILLRULE_NONZERO` (int)

`PATHUNITS_*` constants

`imagick::PATHUNITS_UNDEFINED` (int)
`imagick::PATHUNITS_USERSPACE` (int)
`imagick::PATHUNITS_USERSPACEONUSE` (int)
`imagick::PATHUNITS_OBJECTBOUNDINGBOX` (int)

`LINECAP_*` constants

`imagick::LINECAP_UNDEFINED` (int)
`imagick::LINECAP_BUTT` (int)
`imagick::LINECAP_ROUND` (int)
`imagick::LINECAP_SQUARE` (int)

`LINEJOIN_*` constants

`imagick::LINEJOIN_UNDEFINED` (int)
`imagick::LINEJOIN_MITER` (int)
`imagick::LINEJOIN_ROUND` (int)
`imagick::LINEJOIN_BEVEL` (int)

`RESOURCETYPE_*` constants

`imagick::RESOURCETYPE_UNDEFINED` (int)
`imagick::RESOURCETYPE_AREA` (int)
  Set the maximum width * height of an image that can reside in the pixel cache memory.
`imagick::RESOURCETYPE_DISK` (int)
  Set maximum amount of disk space in bytes permitted for use by the pixel cache.
`imagick::RESOURCETYPE_FILE` (int)
  Set maximum number of open pixel cache files.
`imagick::RESOURCETYPE_MAP` (int)
  Set maximum amount of memory map in bytes to allocate for the pixel cache.
`imagick::RESOURCETYPE_MEMORY` (int)
  Set maximum amount of memory in bytes to allocate for the pixel cache from the heap.
`imagick::RESOURCETYPE_THREAD` (int)
  Set maximum parallel threads. This constant is available if Imagick has been compiled against ImageMagick version 6.7.8 or higher.

`LAYERMETHOD_*` constants

`imagick::LAYERMETHOD_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_COALESCE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_COMPAREANY` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_COMPARECLEAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_COMPAREOVERLAY` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_DISPOSE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_OPTIMIZE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_OPTIMIZEPLUS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
`imagick::LAYERMETHOD_OPTIMIZEIMAGE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::LAYERMETHOD_OPTIMIZETRANS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::LAYERMETHOD_REMOVEDUPS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::LAYERMETHOD_REMOVEZERO` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::LAYERMETHOD_COMPOSITE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::LAYERMETHOD_MERGE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
`imagick::LAYERMETHOD_FLATTEN` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
`imagick::LAYERMETHOD_MOSAIC` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.

`ORIENTATION_*` constants

`imagick::ORIENTATION_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_TOPLEFT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_TOPRIGHT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_BOTTOMRIGHT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_BOTTOMLEFT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_LEFTTOP` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_RIGHTTOP` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_RIGHTBOTTOM` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
`imagick::ORIENTATION_LEFTBOTTOM` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.

`DISTORTION_*` constants

`imagick::DISTORTION_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_AFFINE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_AFFINEPROJECTION` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_ARC` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_BILINEAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_PERSPECTIVE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_PERSPECTIVEPROJECTION` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_SCALEROTATETRANSLATE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
`imagick::DISTORTION_POLYNOMIAL` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_POLAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_DEPOLAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_BARREL` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_BARRELINVERSE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_SHEPARDS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DISTORTION_SENTINEL` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.

`ALPHACHANNEL_*` constants

`imagick::ALPHACHANNEL_ACTIVATE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
`imagick::ALPHACHANNEL_DEACTIVATE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
`imagick::ALPHACHANNEL_RESET` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
`imagick::ALPHACHANNEL_SET` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
`imagick::ALPHACHANNEL_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_COPY` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_EXTRACT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_OPAQUE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_SHAPE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_TRANSPARENT` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::ALPHACHANNEL_BACKGROUND` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.5.3 or higher.
`imagick::ALPHACHANNEL_REMOVE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.7.8 or higher.
`imagick::ALPHACHANNEL_ASSOCIATE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.9.0 or higher.
`imagick::ALPHACHANNEL_DISSOCIATE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.9.0 or higher.
`imagick::ALPHACHANNEL_ON` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 7.0.0 or higher.
`imagick::ALPHACHANNEL_OFF` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 7.0.0 or higher.
`imagick::ALPHACHANNEL_DISCRETE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 7.0.0 or higher.

`SPARSECOLORMETHOD_*` constants

`imagick::SPARSECOLORMETHOD_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::SPARSECOLORMETHOD_BARYCENTRIC` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::SPARSECOLORMETHOD_BILINEAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::SPARSECOLORMETHOD_POLYNOMIAL` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::SPARSECOLORMETHOD_SPEPARDS` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::SPARSECOLORMETHOD_VORONOI` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.

`FUNCTION_*` constants

`imagick::FUNCTION_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
`imagick::FUNCTION_POLYNOMIAL` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
`imagick::FUNCTION_SINUSOID` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.

`INTERPOLATE_*` constants

`imagick::INTERPOLATE_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_AVERAGE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_BICUBIC` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_BILINEAR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_FILTER` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_INTEGER` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_MESH` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_NEARESTNEIGHBOR` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
`imagick::INTERPOLATE_SPLINE` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.

`DITHERMETHOD_*` constants

`imagick::DITHERMETHOD_UNDEFINED` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DITHERMETHOD_NO` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DITHERMETHOD_RIEMERSMA` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
`imagick::DITHERMETHOD_FLOYDSTEINBERG` (int)
  This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.

# Examples

## Table of Contents

- Basic usage

## Basic usage

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

Example #1 Creating a thumbnail in Imagick

`<?php
header('Content-type: image/jpeg');
$image = new Imagick('image.jpg');
// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);
echo $image;
?>`

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Example #2 Make a thumbnail of all JPG files in a directory

`<?php
$images = new Imagick(glob('images/*.JPG'));
foreach($images as $image) {
// Providing 0 forces thumbnailImage to maintain aspect ratio
$image->thumbnailImage(1024,0);
}
$images->writeImages();
?>`

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Example #3 Creating a reflection of an image

`<?php
/* Read the image */
$im = new Imagick("test.png");
/* Thumbnail the image */
$im->thumbnailImage(200, null);
/* Create a border for the image */
$im->borderImage(new ImagickPixel("white"), 5, 5);
/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();
/* Create gradient. It will be overlayed on the reflection */
$gradient = new Imagick();
/* Gradient needs to be large enough for the image and the borders */
$gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");
/* Composite the gradient on the reflection */
$reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);
/* Add some opacity. Requires ImageMagick 6.2.9 or later */
$reflection->setImageOpacity( 0.3 );
/* Create an empty canvas */
$canvas = new Imagick();
/* Canvas needs to be large enough to hold the both images */
$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;
$canvas->newImage($width, $height, new ImagickPixel("black"));
$canvas->setImageFormat("png");
/* Composite the original image and the reflection on the canvas */
$canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
$canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);
/* Output the image*/
header("Content-Type: image/png");
echo $canvas;
?>`

The above example will output something similar to:

This example illustrates how to use fill patterns during drawing.

Example #4 Filling text with gradient

`<?php
/* Create a new imagick object */
$im = new Imagick();
/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");
/* Create imagickdraw object */
$draw = new ImagickDraw();
/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);
/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);
/* Close the pattern */
$draw->popPattern();
/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');
/* Set font size to 52 */
$draw->setFontSize(52);
/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");
/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");
/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);
/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);
/* Set the format to PNG */
$canvas->setImageFormat('png');
/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>`

The above example will output something similar to:

Working with animated GIF images

Example #5 Read in GIF image and resize all frames

`<?php
/* Create a new imagick object and read in GIF */
$im = new Imagick("example.gif");
/* Resize all frames */
foreach ($im as $frame) {
/* 50x50 frames */
$frame->thumbnailImage(50, 50);
/* Set the virtual canvas to correct size */
$frame->setImagePage(50, 50, 0, 0);
}
/* Notice writeImages instead of writeImage */
$im->writeImages("example_small.gif", true);
?>`

Working with ellipse primitive and custom fonts

Example #6 Create a PHP logo

`<?php
/* Set width and height in proportion of genuine PHP logo */
$width = 400;
$height = 210;
/* Create an Imagick object with transparent canvas */
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));
/* New ImagickDraw instance for ellipse draw */
$draw = new ImagickDraw();
/* Set purple fill color for ellipse */
$draw->setFillColor('#777bb4');
/* Set ellipse dimensions */
$draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
/* Draw ellipse onto the canvas */
$img->drawImage($draw);
/* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
$draw->setFillColor('black');
/* Set stroke border to white color */
$draw->setStrokeColor('white');
/* Set stroke border thickness */
$draw->setStrokeWidth(2);
/* Set font kerning (negative value means that letters are closer to each other) */
$draw->setTextKerning(-8);
/* Set font and font size used in PHP logo */
$draw->setFont('Handel Gothic.ttf');
$draw->setFontSize(150);
/* Center text horizontally and vertically */
$draw->setGravity(Imagick::GRAVITY_CENTER);
/* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
$img->annotateImage($draw, 0, -10, 0, 'php');
$img->setImageFormat('png');
/* Set appropriate header for PNG and output the image */
header('Content-Type: image/png');
echo $img;
?>`

The above example will output something similar to:

# The Imagick class

(PECL imagick 2, PECL imagick 3)

## Class synopsis

class Imagick implements Iterator {
public __construct(mixed `$files` = ?)
public adaptiveBlurImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public adaptiveResizeImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool
public adaptiveSharpenImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public adaptiveThresholdImage(int `$width`, int `$height`, int `$offset`): bool
public addImage(Imagick `$source`): bool
public addNoiseImage(int `$noise_type`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public affineTransformImage(ImagickDraw `$matrix`): bool
public animateImages(string `$x_server`): bool
public annotateImage(
ImagickDraw `$draw_settings`,
float `$x`,
float `$y`,
float `$angle`,
string `$text`
): bool
public appendImages(bool `$stack`): Imagick
public autoLevelImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public averageImages(): Imagick
public blackThresholdImage(mixed `$threshold`): bool
public blueShiftImage(float `$factor` = 1.5): bool
public blurImage(float `$radius`, float `$sigma`, int `$channel` = ?): bool
public borderImage(mixed `$bordercolor`, int `$width`, int `$height`): bool
public brightnessContrastImage(float `$brightness`, float `$contrast`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public charcoalImage(float `$radius`, float `$sigma`): bool
public chopImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public clampImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public clear(): bool
public clipImage(): bool
public clipImagePath(string `$pathname`, string `$inside`): void
public clipPathImage(string `$pathname`, bool `$inside`): bool
public clone(): Imagick
public clutImage(Imagick `$lookup_table`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public coalesceImages(): Imagick
public colorFloodfillImage(
mixed `$fill`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`
): bool
public colorizeImage(mixed `$colorize`, mixed `$opacity`, bool `$legacy` = `false`): bool
public colorMatrixImage(array `$color_matrix`): bool
public combineImages(int `$channelType`): Imagick
public commentImage(string `$comment`): bool
public compareImageChannels(Imagick `$image`, int `$channelType`, int `$metricType`): array
public compareImageLayers(int `$method`): Imagick
public compareImages(Imagick `$compare`, int `$metric`): array
public compositeImage(
Imagick `$composite_object`,
int `$composite`,
int `$x`,
int `$y`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public contrastImage(bool `$sharpen`): bool
public contrastStretchImage(float `$black_point`, float `$white_point`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public convolveImage(array `$kernel`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public count(int `$mode` = 0): int
public cropImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public cropThumbnailImage(int `$width`, int `$height`, bool `$legacy` = `false`): bool
public current(): Imagick
public cycleColormapImage(int `$displace`): bool
public decipherImage(string `$passphrase`): bool
public deconstructImages(): Imagick
public deleteImageArtifact(string `$artifact`): bool
public deleteImageProperty(string `$name`): bool
public deskewImage(float `$threshold`): bool
public despeckleImage(): bool
public destroy(): bool
public displayImage(string `$servername`): bool
public displayImages(string `$servername`): bool
public distortImage(int `$method`, array `$arguments`, bool `$bestfit`): bool
public drawImage(ImagickDraw `$draw`): bool
public edgeImage(float `$radius`): bool
public embossImage(float `$radius`, float `$sigma`): bool
public encipherImage(string `$passphrase`): bool
public enhanceImage(): bool
public equalizeImage(): bool
public evaluateImage(int `$op`, float `$constant`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public exportImagePixels(
int `$x`,
int `$y`,
int `$width`,
int `$height`,
string `$map`,
int `$STORAGE`
): array
public extentImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public filter(ImagickKernel `$ImagickKernel`, int `$channel` = Imagick::CHANNEL_UNDEFINED): bool
public flattenImages(): Imagick
public flipImage(): bool
public floodFillPaintImage(
mixed `$fill`,
float `$fuzz`,
mixed `$target`,
int `$x`,
int `$y`,
bool `$invert`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public flopImage(): bool
public forwardFourierTransformimage(bool `$magnitude`): bool
public frameImage(
mixed `$matte_color`,
int `$width`,
int `$height`,
int `$inner_bevel`,
int `$outer_bevel`
): bool
public functionImage(int `$function`, array `$arguments`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public fxImage(string `$expression`, int `$channel` = Imagick::CHANNEL_DEFAULT): Imagick
public gammaImage(float `$gamma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public gaussianBlurImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public getColorspace(): int
public getCompression(): int
public getCompressionQuality(): int
public static getCopyright(): string
public getFilename(): string
public getFont(): string
public getFormat(): string
public getGravity(): int
public static getHomeURL(): string
public getImage(): Imagick
public getImageAlphaChannel(): bool
public getImageArtifact(string `$artifact`): string
public getImageAttribute(string `$key`): string
public getImageBackgroundColor(): ImagickPixel
public getImageBlob(): string
public getImageBluePrimary(): array
public getImageBorderColor(): ImagickPixel
public getImageChannelDepth(int `$channel`): int
public getImageChannelDistortion(Imagick `$reference`, int `$channel`, int `$metric`): float
public getImageChannelDistortions(Imagick `$reference`, int `$metric`, int `$channel` = Imagick::CHANNEL_DEFAULT): float
public getImageChannelExtrema(int `$channel`): array
public getImageChannelKurtosis(int `$channel` = Imagick::CHANNEL_DEFAULT): array
public getImageChannelMean(int `$channel`): array
public getImageChannelRange(int `$channel`): array
public getImageChannelStatistics(): array
public getImageClipMask(): Imagick
public getImageColormapColor(int `$index`): ImagickPixel
public getImageColors(): int
public getImageColorspace(): int
public getImageCompose(): int
public getImageCompression(): int
public getImageCompressionQuality(): int
public getImageDelay(): int
public getImageDepth(): int
public getImageDispose(): int
public getImageDistortion(MagickWand `$reference`, int `$metric`): float
public getImageExtrema(): array
public getImageFilename(): string
public getImageFormat(): string
public getImageGamma(): float
public getImageGeometry(): array
public getImageGravity(): int
public getImageGreenPrimary(): array
public getImageHeight(): int
public getImageHistogram(): array
public getImageIndex(): int
public getImageInterlaceScheme(): int
public getImageInterpolateMethod(): int
public getImageIterations(): int
public getImageLength(): int
public getImageMatte(): bool
public getImageMatteColor(): ImagickPixel
public getImageMimeType(): string
public getImageOrientation(): int
public getImagePage(): array
public getImagePixelColor(int `$x`, int `$y`): ImagickPixel
public getImageProfile(string `$name`): string
public getImageProfiles(string `$pattern` = "*", bool `$include_values` = `true`): array
public getImageProperties(string `$pattern` = "*", bool `$include_values` = `true`): array
public getImageProperty(string `$name`): string
public getImageRedPrimary(): array
public getImageRegion(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): Imagick
public getImageRenderingIntent(): int
public getImageResolution(): array
public getImagesBlob(): string
public getImageScene(): int
public getImageSignature(): string
public getImageSize(): int
public getImageTicksPerSecond(): int
public getImageTotalInkDensity(): float
public getImageType(): int
public getImageUnits(): int
public getImageVirtualPixelMethod(): int
public getImageWhitePoint(): array
public getImageWidth(): int
public getInterlaceScheme(): int
public getIteratorIndex(): int
public getNumberImages(): int
public getOption(string `$key`): string
public static getPackageName(): string
public getPage(): array
public getPixelIterator(): ImagickPixelIterator
public getPixelRegionIterator(
int `$x`,
int `$y`,
int `$columns`,
int `$rows`
): ImagickPixelIterator
public getPointSize(): float
public static getQuantum(): int
public static getQuantumDepth(): array
public static getQuantumRange(): array
public static getRegistry(string `$key`): string
public static getReleaseDate(): string
public static getResource(int `$type`): int
public static getResourceLimit(int `$type`): int
public getSamplingFactors(): array
public getSize(): array
public getSizeOffset(): int
public static getVersion(): array
public haldClutImage(Imagick `$clut`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public hasNextImage(): bool
public hasPreviousImage(): bool
public identifyFormat(string `$embedText`): string|false
public identifyImage(bool `$appendRawOutput` = `false`): array
public implodeImage(float `$radius`): bool
public importImagePixels(
int `$x`,
int `$y`,
int `$width`,
int `$height`,
string `$map`,
int `$storage`,
array `$pixels`
): bool
public inverseFourierTransformImage(Imagick `$complement`, bool `$magnitude`): bool
public labelImage(string `$label`): bool
public levelImage(
float `$blackPoint`,
float `$gamma`,
float `$whitePoint`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public linearStretchImage(float `$blackPoint`, float `$whitePoint`): bool
public liquidRescaleImage(
int `$width`,
int `$height`,
float `$delta_x`,
float `$rigidity`
): bool
public static listRegistry(): array
public magnifyImage(): bool
public mapImage(Imagick `$map`, bool `$dither`): bool
public matteFloodfillImage(
float `$alpha`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`
): bool
public medianFilterImage(float `$radius`): bool
public mergeImageLayers(int `$layer_method`): Imagick
public minifyImage(): bool
public modulateImage(float `$brightness`, float `$saturation`, float `$hue`): bool
public montageImage(
ImagickDraw `$draw`,
string `$tile_geometry`,
string `$thumbnail_geometry`,
int `$mode`,
string `$frame`
): Imagick
public morphImages(int `$number_frames`): Imagick
public morphology(
int `$morphologyMethod`,
int `$iterations`,
ImagickKernel `$ImagickKernel`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public mosaicImages(): Imagick
public motionBlurImage(
float `$radius`,
float `$sigma`,
float `$angle`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public negateImage(bool `$gray`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public newImage(
int `$cols`,
int `$rows`,
mixed `$background`,
string `$format` = ?
): bool
public newPseudoImage(int `$columns`, int `$rows`, string `$pseudoString`): bool
public nextImage(): bool
public normalizeImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public oilPaintImage(float `$radius`): bool
public opaquePaintImage(
mixed `$target`,
mixed `$fill`,
float `$fuzz`,
bool `$invert`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public optimizeImageLayers(): bool
public orderedPosterizeImage(string `$threshold_map`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public paintFloodfillImage(
mixed `$fill`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public paintOpaqueImage(
mixed `$target`,
mixed `$fill`,
float `$fuzz`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public paintTransparentImage(mixed `$target`, float `$alpha`, float `$fuzz`): bool
public pingImage(string `$filename`): bool
public pingImageBlob(string `$image`): bool
public pingImageFile(resource `$filehandle`, string `$fileName` = ?): bool
public polaroidImage(ImagickDraw `$properties`, float `$angle`): bool
public posterizeImage(int `$levels`, bool `$dither`): bool
public previewImages(int `$preview`): bool
public previousImage(): bool
public profileImage(string `$name`, string `$profile` = ?): bool
public quantizeImage(
int `$numberColors`,
int `$colorspace`,
int `$treedepth`,
bool `$dither`,
bool `$measureError`
): bool
public quantizeImages(
int `$numberColors`,
int `$colorspace`,
int `$treedepth`,
bool `$dither`,
bool `$measureError`
): bool
public queryFontMetrics(ImagickDraw `$properties`, string `$text`, bool `$multiline` = ?): array
public static queryFonts(string `$pattern` = "*"): array
public static queryFormats(string `$pattern` = "*"): array
public radialBlurImage(float `$angle`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public raiseImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`,
bool `$raise`
): bool
public randomThresholdImage(float `$low`, float `$high`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public readImage(string `$filename`): bool
public readImageBlob(string `$image`, string `$filename` = ?): bool
public readImageFile(resource `$filehandle`, string `$fileName` = `null`): bool
public readImages(array `$filenames`): bool
public recolorImage(array `$matrix`): bool
public reduceNoiseImage(float `$radius`): bool
public remapImage(Imagick `$replacement`, int `$DITHER`): bool
public removeImage(): bool
public removeImageProfile(string `$name`): string
public render(): bool
public resampleImage(
float `$x_resolution`,
float `$y_resolution`,
int `$filter`,
float `$blur`
): bool
public resetImagePage(string `$page`): bool
public resizeImage(
int `$columns`,
int `$rows`,
int `$filter`,
float `$blur`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool
public rollImage(int `$x`, int `$y`): bool
public rotateImage(mixed `$background`, float `$degrees`): bool
public rotationalBlurImage(float `$angle`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public roundCorners(
float `$x_rounding`,
float `$y_rounding`,
float `$stroke_width` = 10,
float `$displace` = 5,
float `$size_correction` = -6
): bool
public sampleImage(int `$columns`, int `$rows`): bool
public scaleImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool
public segmentImage(
int `$COLORSPACE`,
float `$cluster_threshold`,
float `$smooth_threshold`,
bool `$verbose` = `false`
): bool
public selectiveBlurImage(
float `$radius`,
float `$sigma`,
float `$threshold`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public separateImageChannel(int `$channel`): bool
public sepiaToneImage(float `$threshold`): bool
public setBackgroundColor(mixed `$background`): bool
public setColorspace(int `$COLORSPACE`): bool
public setCompression(int `$compression`): bool
public setCompressionQuality(int `$quality`): bool
public setFilename(string `$filename`): bool
public setFirstIterator(): bool
public setFont(string `$font`): bool
public setFormat(string `$format`): bool
public setGravity(int `$gravity`): bool
public setImage(Imagick `$replace`): bool
public setImageAlphaChannel(int `$mode`): bool
public setImageArtifact(string `$artifact`, string `$value`): bool
public setImageAttribute(string `$key`, string `$value`): bool
public setImageBackgroundColor(mixed `$background`): bool
public setImageBias(float `$bias`): bool
public setImageBiasQuantum(float `$bias`): void
public setImageBluePrimary(float `$x`, float `$y`): bool
public setImageBorderColor(mixed `$border`): bool
public setImageChannelDepth(int `$channel`, int `$depth`): bool
public setImageClipMask(Imagick `$clip_mask`): bool
public setImageColormapColor(int `$index`, ImagickPixel `$color`): bool
public setImageColorspace(int `$colorspace`): bool
public setImageCompose(int `$compose`): bool
public setImageCompression(int `$compression`): bool
public setImageCompressionQuality(int `$quality`): bool
public setImageDelay(int `$delay`): bool
public setImageDepth(int `$depth`): bool
public setImageDispose(int `$dispose`): bool
public setImageExtent(int `$columns`, int `$rows`): bool
public setImageFilename(string `$filename`): bool
public setImageFormat(string `$format`): bool
public setImageGamma(float `$gamma`): bool
public setImageGravity(int `$gravity`): bool
public setImageGreenPrimary(float `$x`, float `$y`): bool
public setImageIndex(int `$index`): bool
public setImageInterlaceScheme(int `$interlace_scheme`): bool
public setImageInterpolateMethod(int `$method`): bool
public setImageIterations(int `$iterations`): bool
public setImageMatte(bool `$matte`): bool
public setImageMatteColor(mixed `$matte`): bool
public setImageOpacity(float `$opacity`): bool
public setImageOrientation(int `$orientation`): bool
public setImagePage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public setImageProfile(string `$name`, string `$profile`): bool
public setImageProperty(string `$name`, string `$value`): bool
public setImageRedPrimary(float `$x`, float `$y`): bool
public setImageRenderingIntent(int `$rendering_intent`): bool
public setImageResolution(float `$x_resolution`, float `$y_resolution`): bool
public setImageScene(int `$scene`): bool
public setImageTicksPerSecond(int `$ticks_per_second`): bool
public setImageType(int `$image_type`): bool
public setImageUnits(int `$units`): bool
public setImageVirtualPixelMethod(int `$method`): bool
public setImageWhitePoint(float `$x`, float `$y`): bool
public setInterlaceScheme(int `$interlace_scheme`): bool
public setIteratorIndex(int `$index`): bool
public setLastIterator(): bool
public setOption(string `$key`, string `$value`): bool
public setPage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public setPointSize(float `$point_size`): bool
public setProgressMonitor(callable `$callback`): bool
public static setRegistry(string `$key`, string `$value`): bool
public setResolution(float `$x_resolution`, float `$y_resolution`): bool
public static setResourceLimit(int `$type`, int `$limit`): bool
public setSamplingFactors(array `$factors`): bool
public setSize(int `$columns`, int `$rows`): bool
public setSizeOffset(int `$columns`, int `$rows`, int `$offset`): bool
public setType(int `$image_type`): bool
public shadeImage(bool `$gray`, float `$azimuth`, float `$elevation`): bool
public shadowImage(
float `$opacity`,
float `$sigma`,
int `$x`,
int `$y`
): bool
public sharpenImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public shaveImage(int `$columns`, int `$rows`): bool
public shearImage(mixed `$background`, float `$x_shear`, float `$y_shear`): bool
public sigmoidalContrastImage(
bool `$sharpen`,
float `$alpha`,
float `$beta`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public sketchImage(float `$radius`, float `$sigma`, float `$angle`): bool
public smushImages(bool `$stack`, int `$offset`): Imagick
public solarizeImage(int `$threshold`): bool
public sparseColorImage(int `$SPARSE_METHOD`, array `$arguments`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public spliceImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool
public spreadImage(float `$radius`): bool
public statisticImage(
int `$type`,
int `$width`,
int `$height`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public steganoImage(Imagick `$watermark_wand`, int `$offset`): Imagick
public stereoImage(Imagick `$offset_wand`): bool
public stripImage(): bool
public subImageMatch(Imagick `$Imagick`, array `&$offset` = ?, float `&$similarity` = ?): Imagick
swirlImage(float `$degrees`): bool
textureImage(Imagick `$texture_wand`): Imagick
public thresholdImage(float `$threshold`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool
public thumbnailImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$fill` = `false`,
bool `$legacy` = `false`
): bool
public tintImage(mixed `$tint`, mixed `$opacity`, bool `$legacy` = `false`): bool
public __toString(): string
public transformImage(string `$crop`, string `$geometry`): Imagick
public transformImageColorspace(int `$colorspace`): bool
public transparentPaintImage(
mixed `$target`,
float `$alpha`,
float `$fuzz`,
bool `$invert`
): bool
public transposeImage(): bool
public transverseImage(): bool
public trimImage(float `$fuzz`): bool
public uniqueImageColors(): bool
public unsharpMaskImage(
float `$radius`,
float `$sigma`,
float `$amount`,
float `$threshold`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool
public valid(): bool
public vignetteImage(
float `$blackPoint`,
float `$whitePoint`,
int `$x`,
int `$y`
): bool
public waveImage(float `$amplitude`, float `$length`): bool
public whiteThresholdImage(mixed `$threshold`): bool
public writeImage(string `$filename` = NULL): bool
public writeImageFile(resource `$filehandle`, string `$format` = ?): bool
public writeImages(string `$filename`, bool `$adjoin`): bool
public writeImagesFile(resource `$filehandle`, string `$format` = ?): bool
}

## Image methods and global methods

The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack.

## Class Methods

Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose:

Class methods by purpose
Image effects | Get methods | Set methods | Read/write images | Other
--- | --- | --- | --- | ---
Imagick::adaptiveBlurImage() | Imagick::getCompression() | Imagick::setBackgroundColor() | Imagick::__construct() | Imagick::clear()
Imagick::adaptiveResizeImage() | Imagick::getFilename() | Imagick::setCompressionQuality() | Imagick::addImage() | Imagick::clone()
Imagick::adaptiveSharpenImage() | Imagick::getFormat() | Imagick::setCompression() | Imagick::appendImages() | Imagick::current()
Imagick::adaptiveThresholdImage() | Imagick::getImageBackgroundColor() | Imagick::setFilename() | Imagick::getFilename() | Imagick::destroy()
Imagick::addNoiseImage() | Imagick::getImageBlob() | Imagick::getImagesBlob() | Imagick::setFormat() | Imagick::getFormat()
Imagick::affinetransformimage() | Imagick::getImageBluePrimary() | Imagick::setImageBackgroundColor() | Imagick::getImageFilename() | Imagick::getHomeURL()
Imagick::annotateImage() | Imagick::getImageBorderColor() | Imagick::setFirstIterator() | Imagick::getImageFormat() | Imagick::commentImage()
Imagick::averageImages() | Imagick::getImageChannelDepth() | Imagick::setImageBias() | Imagick::getImage() | Imagick::getNumberImages()
Imagick::blackThresholdImage() | Imagick::getImageChannelDistortion() | Imagick::setImageBluePrimary() | Imagick::setImageFilename() | Imagick::getReleaseDate()
Imagick::blurImage() | Imagick::getImageChannelExtrema() | Imagick::setImageBorderColor() | Imagick::setImageFormat() | Imagick::getVersion()
Imagick::borderImage() | Imagick::getImageChannelMean() | Imagick::setImageChannelDepth() | Imagick::readImageFile() | Imagick::hasNextImage()
Imagick::charcoalImage() | Imagick::getImageChannelStatistics() | Imagick::setImageColormapColor() | Imagick::readImage() | Imagick::hasPreviousImage()
Imagick::chopImage() | Imagick::getImageColormapColor() | Imagick::setImageColorSpace() | Imagick::writeImages() | Imagick::labelImage()
Imagick::clipImage() | Imagick::getImageColorspace() | Imagick::setImageCompose() | Imagick::writeImage() | Imagick::newImage()
Imagick::clipPathImage() | Imagick::getImageColors() | Imagick::setImageCompression() |  | Imagick::newPseudoImage()
Imagick::coalesceImages() | Imagick::getImageCompose() | Imagick::setImageDelay() |  | Imagick::nextImage()
Imagick::colorFloodFillImage() | Imagick::getImageDelay() | Imagick::setImageDepth() |  | Imagick::pingImageBlob()
Imagick::colorizeImage() | Imagick::getImageDepth() | Imagick::setImageDispose() |  | Imagick::pingImageFile()
Imagick::combineImages() | Imagick::getImageDispose() | Imagick::setImageDispose() |  | Imagick::pingImage()
Imagick::compareImageChannels() | Imagick::getImageDistortion() | Imagick::setImageExtent() |  | Imagick::previousImage()
Imagick::compareImageLayers() | Imagick::getImageExtrema() | Imagick::setImageFilename() |  | Imagick::profileImage()
Imagick::compositeImage() | Imagick::getImageFilename() | Imagick::setImageFormat() |  | Imagick::queryFormats()
Imagick::contrastImage() | Imagick::getImageFormat() | Imagick::setImageGamma() |  | Imagick::removeImageProfile()
Imagick::contrastStretchImage() | Imagick::getImageGamma() | Imagick::setImageGreenPrimary() |  | Imagick::removeImage()
Imagick::convolveImage() | Imagick::getImageGeometry() | Imagick::setImageIndex() |  | Imagick::setFirstIterator()
Imagick::cropImage() | Imagick::getImageGreenPrimary() | Imagick::setImageInterpolateMethod() |  | Imagick::setImageIndex()
Imagick::cycleColormapImage() | Imagick::getImageHeight() | Imagick::setImageIterations() |  | Imagick::valid()
Imagick::deconstructImages() | Imagick::getImageHistogram() | Imagick::setImageMatteColor() |  | Imagick::getCopyright()
Imagick::drawImage() | Imagick::getImageIndex() | Imagick::setImageMatte() |  |
Imagick::edgeImage() | Imagick::getImageInterlaceScheme() | Imagick::setImagePage() |  |
Imagick::embossImage() | Imagick::getImageInterpolateMethod() | Imagick::setImageProfile() |  |
Imagick::enhanceImage() | Imagick::getImageIterations() | Imagick::setImageProperty() |  |
Imagick::equalizeImage() | Imagick::getImageMatteColor() | Imagick::setImageRedPrimary() |  |
Imagick::evaluateImage() | Imagick::getImageMatte() | Imagick::setImageRenderingIntent() |  |
Imagick::flattenImages() | Imagick::getImagePage() | Imagick::setImageResolution() |  |
Imagick::flipImage() | Imagick::getImagePixelColor() | Imagick::setImageScene() |  |
Imagick::flopImage() | Imagick::getImageProfile() | Imagick::setImageTicksPerSecond() |  |
| Imagick::getImageProperty() | Imagick::setImageType() |  |
Imagick::fxImage() | Imagick::getImageRedPrimary() | Imagick::setImageUnits() |  |
Imagick::gammaImage() | Imagick::getImageRegion() | Imagick::setImageVirtualPixelMethod() |  |
Imagick::gaussianBlurImage() | Imagick::getImageRenderingIntent() | Imagick::setImageWhitepoint() |  |
Imagick::implodeImage() | Imagick::getImageResolution() | Imagick::setInterlaceScheme() |  |
Imagick::levelImage() | Imagick::getImageScene() | Imagick::setOption() |  |
Imagick::linearStretchImage() | Imagick::getImageSignature() | Imagick::setPage() |  |
Imagick::magnifyImage() | Imagick::getImageTicksPerSecond() | Imagick::setResolution() |  |
Imagick::matteFloodFillImage() | Imagick::getImageTotalInkDensity() | Imagick::setResourceLimit() |  |
Imagick::medianFilterImage() | Imagick::getImageType() | Imagick::setSamplingFactors() |  |
Imagick::minifyImage() | Imagick::getImageUnits() | Imagick::setSizeOffset() |  |
Imagick::modulateImage() | Imagick::getImageVirtualPixelMethod() | Imagick::setSize() |  |
Imagick::montageImage() | Imagick::getImageWhitepoint() | Imagick::setType() |  |
Imagick::morphImages() | Imagick::getImageWidth() |  |  |
Imagick::mosaicImages() | Imagick::getImage() |  |  |
Imagick::motionBlurImage() | Imagick::getInterlaceScheme() |  |  |
Imagick::negateImage() | Imagick::getNumberImages() |  |  |
Imagick::normalizeImage() | Imagick::getOption() |  |  |
Imagick::oilPaintImage() | Imagick::getPackageName() |  |  |
Imagick::optimizeImageLayers() | Imagick::getPage() |  |  |
Imagick::paintOpaqueImage() | Imagick::getPixelIterator() |  |  |
Imagick::paintTransparentImage() | Imagick::getPixelRegionIterator() |  |  |
Imagick::posterizeImage() | Imagick::getQuantumDepth() |  |  |
Imagick::radialBlurImage() | Imagick::getQuantumRange() |  |  |
Imagick::raiseImage() | Imagick::getResourceLimit() |  |  |
Imagick::randomThresholdImage() | Imagick::getResource() |  |  |
Imagick::reduceNoiseImage() | Imagick::getSamplingFactors() |  |  |
Imagick::render() | Imagick::getSizeOffset() |  |  |
Imagick::resampleImage() | Imagick::getSize() |  |  |
Imagick::resizeImage() | Imagick::identifyImage() |  |  |
Imagick::rollImage() | Imagick::getImageSize() |  |  |
Imagick::rotateImage() |  |  |  |
Imagick::sampleImage() |  |  |  |
Imagick::scaleImage() |  |  |  |
Imagick::separateImageChannel() |  |  |  |
Imagick::sepiaToneImage() |  |  |  |
Imagick::shadeImage() |  |  |  |
Imagick::shadowImage() |  |  |  |
Imagick::sharpenImage() |  |  |  |
Imagick::shaveImage() |  |  |  |
Imagick::shearImage() |  |  |  |
Imagick::sigmoidalContrastImage() |  |  |  |
Imagick::sketchImage() |  |  |  |
Imagick::solarizeImage() |  |  |  |
Imagick::spliceImage() |  |  |  |
Imagick::spreadImage() |  |  |  |
Imagick::steganoImage() |  |  |  |
Imagick::stereoImage() |  |  |  |
Imagick::stripImage() |  |  |  |
Imagick::swirlImage() |  |  |  |
Imagick::textureImage() |  |  |  |
Imagick::thresholdImage() |  |  |  |
Imagick::thumbnailImage() |  |  |  |
Imagick::tintImage() |  |  |  |
Imagick::transverseImage() |  |  |  |
Imagick::trimImage() |  |  |  |
Imagick::uniqueImageColors() |  |  |  |
Imagick::unsharpMaskImage() |  |  |  |
Imagick::vignetteImage() |  |  |  |
Imagick::waveImage() |  |  |  |
Imagick::whiteThresholdImage() |  |  |  |

# Imagick::adaptiveBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

### Description

public Imagick::adaptiveBlurImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically.

`sigma`

  The standard deviation of the Gaussian, in pixels.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::adaptiveBlurImage():

Adaptively blur an image, then display to the browser.

`<?php
header('Content-type: image/jpeg');
$image = new Imagick('test.jpg');
$image->adaptiveBlurImage(5,3);
echo $image;
?>`

The above example will output something similar to:

### See Also

- Imagick::blurImage() - Adds blur filter to image
- Imagick::motionBlurImage() - Simulates motion blur
- Imagick::radialBlurImage() - Radial blurs an image

# Imagick::adaptiveResizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

### Description

public Imagick::adaptiveResizeImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool

Adaptively resize image with data-dependent triangulation. Avoids blurring across sharp color changes. Most useful when used to shrink images slightly to a slightly smaller "web size"; may not look good when a full-sized image is adaptively resized to a thumbnail. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

> Note: The behavior of the parameter `bestfit` changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If `bestfit` parameter is used both width and height must be given.

### Parameters

`columns`

  The number of columns in the scaled image.

`rows`

  The number of rows in the scaled image.

`bestfit`

  Whether to fit the image inside a bounding box.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Added optional fit parameter.
PECL imagick 2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

### Examples

Example #1 Using Imagick::adaptiveResizeImage()

Resize an image to a standard size for the web. This method works best when resizing to a size only slightly smaller than the previous image size.

`<?php
header('Content-type: image/jpeg');
$image = new Imagick('image.jpg');
$image->adaptiveResizeImage(1024,768);
echo $image;
?>`

### See Also

- Imagick::chopImage() - Removes a region of an image and trims
- Imagick::cropImage() - Extracts a region of the image
- Imagick::magnifyImage() - Scales an image proportionally 2x
- Imagick::minifyImage() - Scales an image proportionally to half its size
- Imagick::resizeImage() - Scales an image
- Imagick::scaleImage() - Scales the size of an image
- Imagick::shaveImage() - Shaves pixels from the image edges
- Imagick::thumbnailImage() - Changes the size of an image
- Imagick::trimImage() - Remove edges from the image

# Imagick::adaptiveSharpenImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

### Description

public Imagick::adaptiveSharpenImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Adaptively sharpen the image by sharpening more intensely near image edges and less intensely far from edges. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel. Use 0 for auto-select.

`sigma`

  The standard deviation of the Gaussian, in pixels.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 A Imagick::adaptiveSharpenImage() example

Adaptively sharpen the image with radius 2 and sigma 1.

`<?php
try {
$image = new Imagick('image.png');
$image->adaptiveSharpenImage(2,1);
} catch(ImagickException $e) {
echo 'Error: ' , $e->getMessage();
die();
}
header('Content-type: image/png');
echo $image;
?>`

### See Also

- Imagick::sharpenImage() - Sharpens an image

# Imagick::adaptiveThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

### Description

public Imagick::adaptiveThresholdImage(int `$width`, int `$height`, int `$offset`): bool

Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.

### Parameters

`width`

  Width of the local neighborhood.

`height`

  Height of the local neighborhood.

`offset`

  The mean offset

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::adaptiveThresholdImage()

`<?php
function adaptiveThresholdImage($imagePath, $width, $height, $adaptiveOffset) {
$imagick = new \Imagick(realpath($imagePath));
$adaptiveOffsetQuantum = intval($adaptiveOffset * \Imagick::getQuantum());
$imagick->adaptiveThresholdImage($width, $height, $adaptiveOffsetQuantum);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::addImage

(PECL imagick 2, PECL imagick 3)

Imagick::addImage — Adds new image to Imagick object image list

### Description

public Imagick::addImage(Imagick `$source`): bool

Adds new image to Imagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

### Parameters

`source`

  The source Imagick object

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::addNoiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::addNoiseImage — Adds random noise to the image

### Description

public Imagick::addNoiseImage(int `$noise_type`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Adds random noise to the image.

### Parameters

`noise_type`

  The type of the noise. Refer to this list of noise constants.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::addNoiseImage()

`<?php
function addNoiseImage($noiseType, $imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->addNoiseImage($noiseType, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::affineTransformImage

(PECL imagick 2, PECL imagick 3)

Imagick::affineTransformImage — Transforms an image

### Description

public Imagick::affineTransformImage(ImagickDraw `$matrix`): bool

Transforms an image as dictated by the affine matrix.

### Parameters

`matrix`

  The affine matrix

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::affineTransformImage()

`<?php
function affineTransformImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$draw = new \ImagickDraw();
$angle = deg2rad(40);
$affineRotate = array(
"sx" => cos($angle), "sy" => cos($angle),
"rx" => sin($angle), "ry" => -sin($angle),
"tx" => 0, "ty" => 0,
);
$draw->affine($affineRotate);
$imagick->affineTransformImage($draw);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::animateImages

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::animateImages — Animates an image or images

### Description

public Imagick::animateImages(string `$x_server`): bool

This method animates the image onto a local or remote X server. This method is not available on Windows. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`x_server`

  X server address

### Return Values

Returns `true` on success.

### See Also

- Imagick::displayImage() - Displays an image

# Imagick::annotateImage

(PECL imagick 2, PECL imagick 3)

Imagick::annotateImage — Annotates an image with text

### Description

public Imagick::annotateImage(
ImagickDraw `$draw_settings`,
float `$x`,
float `$y`,
float `$angle`,
string `$text`
): bool

Annotates an image with text.

### Parameters

`draw_settings`

  The ImagickDraw object that contains settings for drawing the text

`x`

  Horizontal offset in pixels to the left of text

`y`

  Vertical offset in pixels to the baseline of text

`angle`

  The angle at which to write the text

`text`

  The string to draw

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::annotateImage():

Annotate text on an empty image

`<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );
/* New image */
$image->newImage(800, 75, $pixel);
/* Black text */
$draw->setFillColor('black');
/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );
/* Create text */
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');
/* Give image a format */
$image->setImageFormat('png');
/* Output the image with headers */
header('Content-type: image/png');
echo $image;
?>`

### See Also

- ImagickDraw::annotation() - Draws text on the image
- ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text

# Imagick::appendImages

(PECL imagick 2, PECL imagick 3)

Imagick::appendImages — Append a set of images

### Description

public Imagick::appendImages(bool `$stack`): Imagick

Append a set of images into one larger image.

### Parameters

`stack`

  Whether to stack the images vertically. By default (or if `false` is specified) images are stacked left-to-right. If `stack` is `true`, images are stacked top-to-bottom.

### Return Values

Returns Imagick instance on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::appendImages() example

`<?php
/* Create new imagick object */
$im = new Imagick();
/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");
/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);
/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;
?>`

The above example will output something similar to:

# Imagick::autoLevelImage

(PECL imagick 3 >= 3.3.0)

Imagick::autoLevelImage — Adjusts the levels of a particular image channel

### Description

public Imagick::autoLevelImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Adjusts the levels of a particular image channel by scaling the minimum and maximum values to the full quantum range.

### Parameters

`channel`

  Which channel should the auto-levelling should be done on.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::autoLevelImage()

`<?php
function autoLevelImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->autoLevelImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::averageImages

(PECL imagick 2, PECL imagick 3)

Imagick::averageImages — Average a set of images

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::averageImages(): Imagick

Average a set of images.

### Parameters

This function has no parameters.

### Return Values

Returns a new Imagick object on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::blackThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

### Description

public Imagick::blackThresholdImage(mixed `$threshold`): bool

Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.

### Parameters

`threshold`

  The threshold below which everything turns black

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::blackThresholdImage()

`<?php
function blackThresholdImage($imagePath, $thresholdColor) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->blackthresholdimage($thresholdColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::blueShiftImage

(PECL imagick 3 >= 3.3.0)

Imagick::blueShiftImage — Mutes the colors of the image

### Description

public Imagick::blueShiftImage(float `$factor` = 1.5): bool

Mutes the colors of the image to simulate a scene at nighttime in the moonlight.

### Parameters

`factor`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::blueShiftImage()

`<?php
function blueShiftImage($imagePath, $blueShift) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->blueShiftImage($blueShift);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::blurImage

(PECL imagick 2, PECL imagick 3)

Imagick::blurImage — Adds blur filter to image

### Description

public Imagick::blurImage(float `$radius`, float `$sigma`, int `$channel` = ?): bool

Adds blur filter to image. Optional third parameter to blur a specific channel.

### Parameters

`radius`

  Blur radius

`sigma`

  Standard deviation

`channel`

  The Channeltype constant. When not supplied, all channels are blurred.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::blurImage():

Blur an image, then display to the browser.

`<?php
header('Content-type: image/jpeg');
$image = new Imagick('test.jpg');
$image->blurImage(5,3);
echo $image;
?>`

### See Also

- Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
- Imagick::motionBlurImage() - Simulates motion blur
- Imagick::radialBlurImage() - Radial blurs an image

# Imagick::borderImage

(PECL imagick 2, PECL imagick 3)

Imagick::borderImage — Surrounds the image with a border

### Description

public Imagick::borderImage(mixed `$bordercolor`, int `$width`, int `$height`): bool

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

### Parameters

`bordercolor`

  ImagickPixel object or a string containing the border color

`width`

  Border width

`height`

  Border height

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::borderImage()

`<?php
function borderImage($imagePath, $color, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->borderImage($color, $width, $height);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::brightnessContrastImage

(PECL imagick 3 >= 3.3.0)

Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image

### Description

public Imagick::brightnessContrastImage(float `$brightness`, float `$contrast`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Change the brightness and/or contrast of an image. It converts the brightness and contrast parameters into slope and intercept and calls a polynomical function to apply to the image.

### Parameters

`brightness`

`contrast`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::brightnessContrastImage()

`<?php
function brightnessContrastImage($imagePath, $brightness, $contrast, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->brightnessContrastImage($brightness, $contrast, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::charcoalImage

(PECL imagick 2, PECL imagick 3)

Imagick::charcoalImage — Simulates a charcoal drawing

### Description

public Imagick::charcoalImage(float `$radius`, float `$sigma`): bool

Simulates a charcoal drawing.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel

`sigma`

  The standard deviation of the Gaussian, in pixels

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::charcoalImage()

`<?php
function charcoalImage($imagePath, $radius, $sigma) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->charcoalImage($radius, $sigma);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::chopImage

(PECL imagick 2, PECL imagick 3)

Imagick::chopImage — Removes a region of an image and trims

### Description

public Imagick::chopImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Removes a region of an image and collapses the image to occupy the removed portion.

### Parameters

`width`

  Width of the chopped area

`height`

  Height of the chopped area

`x`

  X origo of the chopped area

`y`

  Y origo of the chopped area

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::chopImage():

Example of using Imagick::chopImage

`<?php
/* Create some objects */
$image = new Imagick();
$pixel = new ImagickPixel( 'gray' );
/* New image */
$image->newImage(400, 200, $pixel);
/* Chop image */
$image->chopImage(200, 200, 0, 0);
/* Give image a format */
$image->setImageFormat('png');
/* Output the image with headers */
header('Content-type: image/png');
echo $image;
?>`

### See Also

- Imagick::cropImage() - Extracts a region of the image

# Imagick::clampImage

(PECL imagick 3 >= 3.3.0)

Imagick::clampImage — Restricts the color range from 0 to the quantum depth.

### Description

public Imagick::clampImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Restricts the color range from 0 to the quantum depth.

### Parameters

`channel`

### Return Values

Returns `true` on success or `false` on failure.

# Imagick::clear

(PECL imagick 2, PECL imagick 3)

Imagick::clear — Clears all resources associated to Imagick object

### Description

public Imagick::clear(): bool

Clears all resources associated to Imagick object

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::clipImage

(PECL imagick 2, PECL imagick 3)

Imagick::clipImage — Clips along the first path from the 8BIM profile

### Description

public Imagick::clipImage(): bool

Clips along the first path from the 8BIM profile, if present.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::clipImagePath

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present

### Description

public Imagick::clipImagePath(string `$pathname`, string `$inside`): void

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`pathname`

`inside`

### Return Values

# Imagick::clipPathImage

(PECL imagick 2, PECL imagick 3)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

### Description

public Imagick::clipPathImage(string `$pathname`, bool `$inside`): bool

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. It may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

### Parameters

`pathname`

  The name of the path

`inside`

  If `true` later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::clone

(PECL imagick 2, PECL imagick 3)

Imagick::clone — Makes an exact copy of the Imagick object

### Description

public Imagick::clone(): Imagick

Makes an exact copy of the Imagick object.

Warning

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

### Parameters

This function has no parameters.

### Return Values

A copy of the Imagick object is returned.

### Changelog

Version | Description
--- | ---
PECL imagick 3.1.0 | The method was deprecated in favour of the clone keyword.

### Examples

Example #1 Imagick object cloning in different versions of imagick

`<?php
// Cloning an Imagick object in imagick 2.x and 3.0:
$newImage = $image->clone();
// Cloning an Imagick object from 3.1.0 on:
$newImage = clone $image;
?>`

# Imagick::clutImage

(PECL imagick 2, PECL imagick 3)

Imagick::clutImage — Replaces colors in the image

### Description

public Imagick::clutImage(Imagick `$lookup_table`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Replaces colors in the image from a color lookup table. Optional second parameter to replace colors in a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`lookup_table`

  Imagick object containing the color lookup table

`channel`

  The Channeltype constant. When not supplied, default channels are replaced.

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::clutImage():

Replace colors in the image from a color lookup table.

`<?php
$image = new Imagick('test.jpg');
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('black'));
$image->clutImage($clut);
$image->writeImage('test_out.jpg');
?>`

### See Also

- Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
- Imagick::motionBlurImage() - Simulates motion blur
- Imagick::radialBlurImage() - Radial blurs an image

# Imagick::coalesceImages

(PECL imagick 2, PECL imagick 3)

Imagick::coalesceImages — Composites a set of images

### Description

public Imagick::coalesceImages(): Imagick

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a new Imagick object on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::colorFloodfillImage

(PECL imagick 2, PECL imagick 3)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::colorFloodfillImage(
mixed `$fill`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor.

### Parameters

`fill`

  ImagickPixel object containing the fill color

`fuzz`

  The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

`bordercolor`

  ImagickPixel object containing the border color

`x`

  X start position of the floodfill

`y`

  Y start position of the floodfill

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.

# Imagick::colorizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::colorizeImage — Blends the fill color with the image

### Description

public Imagick::colorizeImage(mixed `$colorize`, mixed `$opacity`, bool `$legacy` = `false`): bool

Blends the fill color with each pixel in the image.

### Parameters

`colorize`

  ImagickPixel object or a string containing the colorize color

`opacity`

  ImagickPixel object or an float containing the opacity value. 1.0 is fully opaque and 0.0 is fully transparent.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

### Examples

Example #1 Imagick::colorizeImage()

`<?php
function colorizeImage($imagePath, $color, $opacity) {
$imagick = new \Imagick(realpath($imagePath));
$opacity = $opacity / 255.0;
$opacityColor = new \ImagickPixel("rgba(0, 0, 0, $opacity)");
$imagick->colorizeImage($color, $opacityColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::colorMatrixImage

(PECL imagick 3 >= 3.3.0)

Imagick::colorMatrixImage — Apply color transformation to an image

### Description

public Imagick::colorMatrixImage(array `$color_matrix`): bool

Apply color transformation to an image. The method permits saturation changes, hue rotation, luminance to alpha, and various other effects. Although variable-sized transformation matrices can be used, typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with offsets). The matrix is similar to those used by Adobe Flash except offsets are in column 6 rather than 5 (in support of CMYKA images) and offsets are normalized (divide Flash offset by 255)

### Parameters

`color_matrix`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::colorMatrixImage()

`<?php
function colorMatrixImage($imagePath, $colorMatrix) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageOpacity(1);
//A color matrix should look like:
// $colorMatrix = [
// 1.5, 0.0, 0.0, 0.0, 0.0, -0.157,
// 0.0, 1.0, 0.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 1.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 0.0, 1.0
// ];
$background = new \Imagick();
$background->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "pattern:checkerboard");
$background->setImageFormat('png');
$imagick->setImageFormat('png');
$imagick->colorMatrixImage($colorMatrix);
$background->compositeImage($imagick, \Imagick::COMPOSITE_ATOP, 0, 0);
header("Content-Type: image/png");
echo $background->getImageBlob();
}
?>`

# Imagick::combineImages

(PECL imagick 2, PECL imagick 3)

Imagick::combineImages — Combines one or more images into a single image

### Description

public Imagick::combineImages(int `$channelType`): Imagick

Combines one or more images into a single image. The grayscale value of the pixels of each image in the sequence is assigned in order to the specified channels of the combined image. The typical ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.

### Parameters

`channelType`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::commentImage

(PECL imagick 2, PECL imagick 3)

Imagick::commentImage — Adds a comment to your image

### Description

public Imagick::commentImage(string `$comment`): bool

Adds a comment to your image.

### Parameters

`comment`

  The comment to add

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::commentImage():

Commenting an image and retrieving the comment:

`<?php
/* Create new Imagick object */
$im = new imagick();
/* Create an empty image */
$im->newImage(100, 100, new ImagickPixel("red"));
/* Add comment to the image */
$im->commentImage("Hello World!");
/* Display the comment */
echo $im->getImageProperty("comment");
?>`

# Imagick::compareImageChannels

(PECL imagick 2, PECL imagick 3)

Imagick::compareImageChannels — Returns the difference in one or more images

### Description

public Imagick::compareImageChannels(Imagick `$image`, int `$channelType`, int `$metricType`): array

Compares one or more images and returns the difference image.

### Parameters

`image`

  Imagick object containing the image to compare.

`channelType`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

`metricType`

  One of the metric type constants.

### Return Values

Array consisting of `new_wand` and `distortion`.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::compareImageLayers

(PECL imagick 2, PECL imagick 3)

Imagick::compareImageLayers — Returns the maximum bounding region between images

### Description

public Imagick::compareImageLayers(int `$method`): Imagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`method`

  One of the layer method constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::compareImageLayers()

Comparing image layers

`<?php
/* create new imagick object */
$im = new Imagick("test.gif");
/* optimize the image layers */
$result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE);
/* work on the $result */
?>`

### See Also

- Imagick::optimizeImageLayers() - Removes repeated portions of images to optimize
- Imagick::writeImages() - Writes an image or image sequence
- Imagick::writeImage() - Writes an image to the specified filename

# Imagick::compareImages

(PECL imagick 2, PECL imagick 3)

Imagick::compareImages — Compares an image to a reconstructed image

### Description

public Imagick::compareImages(Imagick `$compare`, int `$metric`): array

Returns an array containing a reconstructed image and the difference between images.

### Parameters

`compare`

  An image to compare to.

`metric`

  Provide a valid metric type constant. Refer to this list of metric constants.

### Return Values

Returns an array containing a reconstructed image and the difference between images.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::compareImages():

Compare images and display the reconstructed image

`<?php
$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");
$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");
header("Content-Type: image/png");
echo $result[0];
?>`

# Imagick::compositeImage

(PECL imagick 2, PECL imagick 3)

Imagick::compositeImage — Composite one image onto another

### Description

public Imagick::compositeImage(
Imagick `$composite_object`,
int `$composite`,
int `$x`,
int `$y`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Composite one image onto another at the specified offset. Any extra arguments needed for the compose algorithm should passed to setImageArtifact with 'compose:args' as the first parameter and the data as the second parameter.

### Parameters

`composite_object`

  Imagick object which holds the composite image

`compose`

  Composite operator. See Composite Operator Constants

`x`

  The column offset of the composited image

`y`

  The row offset of the composited image

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::compositeImage():

Composite two images with the 'mathematics' compose method

`<?php
// Equivalent to running the command
// convert src1.png src2.png -compose mathematics -define compose:args="1,0,-0.5,0.5" -composite output.png
$src1 = new \Imagick("./src1.png");
$src2 = new \Imagick("./src2.png");
$src1->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src1->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);
$src1->writeImage("./output.png");
?>`

### See Also

- Imagick::setImageArtifact() - Set image artifact

# Imagick::__construct

(PECL imagick 2, PECL imagick 3)

Imagick::__construct — The Imagick constructor

### Description

public Imagick::__construct(mixed `$files` = ?)

Creates an Imagick instance for a specified image or set of images.

### Parameters

`files`

  The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::contrastImage

(PECL imagick 2, PECL imagick 3)

Imagick::contrastImage — Change the contrast of the image

### Description

public Imagick::contrastImage(bool `$sharpen`): bool

Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.

### Parameters

`sharpen`

  The sharpen value

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::contrastImage()

`<?php
function contrastImage($imagePath, $contrastType) {
$imagick = new \Imagick(realpath($imagePath));
if ($contrastType != 2) {
$imagick->contrastImage($contrastType);
}
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::contrastStretchImage

(PECL imagick 2, PECL imagick 3)

Imagick::contrastStretchImage — Enhances the contrast of a color image

### Description

public Imagick::contrastStretchImage(float `$black_point`, float `$white_point`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`black_point`

  The black point.

`white_point`

  The white point.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. `Imagick::CHANNEL_ALL`. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

# Imagick::convolveImage

(PECL imagick 2, PECL imagick 3)

Imagick::convolveImage — Applies a custom convolution kernel to the image

### Description

public Imagick::convolveImage(array `$kernel`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Applies a custom convolution kernel to the image.

### Parameters

`kernel`

  The convolution kernel

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::convolveImage()

`<?php
function convolveImage($imagePath, $bias, $kernelMatrix) {
$imagick = new \Imagick(realpath($imagePath));
//$edgeFindingKernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1,];
$imagick->setImageBias($bias * \Imagick::getQuantum());
$imagick->convolveImage($kernelMatrix);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::count

(PECL imagick 3 >= 3.3.0)

Imagick::count — Get the number of images

### Description

public Imagick::count(int `$mode` = 0): int

Returns the number of images.

### Parameters

`mode`

  An unused argument. Currently there is a non-particularly well defined feature in PHP where calling count() on a countable object might (or might not) require this method to accept a parameter. This parameter is here to be conformant with the interface of countable, even though the param is not used.

### Return Values

Returns the number of images.

# Imagick::cropImage

(PECL imagick 2, PECL imagick 3)

Imagick::cropImage — Extracts a region of the image

### Description

public Imagick::cropImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Extracts a region of the image.

### Parameters

`width`

  The width of the crop

`height`

  The height of the crop

`x`

  The X coordinate of the cropped region's top left corner

`y`

  The Y coordinate of the cropped region's top left corner

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::cropImage()

`<?php
function cropImage($imagePath, $startX, $startY, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->cropImage($width, $height, $startX, $startY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::cropThumbnailImage

(PECL imagick 2, PECL imagick 3)

Imagick::cropThumbnailImage — Creates a crop thumbnail

### Description

public Imagick::cropThumbnailImage(int `$width`, int `$height`, bool `$legacy` = `false`): bool

Creates a fixed size thumbnail by first scaling the image up or down and cropping a specified area from the center.

### Parameters

`width`

  The width of the thumbnail

`height`

  The Height of the thumbnail

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::current

(PECL imagick 2, PECL imagick 3)

Imagick::current — Returns a reference to the current Imagick object

### Description

public Imagick::current(): Imagick

Returns reference to the current imagick object with image pointer at the correct sequence.

### Parameters

This function has no parameters.

### Return Values

Returns self on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::cycleColormapImage

(PECL imagick 2, PECL imagick 3)

Imagick::cycleColormapImage — Displaces an image's colormap

### Description

public Imagick::cycleColormapImage(int `$displace`): bool

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

### Parameters

`displace`

  The amount to displace the colormap.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::decipherImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::decipherImage — Deciphers an image

### Description

public Imagick::decipherImage(string `$passphrase`): bool

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

### Parameters

`passphrase`

  The passphrase

### Return Values

Returns `true` on success.

### See Also

- Imagick::encipherImage() - Enciphers an image

# Imagick::deconstructImages

(PECL imagick 2, PECL imagick 3)

Imagick::deconstructImages — Returns certain pixel differences between images

### Description

public Imagick::deconstructImages(): Imagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

### Parameters

This function has no parameters.

### Return Values

Returns a new Imagick object on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::deleteImageArtifact

(PECL imagick 3)

Imagick::deleteImageArtifact — Delete image artifact

### Description

public Imagick::deleteImageArtifact(string `$artifact`): bool

Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

### Parameters

`artifact`

  The name of the artifact to delete

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### See Also

- Imagick::setImageArtifact() - Set image artifact
- Imagick::getImageArtifact() - Get image artifact

# Imagick::deleteImageProperty

(PECL imagick 3 >= 3.3.0)

Imagick::deleteImageProperty — Deletes an image property

### Description

public Imagick::deleteImageProperty(string `$name`): bool

Deletes an image property.

### Parameters

`name`

  The name of the property to delete.

### Return Values

Returns `true` on success.

# Imagick::deskewImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.3.0)

Imagick::deskewImage — Removes skew from the image

### Description

public Imagick::deskewImage(float `$threshold`): bool

This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

### Parameters

`threshold`

  Deskew threshold

### Return Values

### Examples

Example #1 Imagick::deskewImage()

`<?php
function deskewImage($threshold) {
$imagick = new \Imagick(realpath("images/NYTimes-Page1-11-11-1918.jpg"));
$deskewImagick = clone $imagick;
//This is the only thing required for deskewing.
$deskewImagick->deskewImage($threshold);
//The rest of this example is to make the result obvious - because
//otherwise the result is not obvious.
$trim = 9;
$deskewImagick->cropImage($deskewImagick->getImageWidth() - $trim, $deskewImagick->getImageHeight(), $trim, 0);
$imagick->cropImage($imagick->getImageWidth() - $trim, $imagick->getImageHeight(), $trim, 0);
$deskewImagick->resizeimage($deskewImagick->getImageWidth() / 2, $deskewImagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
$imagick->resizeimage($imagick->getImageWidth() / 2, $imagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
$newCanvas = new \Imagick();
$newCanvas->newimage($imagick->getImageWidth() + $deskewImagick->getImageWidth() + 20, $imagick->getImageHeight(), 'red', 'jpg');
$newCanvas->compositeimage($imagick, \Imagick::COMPOSITE_COPY, 5, 0);
$newCanvas->compositeimage($deskewImagick, \Imagick::COMPOSITE_COPY, $imagick->getImageWidth() + 10, 0);
header("Content-Type: image/jpg");
echo $newCanvas->getImageBlob();
}
?>`

# Imagick::despeckleImage

(PECL imagick 2, PECL imagick 3)

Imagick::despeckleImage — Reduces the speckle noise in an image

### Description

public Imagick::despeckleImage(): bool

Reduces the speckle noise in an image while preserving the edges of the original image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::despeckleImage()

`<?php
function despeckleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->despeckleImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::destroy

(PECL imagick 2, PECL imagick 3)

Imagick::destroy — Destroys the Imagick object

### Description

public Imagick::destroy(): bool

Destroys the Imagick object and frees all resources associated with it. This method is deprecated in favour of Imagick::clear.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::displayImage

(PECL imagick 2, PECL imagick 3)

Imagick::displayImage — Displays an image

### Description

public Imagick::displayImage(string `$servername`): bool

This method displays an image on a X server.

### Parameters

`servername`

  The X server name

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::displayImages

(PECL imagick 2, PECL imagick 3)

Imagick::displayImages — Displays an image or image sequence

### Description

public Imagick::displayImages(string `$servername`): bool

Displays an image or image sequence on a X server.

### Parameters

`servername`

  The X server name

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::distortImage

(PECL imagick 2 >= 2.0.1, PECL imagick 3)

Imagick::distortImage — Distorts an image using various distortion methods

### Description

public Imagick::distortImage(int `$method`, array `$arguments`, bool `$bestfit`): bool

Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to `true`.

If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping.

This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`method`

  The method of image distortion. See distortion constants

`arguments`

  The arguments for this distortion method

`bestfit`

  Attempt to resize destination to fit distorted source

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::distortImage():

Distort an image and display to the browser.

`<?php
/* Create new object */
$im = new Imagick();
/* Create new checkerboard pattern */
$im->newPseudoImage(100, 100, "pattern:checkerboard");
/* Set the image format to png */
$im->setImageFormat('png');
/* Fill new visible areas with transparent */
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
/* Activate matte */
$im->setImageMatte(true);
/* Control points for the distortion */
$controlPoints = array( 10, 10,
10, 5,
10, $im->getImageHeight() - 20,
10, $im->getImageHeight() - 5,
$im->getImageWidth() - 10, 10,
$im->getImageWidth() - 10, 20,
$im->getImageWidth() - 10, $im->getImageHeight() - 10,
$im->getImageWidth() - 10, $im->getImageHeight() - 30);
/* Perform the distortion */
$im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);
/* Ouput the image */
header("Content-Type: image/png");
echo $im;
?>`

The above example will output something similar to:

### See Also

- Imagick::blurImage() - Adds blur filter to image
- Imagick::motionBlurImage() - Simulates motion blur
- Imagick::radialBlurImage() - Radial blurs an image

# Imagick::drawImage

(PECL imagick 2, PECL imagick 3)

Imagick::drawImage — Renders the ImagickDraw object on the current image

### Description

public Imagick::drawImage(ImagickDraw `$draw`): bool

Renders the ImagickDraw object on the current image.

### Parameters

`draw`

  The drawing operations to render on the image.

### Return Values

Returns `true` on success.

# Imagick::edgeImage

(PECL imagick 2, PECL imagick 3)

Imagick::edgeImage — Enhance edges within the image

### Description

public Imagick::edgeImage(float `$radius`): bool

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

### Parameters

`radius`

  The radius of the operation.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::edgeImage()

`<?php
function edgeImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->edgeImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::embossImage

(PECL imagick 2, PECL imagick 3)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

### Description

public Imagick::embossImage(float `$radius`, float `$sigma`): bool

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

### Parameters

`radius`

  The radius of the effect

`sigma`

  The sigma of the effect

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::embossImage()

`<?php
function embossImage($imagePath, $radius, $sigma) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->embossImage($radius, $sigma);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::encipherImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::encipherImage — Enciphers an image

### Description

public Imagick::encipherImage(string `$passphrase`): bool

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

### Parameters

`passphrase`

  The passphrase

### Return Values

Returns `true` on success.

### See Also

- Imagick::decipherImage() - Deciphers an image

# Imagick::enhanceImage

(PECL imagick 2, PECL imagick 3)

Imagick::enhanceImage — Improves the quality of a noisy image

### Description

public Imagick::enhanceImage(): bool

Applies a digital filter that improves the quality of a noisy image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::enhanceImage()

`<?php
function enhanceImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->enhanceImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::equalizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::equalizeImage — Equalizes the image histogram

### Description

public Imagick::equalizeImage(): bool

Equalizes the image histogram.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::equalizeImage()

`<?php
function equalizeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->equalizeImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::evaluateImage

(PECL imagick 2, PECL imagick 3)

Imagick::evaluateImage — Applies an expression to an image

### Description

public Imagick::evaluateImage(int `$op`, float `$constant`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image.

### Parameters

`op`

  The evaluation operator

`constant`

  The value of the operator

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::evaluateImage()

Using evaluateImage to reduce opacity in an image.

`<?php
// Create new object with the image
$im = new Imagick('example-alpha.png');
// Reduce the alpha by 50%
$im->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);
// Output the image
header("Content-Type: image/png");
echo $im;
?>`

# Imagick::exportImagePixels

(PECL imagick 2 >=2.3.0, PECL imagick 3)

Imagick::exportImagePixels — Exports raw image pixels

### Description

public Imagick::exportImagePixels(
int `$x`,
int `$y`,
int `$width`,
int `$height`,
string `$map`,
int `$STORAGE`
): array

Exports image pixels into an array. The map defines the ordering of the exported pixels. The size of the returned array is `width * height * strlen(map)`. This method is available if Imagick has been compiled against ImageMagick version 6.4.7 or newer.

### Parameters

`x`

  X-coordinate of the exported area

`y`

  Y-coordinate of the exported area

`width`

  Width of the exported aread

`height`

  Height of the exported area

`map`

  Ordering of the exported pixels. For example `"RGB"`. Valid characters for the map are R, G, B, A, O, C, Y, M, K, I and P.

`STORAGE`

  Refer to this list of pixel type constants

### Return Values

Returns an array containing the pixels values.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::exportImagePixels()

Export image pixels into an array

`<?php
/* Create new object */
$im = new Imagick();
/* Create new image */
$im->newPseudoImage(0, 0, "magick:rose");
/* Export the image pixels */
$pixels = $im->exportImagePixels(10, 10, 2, 2, "RGB", Imagick::PIXEL_CHAR);
/* Output */
var_dump($pixels);
?>`

The above example will output:

    array(12) {
      [0]=>
      int(72)
      [1]=>
      int(64)
      [2]=>
      int(57)
      [3]=>
      int(69)
      [4]=>
      int(59)
      [5]=>
      int(43)
      [6]=>
      int(124)
      [7]=>
      int(120)
      [8]=>
      int(-96)
      [9]=>
      int(91)
      [10]=>
      int(84)
      [11]=>
      int(111)
    }

# Imagick::extentImage

(PECL imagick 2, PECL imagick 3)

Imagick::extentImage — Set image size

### Description

public Imagick::extentImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Caution

Prior to ImageMagick 6.5.7-8 (1623), $x was positive when shifting to the left and negative when shifting to the right, and $y was positive when shifting an image up and negative when shifting an image down. Somewhere betwen ImageMagick 6.3.7 (1591) and ImageMagick 6.5.7-8 (1623), the axes of $x and $y were flipped, so that $x was negative when shifting to the left and positive when shifting to the right, and $y was negative when shifting an image up and positive when shifting an image down. Somewhere between ImageMagick 6.5.7-8 (1623) and ImageMagick 6.6.9-7 (1641), the axes of $x and $y were flipped back to pre-ImageMagick 6.5.7-8 (1623) functionality.

### Parameters

`width`

  The new width

`height`

  The new height

`x`

  X position for the new size

`y`

  Y position for the new size

### Return Values

Returns `true` on success.

### See Also

- Imagick::resizeImage() - Scales an image
- Imagick::thumbnailImage() - Changes the size of an image
- Imagick::cropImage() - Extracts a region of the image

# Imagick::filter

(PECL imagick 3 >= 3.3.0)

Imagick::filter — Applies a custom convolution kernel to the image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::filter(ImagickKernel `$ImagickKernel`, int `$channel` = Imagick::CHANNEL_UNDEFINED): bool

Applies a custom convolution kernel to the image.

### Parameters

`ImagickKernel`

  An instance of ImagickKernel that represents either a single kernel or a linked series of kernels.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::filter()

`<?php
function filter($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$matrix = [
[-1, 0, -1],
[0, 5, 0],
[-1, 0, -1],
];
$kernel = \ImagickKernel::fromMatrix($matrix);
$strength = 0.5;
$kernel->scale($strength, \Imagick::NORMALIZE_KERNEL_VALUE);
$kernel->addUnityKernel(1 - $strength);
$imagick->filter($kernel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::flattenImages

(PECL imagick 2, PECL imagick 3)

Imagick::flattenImages — Merges a sequence of images

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::flattenImages(): Imagick

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::flipImage

(PECL imagick 2, PECL imagick 3)

Imagick::flipImage — Creates a vertical mirror image

### Description

public Imagick::flipImage(): bool

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::flipImage()

`<?php
function flipImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->flipImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::flopimage() - Creates a horizontal mirror image

# Imagick::floodFillPaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

### Description

public Imagick::floodFillPaintImage(
mixed `$fill`,
float `$fuzz`,
mixed `$target`,
int `$x`,
int `$y`,
bool `$invert`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor. This method is a replacement for deprecated Imagick::paintFloodFillImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

### Parameters

`fill`

  ImagickPixel object or a string containing the fill color

`fuzz`

  The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

`target`

  ImagickPixel object or a string containing the target color to paint

`x`

  X start position of the floodfill

`y`

  Y start position of the floodfill

`invert`

  If `true` paints any pixel that does not match the target color.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::floodfillPaintImage() example

`<?php
/* Create new imagick object */
$im = new Imagick();
/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");
/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);
/* Save the intermediate image for comparison */
$combined->writeImage("floodfillpaint_intermediate.png");
/* The target pixel to paint */
$x = 1;
$y = 1;
/* Get the color we are painting */
$target = $combined->getImagePixelColor($x, $y);
/* Paints pixel in position 1,1 black and all neighboring
pixels that match the target color */
$combined->floodfillPaintImage("black", 1, $target, $x, $y, false);
/* Save the result */
$combined->writeImage("floodfillpaint_result.png");
?>`

The above example will output something similar to:

# Imagick::flopImage

(PECL imagick 2, PECL imagick 3)

Imagick::flopImage — Creates a horizontal mirror image

### Description

public Imagick::flopImage(): bool

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::flopImage()

`<?php
function flopImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->flopImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::flipimage() - Creates a vertical mirror image

# Imagick::forwardFourierTransformImage

(PECL imagick 3 >= 3.3.0)

Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)

### Description

public Imagick::forwardFourierTransformimage(bool `$magnitude`): bool

Implements the discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

### Parameters

`magnitude`

  If true, return as magnitude / phase pair otherwise a real / imaginary image pair.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::forwardFourierTransformImage()

`<?php
//Utility function for forwardTransformImage
function createMask() {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(0);
$draw->setStrokeColor('rgb(255, 255, 255)');
$draw->setFillColor('rgb(255, 255, 255)');
//Draw a circle on the y-axis, with it's centre
//at x, y that touches the origin
$draw->circle(250, 250, 220, 250);
$imagick = new \Imagick();
$imagick->newImage(512, 512, "black");
$imagick->drawImage($draw);
$imagick->gaussianBlurImage(20, 20);
$imagick->autoLevelImage();
return $imagick;
}
function forwardFourierTransformImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->resizeimage(512, 512, \Imagick::FILTER_LANCZOS, 1);
$mask = createMask();
$imagick->forwardFourierTransformImage(true);
@$imagick->setimageindex(0);
$magnitude = $imagick->getimage();
@$imagick->setimageindex(1);
$imagickPhase = $imagick->getimage();
if (true) {
$imagickPhase->compositeImage($mask, \Imagick::COMPOSITE_MULTIPLY, 0, 0);
}
if (false) {
$output = clone $imagickPhase;
$output->setimageformat('png');
header("Content-Type: image/png");
echo $output->getImageBlob();
}
$magnitude->inverseFourierTransformImage($imagickPhase, true);
$magnitude->setimageformat('png');
header("Content-Type: image/png");
echo $magnitude->getImageBlob();
}
?>`

# Imagick::frameImage

(PECL imagick 2, PECL imagick 3)

Imagick::frameImage — Adds a simulated three-dimensional border

### Description

public Imagick::frameImage(
mixed `$matte_color`,
int `$width`,
int `$height`,
int `$inner_bevel`,
int `$outer_bevel`
): bool

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

### Parameters

`matte_color`

  ImagickPixel object or a string representing the matte color

`width`

  The width of the border

`height`

  The height of the border

`inner_bevel`

  The inner bevel width

`outer_bevel`

  The outer bevel width

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::frameImage()

`<?php
function frameImage($imagePath, $color, $width, $height, $innerBevel, $outerBevel) {
$imagick = new \Imagick(realpath($imagePath));
$width = $width + $innerBevel + $outerBevel;
$height = $height + $innerBevel + $outerBevel;
$imagick->frameimage(
$color,
$width,
$height,
$innerBevel,
$outerBevel
);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::functionImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::functionImage — Applies a function on the image

### Description

public Imagick::functionImage(int `$function`, array `$arguments`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Applies an arithmetic, relational, or logical expression to a pseudo image.

See also » ImageMagick v6 Examples - Image Transformations — Function, Multi-Argument Evaluate

This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

### Parameters

`function`

  Refer to this list of function constants

`arguments`

  Array of arguments to pass to this function.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Create a sinusoidal gradient

`<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(3, -90);
$imagick->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
header("Content-Type: image/png");
$imagick->setImageFormat("png");
echo $imagick->getImageBlob();
?>`

The above example will output something similar to:

Example #2 Create a gradient from the polynomial (4x^2 - 4x + 1)

`<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(4, -4, 1);
$imagick->functionImage(Imagick::FUNCTION_POLYNOMIAL, $arguments);
header("Content-Type: image/png");
$imagick->setimageformat("png");
echo $imagick->getImageBlob();
?>`

The above example will output something similar to:

Example #3 Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient

`<?php
$imagick1 = new Imagick();
$imagick1->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(9, -90);
$imagick1->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
$imagick2 = new Imagick();
$imagick2->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(0.5, 0);
$imagick2->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
$imagick1->compositeimage($imagick2, Imagick::COMPOSITE_MULTIPLY, 0, 0);
header("Content-Type: image/png");
$imagick1->setImageFormat("png");
echo $imagick1->getImageBlob();
?>`

The above example will output something similar to:

# Imagick::fxImage

(PECL imagick 2, PECL imagick 3)

Imagick::fxImage — Evaluate expression for each pixel in the image

### Description

public Imagick::fxImage(string `$expression`, int `$channel` = Imagick::CHANNEL_DEFAULT): Imagick

Evaluate expression for each pixel in the image. Consult » The Fx Special Effects Image Operator for more information.

### Parameters

`expression`

  The expression.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::fxImage()

`<?php
function fxImage() {
$imagick = new \Imagick();
$imagick->newPseudoImage(200, 200, "xc:white");
$fx = 'xx=i-w/2; yy=j-h/2; rr=hypot(xx,yy); (.5-rr/140)*1.2+.5';
$fxImage = $imagick->fxImage($fx);
header("Content-Type: image/png");
$fxImage->setimageformat('png');
echo $fxImage->getImageBlob();
}
?>`

# Imagick::gammaImage

(PECL imagick 2, PECL imagick 3)

Imagick::gammaImage — Gamma-corrects an image

### Description

public Imagick::gammaImage(float `$gamma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

### Parameters

`gamma`

  The amount of gamma-correction.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::gammaImage()

`<?php
function gammaImage($imagePath, $gamma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->gammaImage($gamma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::gaussianBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::gaussianBlurImage — Blurs an image

### Description

public Imagick::gaussianBlurImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel.

`sigma`

  The standard deviation of the Gaussian, in pixels.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::gaussianBlurImage()

`<?php
function gaussianBlurImage($imagePath, $radius, $sigma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->gaussianBlurImage($radius, $sigma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::getColorspace

(PECL imagick 3)

Imagick::getColorspace — Gets the colorspace

### Description

public Imagick::getColorspace(): int

Gets the global colorspace value. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns an integer which can be compared against COLORSPACE constants.

# Imagick::getCompression

(PECL imagick 2, PECL imagick 3)

Imagick::getCompression — Gets the object compression type

### Description

public Imagick::getCompression(): int

Gets the object compression type.

### Parameters

This function has no parameters.

### Return Values

Returns the compression constant

# Imagick::getCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::getCompressionQuality — Gets the object compression quality

### Description

public Imagick::getCompressionQuality(): int

Gets the object compression quality.

### Parameters

This function has no parameters.

### Return Values

Returns integer describing the compression quality

# Imagick::getCopyright

(PECL imagick 2, PECL imagick 3)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

### Description

public static Imagick::getCopyright(): string

Returns the ImageMagick API copyright as a string.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.

# Imagick::getFilename

(PECL imagick 2, PECL imagick 3)

Imagick::getFilename — The filename associated with an image sequence

### Description

public Imagick::getFilename(): string

Returns the filename associated with an image sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a string on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getFont

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::getFont — Gets font

### Description

public Imagick::getFont(): string

Returns the objects font property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns the string containing the font name or `false` if not font is set.

### See Also

- Imagick::setFont() - Sets font
- ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
- ImagickDraw::getFont() - Returns the font

# Imagick::getFormat

(PECL imagick 2, PECL imagick 3)

Imagick::getFormat — Returns the format of the Imagick object

### Description

public Imagick::getFormat(): string

Returns the format of the Imagick object.

### Parameters

This function has no parameters.

### Return Values

Returns the format of the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getGravity

(PECL imagick 2, PECL imagick 3)

Imagick::getGravity — Gets the gravity

### Description

public Imagick::getGravity(): int

Gets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns the gravity property. Refer to the list of gravity constants.

# Imagick::getHomeURL

(PECL imagick 2, PECL imagick 3)

Imagick::getHomeURL — Returns the ImageMagick home URL

### Description

public static Imagick::getHomeURL(): string

Returns the ImageMagick home URL.

### Parameters

This function has no parameters.

### Return Values

Returns a link to the imagemagick homepage.

# Imagick::getImage

(PECL imagick 2, PECL imagick 3)

Imagick::getImage — Returns a new Imagick object

### Description

public Imagick::getImage(): Imagick

Returns a new Imagick object with the current image sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a new Imagick object with the current image sequence.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageAlphaChannel

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageAlphaChannel — Checks if the image has an alpha channel

### Description

public Imagick::getImageAlphaChannel(): bool

Returns whether the image has an alpha channel.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the image has an alpha channel value and `false` if not, i.e. the image is RGB rather than RGBA or CMYK rather than CMYKA.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 3.6.0 | Returns a bool now; previously, an int was returned.

# Imagick::getImageArtifact

(PECL imagick 3)

Imagick::getImageArtifact — Get image artifact

### Description

public Imagick::getImageArtifact(string `$artifact`): string

Gets an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

### Parameters

`artifact`

  The name of the artifact

### Return Values

Returns the artifact value on success.

### Errors/Exceptions

Throws ImagickException on error.

### See Also

- Imagick::setImageArtifact() - Set image artifact
- Imagick::deleteImageArtifact() - Delete image artifact

# Imagick::getImageAttribute

(PECL imagick 2, PECL imagick 3)

Imagick::getImageAttribute — Returns a named attribute

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageAttribute(string `$key`): string

Returns a named attribute.

### Parameters

`key`

  The key of the attribute to get.

### Return Values

# Imagick::getImageBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBackgroundColor — Returns the image background color

### Description

public Imagick::getImageBackgroundColor(): ImagickPixel

Returns the image background color.

### Parameters

This function has no parameters.

### Return Values

Returns an ImagickPixel set to the background color of the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBlob — Returns the image sequence as a blob

### Description

public Imagick::getImageBlob(): string

Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageBluePrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

### Description

public Imagick::getImageBluePrimary(): array

Returns the chromaticity blue primary point for the image.

### Parameters

`x`

  The chromaticity blue primary x-point.

`y`

  The chromaticity blue primary y-point.

### Return Values

Array consisting of "x" and "y" coordinates of point.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageBorderColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBorderColor — Returns the image border color

### Description

public Imagick::getImageBorderColor(): ImagickPixel

Returns the image border color.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

### Description

public Imagick::getImageChannelDepth(int `$channel`): int

Gets the depth for a particular image channel.

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

# Imagick::getImageChannelDistortion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

### Description

public Imagick::getImageChannelDistortion(Imagick `$reference`, int `$channel`, int `$metric`): float

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.

### Parameters

`reference`

  Imagick object to compare to.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

`metric`

  One of the metric type constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelDistortions

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageChannelDistortions — Gets channel distortions

### Description

public Imagick::getImageChannelDistortions(Imagick `$reference`, int `$metric`, int `$channel` = Imagick::CHANNEL_DEFAULT): float

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metrics This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

### Parameters

`reference`

  Imagick object containing the reference image

`metric`

  Refer to this list of metric type constants.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns a float describing the channel distortion.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelExtrema

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageChannelExtrema(int `$channel`): array

Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelKurtosis

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

### Description

public Imagick::getImageChannelKurtosis(int `$channel` = Imagick::CHANNEL_DEFAULT): array

Get the kurtosis and skewness of a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns an array with `kurtosis` and `skewness` members.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelMean

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelMean — Gets the mean and standard deviation

### Description

public Imagick::getImageChannelMean(int `$channel`): array

Gets the mean and standard deviation of one or more image channels.

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns an array with `"mean"` and `"standardDeviation"` members.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelRange

(PECL imagick 2 >= 2.2.1, PECL imagick 3)

Imagick::getImageChannelRange — Gets channel range

### Description

public Imagick::getImageChannelRange(int `$channel`): array

Gets the range for one or more image channels. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns an array containing minima and maxima values of the channel(s).

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageChannelStatistics

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

### Description

public Imagick::getImageChannelStatistics(): array

Returns statistics for each channel in the image. The statistics include the channel depth, its minima and maxima, the mean, and the standard deviation.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::getImageClipMask

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageClipMask — Gets image clip mask

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageClipMask(): Imagick

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns an Imagick object containing the clip mask.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageColormapColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

### Description

public Imagick::getImageColormapColor(int `$index`): ImagickPixel

Returns the color of the specified colormap index.

### Parameters

`index`

  The offset into the image colormap.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageColors

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColors — Gets the number of unique colors in the image

### Description

public Imagick::getImageColors(): int

Gets the number of unique colors in the image.

### Parameters

This function has no parameters.

### Return Values

Returns an int, the number of unique colors in the image.

# Imagick::getImageColorspace

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColorspace — Gets the image colorspace

### Description

public Imagick::getImageColorspace(): int

Gets the image colorspace.

### Parameters

This function has no parameters.

### Return Values

Returns an integer which can be compared against COLORSPACE constants.

# Imagick::getImageCompose

(PECL imagick 2, PECL imagick 3)

Imagick::getImageCompose — Returns the composite operator associated with the image

### Description

public Imagick::getImageCompose(): int

Returns the composite operator associated with the image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::getImageCompression

(PECL imagick 3 >= 3.3.0)

Imagick::getImageCompression — Gets the current image's compression type

### Description

public Imagick::getImageCompression(): int

Gets the current image's compression type.

### Parameters

This function has no parameters.

### Return Values

Returns the compression constant

# Imagick::getImageCompressionQuality

(PECL imagick 2 >= 2.2.2, PECL imagick 3)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

### Description

public Imagick::getImageCompressionQuality(): int

Gets the current image's compression quality

### Parameters

This function has no parameters.

### Return Values

Returns integer describing the images compression quality

# Imagick::getImageDelay

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDelay — Gets the image delay

### Description

public Imagick::getImageDelay(): int

Gets the image delay.

### Parameters

This function has no parameters.

### Return Values

Returns the image delay.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDepth — Gets the image depth

### Description

public Imagick::getImageDepth(): int

Gets the image depth.

### Parameters

This function has no parameters.

### Return Values

The image depth.

# Imagick::getImageDispose

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDispose — Gets the image disposal method

### Description

public Imagick::getImageDispose(): int

Gets the image disposal method.

### Parameters

This function has no parameters.

### Return Values

Returns the dispose method on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageDistortion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDistortion — Compares an image to a reconstructed image

### Description

public Imagick::getImageDistortion(MagickWand `$reference`, int `$metric`): float

Compares an image to a reconstructed image and returns the specified distortion metric.

### Parameters

`reference`

  Imagick object to compare to.

`metric`

  One of the metric type constants.

### Return Values

Returns the distortion metric used on the image (or the best guess thereof).

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageExtrema

(PECL imagick 2, PECL imagick 3)

Imagick::getImageExtrema — Gets the extrema for the image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageExtrema(): array

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the keys "min" and "max".

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageFilename

(PECL imagick 2, PECL imagick 3)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

### Description

public Imagick::getImageFilename(): string

Returns the filename of a particular image in a sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a string with the filename of the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageFormat

(PECL imagick 2, PECL imagick 3)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

### Description

public Imagick::getImageFormat(): string

Returns the format of a particular image in a sequence.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the image format on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageGamma

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGamma — Gets the image gamma

### Description

public Imagick::getImageGamma(): float

Gets the image gamma.

### Parameters

This function has no parameters.

### Return Values

Returns the image gamma on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageGeometry

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGeometry — Gets the width and height as an associative array

### Description

public Imagick::getImageGeometry(): array

Returns the width and height as an associative array.

### Parameters

This function has no parameters.

### Return Values

Returns an array with the width/height of the image.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::getImageGeometry()

`<?php
$imagick = new Imagick();
$imagick->newImage(100, 200, "black");
print_r($imagick->getImageGeometry());
?>`

The above example will output:

    Array
    (
        [width] => 100
        [height] => 200
    )

# Imagick::getImageGravity

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageGravity — Gets the image gravity

### Description

public Imagick::getImageGravity(): int

Gets the current gravity value of the image. Unlike Imagick::getGravity(), this method returns the gravity defined for the current image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns the images gravity property. Refer to the list of gravity constants.

# Imagick::getImageGreenPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

### Description

public Imagick::getImageGreenPrimary(): array

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageHeight

(PECL imagick 2, PECL imagick 3)

Imagick::getImageHeight — Returns the image height

### Description

public Imagick::getImageHeight(): int

Returns the image height.

### Parameters

This function has no parameters.

### Return Values

Returns the image height in pixels.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageHistogram

(PECL imagick 2, PECL imagick 3)

Imagick::getImageHistogram — Gets the image histogram

### Description

public Imagick::getImageHistogram(): array

Returns the image histogram as an array of ImagickPixel objects.

### Parameters

This function has no parameters.

### Return Values

Returns the image histogram as an array of ImagickPixel objects.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Generates Imagick::getImageHistogram()

`<?php
function getColorStatistics($histogramElements, $colorChannel) {
$colorStatistics = [];
foreach ($histogramElements as $histogramElement) {
$color = $histogramElement->getColorValue($colorChannel);
$color = intval($color * 255);
$count = $histogramElement->getColorCount();
if (array_key_exists($color, $colorStatistics)) {
$colorStatistics[$color] += $count;
}
else {
$colorStatistics[$color] = $count;
}
}
ksort($colorStatistics);
return $colorStatistics;
}
function getImageHistogram($imagePath) {
$backgroundColor = 'black';
$draw = new \ImagickDraw();
$draw->setStrokeWidth(0); //make the lines be as thin as possible
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
$histogramWidth = 256;
$histogramHeight = 100; // the height for each RGB segment
$imagick = new \Imagick(realpath($imagePath));
//Resize the image to be small, otherwise PHP tends to run out of memory
//This might lead to bad results for images that are pathologically 'pixelly'
$imagick->adaptiveResizeImage(200, 200, true);
$histogramElements = $imagick->getImageHistogram();
$histogram = new \Imagick();
$histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black');
$histogram->setImageFormat('png');
$getMax = function ($carry, $item) {
if ($item > $carry) {
return $item;
}
return $carry;
};
$colorValues = [
'red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED),
'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN),
'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE),
];
$max = array_reduce($colorValues['red'] , $getMax, 0);
$max = array_reduce($colorValues['lime'] , $getMax, $max);
$max = array_reduce($colorValues['blue'] , $getMax, $max);
$scale = $histogramHeight / $max;
$count = 0;
foreach ($colorValues as $color => $values) {
$draw->setstrokecolor($color);
$offset = ($count + 1) * $histogramHeight;
foreach ($values as $index => $value) {
$draw->line($index, $offset, $index, $offset - ($value * $scale));
}
$count++;
}
$histogram->drawImage($draw);
header( "Content-Type: image/png" );
echo $histogram;
}
?>`

# Imagick::getImageIndex

(PECL imagick 2, PECL imagick 3)

Imagick::getImageIndex — Gets the index of the current active image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageIndex(): int

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

### Parameters

This function has no parameters.

### Return Values

Returns an integer containing the index of the image in the stack.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

### Description

public Imagick::getImageInterlaceScheme(): int

Gets the image interlace scheme.

### Parameters

This function has no parameters.

### Return Values

Returns the interlace scheme as an integer on success. Throw an ImagickException on error.

# Imagick::getImageInterpolateMethod

(PECL imagick 2, PECL imagick 3)

Imagick::getImageInterpolateMethod — Returns the interpolation method

### Description

public Imagick::getImageInterpolateMethod(): int

Returns the interpolation method for the specified image. The method is one of the `Imagick::INTERPOLATE_*` constants.

### Parameters

This function has no parameters.

### Return Values

Returns the interpolate method on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageIterations

(PECL imagick 2, PECL imagick 3)

Imagick::getImageIterations — Gets the image iterations

### Description

public Imagick::getImageIterations(): int

Gets the image iterations.

### Parameters

This function has no parameters.

### Return Values

Returns the image iterations as an integer.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageLength

(PECL imagick 2, PECL imagick 3)

Imagick::getImageLength — Returns the image length in bytes

### Description

public Imagick::getImageLength(): int

Returns the image length in bytes

### Parameters

This function has no parameters.

### Return Values

Returns an int containing the current image size.

### Examples

Example #1 Using Imagick::getImageLength():

Getting image length in bytes

`<?php
$image = new Imagick('test.jpg');
echo $image->getImageLength() . ' bytes';
?>`

# Imagick::getImageMatte

(PECL imagick 2, PECL imagick 3)

Imagick::getImageMatte — Return if the image has a matte channel

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageMatte(): bool

Returns `true` if the image has a matte channel otherwise false. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::getImageMatteColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageMatteColor — Returns the image matte color

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageMatteColor(): ImagickPixel

Returns the image matte color.

### Parameters

This function has no parameters.

### Return Values

Returns ImagickPixel object on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageMimeType

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageMimeType — Returns the image mime-type

### Description

public Imagick::getImageMimeType(): string

Returns the image mime-type.

### Parameters

This function has no parameters.

### Return Values

# Imagick::getImageOrientation

(PECL imagick 2, PECL imagick 3)

Imagick::getImageOrientation — Gets the image orientation

### Description

public Imagick::getImageOrientation(): int

Gets the image orientation. The return value is one of the orientation constants.

### Parameters

This function has no parameters.

### Return Values

Returns an int on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImagePage

(PECL imagick 2, PECL imagick 3)

Imagick::getImagePage — Returns the page geometry

### Description

public Imagick::getImagePage(): array

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImagePixelColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImagePixelColor — Returns the color of the specified pixel

### Description

public Imagick::getImagePixelColor(int `$x`, int `$y`): ImagickPixel

Returns the color of the specified pixel.

### Parameters

`x`

  The x-coordinate of the pixel

`y`

  The y-coordinate of the pixel

### Return Values

Returns an ImagickPixel instance for the color at the coordinates given.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProfile — Returns the named image profile

### Description

public Imagick::getImageProfile(string `$name`): string

Returns the named image profile.

### Parameters

`name`

  The name of the profile to return.

### Return Values

Returns a string containing the image profile.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageProfiles

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProfiles — Returns the image profiles

### Description

public Imagick::getImageProfiles(string `$pattern` = "*", bool `$include_values` = `true`): array

Returns all associated profiles that match the pattern. If `false` is passed as second parameter only the profile names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`pattern`

  The pattern for profile names.

`include_values`

  Whether to return only profile names. If `false` then only profile names will be returned.

### Return Values

Returns an array containing the image profiles or profile names.

# Imagick::getImageProperties

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProperties — Returns the image properties

### Description

public Imagick::getImageProperties(string `$pattern` = "*", bool `$include_values` = `true`): array

Returns all associated properties that match the pattern. If `false` is passed as second parameter only the property names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`pattern`

  The pattern for property names.

`include_values`

  Whether to return only property names. If `false` then only property names will be returned.

### Return Values

Returns an array containing the image properties or property names.

### Examples

Example #1 Using Imagick::getImageProperties():

An example of extracting EXIF information.

`<?php
/* Create the object */
$im = new imagick("/path/to/example.jpg");
/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");
/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
echo "{$name} => {$property}<br />\n";
}
?>`

# Imagick::getImageProperty

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProperty — Returns the named image property

### Description

public Imagick::getImageProperty(string `$name`): string

Returns the named image property. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

### Parameters

`name`

  name of the property (for example Exif:DateTime)

### Return Values

Returns a string containing the image property, false if a property with the given name does not exist.

### Examples

Example #1 Using Imagick::getImageProperty():

Setting and getting image property

`<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>`

### See Also

- Imagick::setImageProperty() - Sets an image property

# Imagick::getImageRedPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

### Description

public Imagick::getImageRedPrimary(): array

Returns the chromaticity red primary point as an array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y". Throw an ImagickException on error.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageRegion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRegion — Extracts a region of the image

### Description

public Imagick::getImageRegion(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): Imagick

Extracts a region of the image and returns it as a new Imagick object.

### Parameters

`width`

  The width of the extracted region.

`height`

  The height of the extracted region.

`x`

  X-coordinate of the top-left corner of the extracted region.

`y`

  Y-coordinate of the top-left corner of the extracted region.

### Return Values

Extracts a region of the image and returns it as a new wand.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageRenderingIntent

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRenderingIntent — Gets the image rendering intent

### Description

public Imagick::getImageRenderingIntent(): int

Gets the image rendering intent.

### Parameters

This function has no parameters.

### Return Values

Returns the image rendering intent.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageResolution

(PECL imagick 2, PECL imagick 3)

Imagick::getImageResolution — Gets the image X and Y resolution

### Description

public Imagick::getImageResolution(): array

Gets the image X and Y resolution.

### Parameters

This function has no parameters.

### Return Values

Returns the resolution as an array.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImagesBlob

(PECL imagick 2, PECL imagick 3)

Imagick::getImagesBlob — Returns all image sequences as a blob

### Description

public Imagick::getImagesBlob(): string

Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the images. On failure, throws ImagickException.

# Imagick::getImageScene

(PECL imagick 2, PECL imagick 3)

Imagick::getImageScene — Gets the image scene

### Description

public Imagick::getImageScene(): int

Gets the image scene.

### Parameters

This function has no parameters.

### Return Values

Returns the image scene.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageSignature

(PECL imagick 2, PECL imagick 3)

Imagick::getImageSignature — Generates an SHA-256 message digest

### Description

public Imagick::getImageSignature(): string

Generates an SHA-256 message digest for the image pixel stream.

### Parameters

This function has no parameters.

### Return Values

Returns a string containing the SHA-256 hash of the file.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageSize

(PECL imagick 2, PECL imagick 3)

Imagick::getImageSize — Returns the image length in bytes

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::getImageSize(): int

Returns the image length in bytes. Deprecated in favour of Imagick::getImageLength()

### Parameters

This function has no parameters.

### Return Values

Returns an int containing the current image size.

# Imagick::getImageTicksPerSecond

(PECL imagick 2, PECL imagick 3)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

### Description

public Imagick::getImageTicksPerSecond(): int

Gets the image ticks-per-second.

### Parameters

This function has no parameters.

### Return Values

Returns the image ticks-per-second.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageTotalInkDensity

(PECL imagick 2, PECL imagick 3)

Imagick::getImageTotalInkDensity — Gets the image total ink density

### Description

public Imagick::getImageTotalInkDensity(): float

Gets the image total ink density.

### Parameters

This function has no parameters.

### Return Values

Returns the image total ink density of the image. Throw an ImagickException on error.

# Imagick::getImageType

(PECL imagick 2, PECL imagick 3)

Imagick::getImageType — Gets the potential image type

### Description

public Imagick::getImageType(): int

Gets the potential image type.

### Parameters

This function has no parameters.

### Return Values

Returns the potential image type.

- `imagick::IMGTYPE_UNDEFINED`
- `imagick::IMGTYPE_BILEVEL`
- `imagick::IMGTYPE_GRAYSCALE`
- `imagick::IMGTYPE_GRAYSCALEMATTE`
- `imagick::IMGTYPE_PALETTE`
- `imagick::IMGTYPE_PALETTEMATTE`
- `imagick::IMGTYPE_TRUECOLOR`
- `imagick::IMGTYPE_TRUECOLORMATTE`
- `imagick::IMGTYPE_COLORSEPARATION`
- `imagick::IMGTYPE_COLORSEPARATIONMATTE`
- `imagick::IMGTYPE_OPTIMIZE`

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageUnits

(PECL imagick 2, PECL imagick 3)

Imagick::getImageUnits — Gets the image units of resolution

### Description

public Imagick::getImageUnits(): int

Gets the image units of resolution.

### Parameters

This function has no parameters.

### Return Values

Returns the image units of resolution.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageVirtualPixelMethod

(PECL imagick 2, PECL imagick 3)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

### Description

public Imagick::getImageVirtualPixelMethod(): int

Returns the virtual pixel method for the specified image.

### Parameters

This function has no parameters.

### Return Values

Returns the virtual pixel method on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageWhitePoint

(PECL imagick 2, PECL imagick 3)

Imagick::getImageWhitePoint — Returns the chromaticity white point

### Description

public Imagick::getImageWhitePoint(): array

Returns the chromaticity white point as an associative array with the keys "x" and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getImageWidth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageWidth — Returns the image width

### Description

public Imagick::getImageWidth(): int

Returns the image width.

### Parameters

This function has no parameters.

### Return Values

Returns the image width.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::getInterlaceScheme — Gets the object interlace scheme

### Description

public Imagick::getInterlaceScheme(): int

Gets the object interlace scheme.

### Parameters

This function has no parameters.

### Return Values

Gets the wand interlace scheme.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getIteratorIndex

(PECL imagick 2, PECL imagick 3)

Imagick::getIteratorIndex — Gets the index of the current active image

### Description

public Imagick::getIteratorIndex(): int

Returns the index of the current active image within the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns an integer containing the index of the image in the stack.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::getIteratorIndex():

Create images, set and get the iterator index

`<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));
$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>`

### See Also

- Imagick::setIteratorIndex() - Set the iterator position
- Imagick::getImageIndex() - Gets the index of the current active image
- Imagick::setImageIndex() - Set the iterator position

# Imagick::getNumberImages

(PECL imagick 2, PECL imagick 3)

Imagick::getNumberImages — Returns the number of images in the object

### Description

public Imagick::getNumberImages(): int

Returns the number of images associated with Imagick object.

### Parameters

This function has no parameters.

### Return Values

Returns the number of images associated with Imagick object.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getOption

(PECL imagick 2, PECL imagick 3)

Imagick::getOption — Returns a value associated with the specified key

### Description

public Imagick::getOption(string `$key`): string

Returns a value associated within the object for the specified key.

### Parameters

`key`

  The name of the option

### Return Values

Returns a value associated with a wand and the specified key.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getPackageName

(PECL imagick 2, PECL imagick 3)

Imagick::getPackageName — Returns the ImageMagick package name

### Description

public static Imagick::getPackageName(): string

Returns the ImageMagick package name.

### Parameters

This function has no parameters.

### Return Values

Returns the ImageMagick package name as a string.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getPage

(PECL imagick 2, PECL imagick 3)

Imagick::getPage — Returns the page geometry

### Description

public Imagick::getPage(): array

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

### Parameters

This function has no parameters.

### Return Values

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error.

# Imagick::getPixelIterator

(PECL imagick 2, PECL imagick 3)

Imagick::getPixelIterator — Returns a MagickPixelIterator

### Description

public Imagick::getPixelIterator(): ImagickPixelIterator

Returns a MagickPixelIterator.

### Parameters

This function has no parameters.

### Return Values

Returns an ImagickPixelIterator on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::getPixelIterator()

`<?php
function getPixelIterator($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelIterator();
foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */
foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
/** @var $pixel \ImagickPixel */
if ($column % 2) {
$pixel->setColor("rgba(0, 0, 0, 0)"); /* Paint every second pixel black*/
}
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# Imagick::getPixelRegionIterator

(PECL imagick 2, PECL imagick 3)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

### Description

public Imagick::getPixelRegionIterator(
int `$x`,
int `$y`,
int `$columns`,
int `$rows`
): ImagickPixelIterator

Get an ImagickPixelIterator for an image section.

### Parameters

`x`

  The x-coordinate of the region.

`y`

  The y-coordinate of the region.

`columns`

  The width of the region.

`rows`

  The height of the region.

### Return Values

Returns an ImagickPixelIterator for an image section.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::getPixelRegionIterator() example

Iterate over the pixels in the top left of the image, changing them to be black.

`<?php
$im = new Imagick(realpath("./testImage.png"));
$areaIterator = $im->getPixelRegionIterator(0, 0, 10, 10);
foreach ($areaIterator as $rowIterator) {
foreach ($rowIterator as $pixel) {
// Paint every pixel black
$pixel->setColor("rgba(0, 0, 0, 0)");
}
$areaIterator->syncIterator();
}
$im->writeImage("./output.png");
?>`

# Imagick::getPointSize

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::getPointSize — Gets point size

### Description

public Imagick::getPointSize(): float

Returns the objects point size property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns a float containing the point size.

### See Also

- Imagick::setPointSize() - Sets point size

# Imagick::getQuantum

(PECL imagick 3 >= 3.3.0)

Imagick::getQuantum — Returns the ImageMagick quantum range

### Description

public static Imagick::getQuantum(): int

Returns the ImageMagick quantum range. If HDRI was enabled then the type is a float, if not it is an int.

### Parameters

This function has no parameters.

### Return Values

# Imagick::getQuantumDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getQuantumDepth — Gets the quantum depth

### Description

public static Imagick::getQuantumDepth(): array

Returns the Imagick quantum depth.

### Parameters

This function has no parameters.

### Return Values

Returns an array with `"quantumDepthLong"` and `"quantumDepthString"` members.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getQuantumRange

(PECL imagick 2, PECL imagick 3)

Imagick::getQuantumRange — Returns the Imagick quantum range

### Description

public static Imagick::getQuantumRange(): array

Returns the quantum range for the Imagick instance.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array containing the quantum range as an int (`"quantumRangeLong"`) and as a string (`"quantumRangeString"`).

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::getRegistry — Get a StringRegistry entry

### Description

public static Imagick::getRegistry(string `$key`): string

Get the StringRegistry entry for the named key or false if not set.

### Parameters

`key`

  The entry to get.

### Return Values

# Imagick::getReleaseDate

(PECL imagick 2, PECL imagick 3)

Imagick::getReleaseDate — Returns the ImageMagick release date

### Description

public static Imagick::getReleaseDate(): string

Returns the ImageMagick release date as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the ImageMagick release date as a string.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getResource

(PECL imagick 2, PECL imagick 3)

Imagick::getResource — Returns the specified resource's memory usage

### Description

public static Imagick::getResource(int `$type`): int

Returns the specified resource's memory usage in megabytes.

### Parameters

`type`

  Refer to the list of resourcetype constants.

### Return Values

Returns the specified resource's memory usage in megabytes.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getResourceLimit

(PECL imagick 2, PECL imagick 3)

Imagick::getResourceLimit — Returns the specified resource limit

### Description

public static Imagick::getResourceLimit(int `$type`): int

Returns the specified resource limit.

### Parameters

`type`

  One of the resourcetype constants.

### Return Values

Returns the specified resource limit. The unit depends on the type of the resource being limited.

### Errors/Exceptions

Throws ImagickException on error.

### See Also

- Imagick::setResourceLimit() - Sets the limit for a particular resource

# Imagick::getSamplingFactors

(PECL imagick 2, PECL imagick 3)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

### Description

public Imagick::getSamplingFactors(): array

Gets the horizontal and vertical sampling factor.

### Parameters

This function has no parameters.

### Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getSize

(PECL imagick 2, PECL imagick 3)

Imagick::getSize — Returns the size associated with the Imagick object

### Description

public Imagick::getSize(): array

Get the size in pixels associated with the Imagick object, previously set by Imagick::setSize().

> Note:

> This method just returns the size that was set using Imagick::setSize(). If you want to get the actual width / height of the image, use Imagick::getImageWidth() and Imagick::getImageHeight().

### Parameters

This function has no parameters.

### Return Values

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

### Examples

Example #1 Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)

`<?php
//Set size first and then load the raw image
$img = new Imagick();
$img->setSize(200, 400);
$img->readImage("image.rgb");
$img->scaleImage(400, 800);
$size = $img->getSize();
print_r($size);
echo $img->getImageWidth()."x".$img->getImageHeight();
?>`

The above example will output:

    Array
    (
        [columns] => 200
        [rows] => 400
    )
    400x800

# Imagick::getSizeOffset

(PECL imagick 2, PECL imagick 3)

Imagick::getSizeOffset — Returns the size offset

### Description

public Imagick::getSizeOffset(): int

Returns the size offset associated with the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns the size offset associated with the Imagick object.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::getVersion

(PECL imagick 2, PECL imagick 3)

Imagick::getVersion — Returns the ImageMagick API version

### Description

public static Imagick::getVersion(): array

Returns the ImageMagick API version as a string and as a number.

### Parameters

This function has no parameters.

### Return Values

Returns the ImageMagick API version as a string and as a number.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::haldClutImage

(PECL imagick 3)

Imagick::haldClutImage — Replaces colors in the image

### Description

public Imagick::haldClutImage(Imagick `$clut`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Replaces colors in the image using a Hald lookup table. Hald images can be created using HALD color coder.

### Parameters

`clut`

  Imagick object containing the Hald lookup image.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::haldClutImage()

`<?php
function haldClutImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagickPalette = new \Imagick(realpath("images/hald/hald_8.png"));
$imagickPalette->sepiatoneImage(55);
$imagick->haldClutImage($imagickPalette);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::hasNextImage

(PECL imagick 2, PECL imagick 3)

Imagick::hasNextImage — Checks if the object has more images

### Description

public Imagick::hasNextImage(): bool

Returns `true` if the object has more images when traversing the list in the forward direction.

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the object has more images when traversing the list in the forward direction, returns `false` if there are none.

# Imagick::hasPreviousImage

(PECL imagick 2, PECL imagick 3)

Imagick::hasPreviousImage — Checks if the object has a previous image

### Description

public Imagick::hasPreviousImage(): bool

Returns `true` if the object has more images when traversing the list in the reverse direction

### Parameters

This function has no parameters.

### Return Values

Returns `true` if the object has more images when traversing the list in the reverse direction, returns `false` if there are none.

# Imagick::identifyFormat

(PECL imagick 3 >= 3.3.0)

Imagick::identifyFormat — Formats a string with image details

### Description

public Imagick::identifyFormat(string `$embedText`): string|false

Replaces any embedded formatting characters with the appropriate image property and returns the interpreted text. See http://www.imagemagick.org/script/escape.php for escape sequences.

### Parameters

`embedText`

  A string containing formatting sequences e.g. "Trim box: %@ number of unique colors: %k".

### Return Values

Returns format or `false` on failure.

### Examples

Example #1 Imagick::identifyFormat()

`<?php
$output = "Output of 'Trim box: %@ number of unique colors: %k' is: <br/>";
$imagick = new \Imagick(realpath("./images/artifact/mask.png"));
$output .= $imagick->identifyFormat("Trim box: %@ number of unique colors: %k");
?>`

# Imagick::identifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::identifyImage — Identifies an image and fetches attributes

### Description

public Imagick::identifyImage(bool `$appendRawOutput` = `false`): array

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

### Parameters

`appendRawOutput`

  If `true` then the raw output is appended to the array.

### Return Values

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Example Result Format

    Array
    (
        [imageName] => /some/path/image.jpg
        [format] => JPEG (Joint Photographic Experts Group JFIF format)
        [geometry] => Array
            (
                [width] => 90
                [height] => 90
            )

        [type] => TrueColor
        [colorSpace] => RGB
        [resolution] => Array
            (
                [x] => 300
                [y] => 300
            )

        [units] => PixelsPerInch
        [fileSize] => 1.88672kb
        [compression] => JPEG
        [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
    )

# Imagick::implodeImage

(PECL imagick 2, PECL imagick 3)

Imagick::implodeImage — Creates a new image as a copy

### Description

public Imagick::implodeImage(float `$radius`): bool

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

### Parameters

`radius`

  The radius of the implode

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::implodeImage()

`<?php
function implodeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->implodeImage(0.0001);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::importImagePixels

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::importImagePixels — Imports image pixels

### Description

public Imagick::importImagePixels(
int `$x`,
int `$y`,
int `$width`,
int `$height`,
string `$map`,
int `$storage`,
array `$pixels`
): bool

Imports pixels from an array into an image. The `map` is usually 'RGB'. This method imposes the following constraints for the parameters: amount of pixels in the array must match `width` x `height` x length of the map. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

### Parameters

`x`

  The image x position

`y`

  The image y position

`width`

  The image width

`height`

  The image height

`map`

  Map of pixel ordering as a string. This can be for example `RGB`. The value can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad.

`storage`

  The pixel storage method. Refer to this list of pixel constants.

`pixels`

  The array of pixels

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::importImagePixels() example

`<?php
/* Generate array of pixels. 2000 pixels per color stripe */
$count = 2000 * 3;
$pixels =
array_merge(array_pad(array(), $count, 0),
array_pad(array(), $count, 255),
array_pad(array(), $count, 0),
array_pad(array(), $count, 255),
array_pad(array(), $count, 0));
/* Width and height. The area is amount of pixels divided
by three. Three comes from 'RGB', three values per pixel */
$width = $height = pow((count($pixels) / 3), 0.5);
/* Create empty image */
$im = new Imagick();
$im->newImage($width, $height, 'gray');
/* Import the pixels into image.
width * height * strlen("RGB") must match count($pixels) */
$im->importImagePixels(0, 0, $width, $height, "RGB", Imagick::PIXEL_CHAR, $pixels);
/* output as jpeg image */
$im->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $im;
?>`

The above example will output something similar to:

# Imagick::inverseFourierTransformImage

(PECL imagick 3 >= 3.3.0)

Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)

### Description

public Imagick::inverseFourierTransformImage(Imagick `$complement`, bool `$magnitude`): bool

Implements the inverse discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`complement`

  The second image to combine with this one to form either the magnitude / phase or real / imaginary image pair.

`magnitude`

  If true, combine as magnitude / phase pair otherwise a real / imaginary image pair.

### Return Values

Returns `true` on success.

# Imagick::labelImage

(PECL imagick 2, PECL imagick 3)

Imagick::labelImage — Adds a label to an image

### Description

public Imagick::labelImage(string `$label`): bool

Adds a label to an image.

### Parameters

`label`

  The label to add

### Return Values

Returns `true` on success.

# Imagick::levelImage

(PECL imagick 2, PECL imagick 3)

Imagick::levelImage — Adjusts the levels of an image

### Description

public Imagick::levelImage(
float `$blackPoint`,
float `$gamma`,
float `$whitePoint`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

### Parameters

`blackPoint`

  The image black point

`gamma`

  The gamma value

`whitePoint`

  The image white point

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::levelImage()

`<?php
function levelImage($blackPoint, $gamma, $whitePoint) {
$imagick = new \Imagick();
$imagick->newPseudoimage(500, 500, 'gradient:black-white');
$imagick->setFormat('png');
$quantum = $imagick->getQuantum();
$imagick->levelImage($blackPoint / 100 , $gamma, $quantum * $whitePoint / 100);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::linearStretchImage

(PECL imagick 2, PECL imagick 3)

Imagick::linearStretchImage — Stretches with saturation the image intensity

### Description

public Imagick::linearStretchImage(float `$blackPoint`, float `$whitePoint`): bool

Stretches with saturation the image intensity.

### Parameters

`blackPoint`

  The image black point

`whitePoint`

  The image white point

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::linearStretchImage()

`<?php
function linearStretchImage($imagePath, $blackThreshold, $whiteThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$pixels = $imagick->getImageWidth() * $imagick->getImageHeight();
$imagick->linearStretchImage($blackThreshold * $pixels, $whiteThreshold * $pixels);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::liquidRescaleImage

(PECL imagick 2 >= 2.2.0, PECL imagick 3)

Imagick::liquidRescaleImage — Animates an image or images

### Description

public Imagick::liquidRescaleImage(
int `$width`,
int `$height`,
float `$delta_x`,
float `$rigidity`
): bool

This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

### Parameters

`width`

  The width of the target size

`height`

  The height of the target size

`delta_x`

  How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight.

`rigidity`

  Introduces a bias for non-straight seams. This parameter is typically 0.

### Return Values

Returns `true` on success.

### See Also

- Imagick::resizeImage() - Scales an image

# Imagick::listRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::listRegistry — List all the registry settings

### Description

public static Imagick::listRegistry(): array

List all the registry settings. Returns an array of all the key/value pairs in the registry

### Parameters

This function has no parameters.

### Return Values

An array containing the key/values from the registry.

# Imagick::magnifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::magnifyImage — Scales an image proportionally 2x

### Description

public Imagick::magnifyImage(): bool

Is a convenience method that scales an image proportionally to twice its original size.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::magnifyImage()

`<?php
function magnifyImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->magnifyImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::mapImage

(PECL imagick 2, PECL imagick 3)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::mapImage(Imagick `$map`, bool `$dither`): bool

### Parameters

`map`

`dither`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::matteFloodfillImage

(PECL imagick 2, PECL imagick 3)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::matteFloodfillImage(
float `$alpha`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`
): bool

Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method `FillToBorderMethod` is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.

### Parameters

`alpha`

  The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

`fuzz`

  The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

`bordercolor`

  An ImagickPixel object or string representing the border color.

`x`

  The starting x coordinate of the operation.

`y`

  The starting y coordinate of the operation.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

# Imagick::medianFilterImage

(PECL imagick 2, PECL imagick 3)

Imagick::medianFilterImage — Applies a digital filter

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::medianFilterImage(float `$radius`): bool

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

### Parameters

`radius`

  The radius of the pixel neighborhood.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::medianFilterImage()

`<?php
function medianFilterImage($radius, $imagePath) {
$imagick = new \Imagick(realpath($imagePath));
@$imagick->medianFilterImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::mergeImageLayers

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::mergeImageLayers — Merges image layers

### Description

public Imagick::mergeImageLayers(int `$layer_method`): Imagick

Merges image layers into one. This method is useful when working with image formats that use multiple layers such as PSD. The merging is controlled using the `layer_method` which defines how the layers are merged. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

### Parameters

`layer_method`

  One of the `Imagick::LAYERMETHOD_*` constants

### Return Values

Returns an Imagick object containing the merged image.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::mergeImageLayers()

`<?php
function mergeImageLayers($layerMethodType, $imagePath1, $imagePath2) {
$imagick = new \Imagick(realpath($imagePath));
$imagick2 = new \Imagick(realpath($imagePath2));
$imagick->addImage($imagick2);
$imagick->setImageFormat('png');
$result = $imagick->mergeImageLayers($layerMethodType);
header("Content-Type: image/png");
echo $result->getImageBlob();
}
?>`

### See Also

- Imagick::flattenImages() - Merges a sequence of images

# Imagick::minifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::minifyImage — Scales an image proportionally to half its size

### Description

public Imagick::minifyImage(): bool

Is a convenience method that scales an image proportionally to one-half its original size

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::modulateImage

(PECL imagick 2, PECL imagick 3)

Imagick::modulateImage — Control the brightness, saturation, and hue

### Description

public Imagick::modulateImage(float `$brightness`, float `$saturation`, float `$hue`): bool

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

### Parameters

`brightness`

`saturation`

`hue`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::modulateImage()

`<?php
function modulateImage($imagePath, $hue, $brightness, $saturation) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->modulateImage($brightness, $saturation, $hue);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::montageImage

(PECL imagick 2, PECL imagick 3)

Imagick::montageImage — Creates a composite image

### Description

public Imagick::montageImage(
ImagickDraw `$draw`,
string `$tile_geometry`,
string `$thumbnail_geometry`,
int `$mode`,
string `$frame`
): Imagick

Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.

### Parameters

`draw`

  The font name, size, and color are obtained from this object.

`tile_geometry`

  The number of tiles per row and page (e.g. 6x4+0+0).

`thumbnail_geometry`

  Preferred image size and border size of each thumbnail (e.g. 120x120+4+3).

`mode`

  Thumbnail framing mode, see Montage Mode constants.

`frame`

  Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.

### Return Values

Creates a composite image and returns it as a new Imagick object.

# Imagick::morphImages

(PECL imagick 2, PECL imagick 3)

Imagick::morphImages — Method morphs a set of images

### Description

public Imagick::morphImages(int `$number_frames`): Imagick

Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.

### Parameters

`number_frames`

  The number of in-between images to generate.

### Return Values

This method returns a new Imagick object on success. Throw an ImagickException on error.

# Imagick::morphology

(PECL imagick 3 >= 3.3.0)

Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.

### Description

public Imagick::morphology(
int `$morphologyMethod`,
int `$iterations`,
ImagickKernel `$ImagickKernel`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Applies a user supplied kernel to the image according to the given morphology method.

### Parameters

`morphologyMethod`

  Which morphology method to use one of the \Imagick::MORPHOLOGY_* constants.

`iterations`

  The number of iteration to apply the morphology function. A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1.

`ImagickKernel`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Convolve Imagick::morphology()

`<?php
$imagick = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_GAUSSIAN, "5,1");
$imagick->morphology(\Imagick::MORPHOLOGY_CONVOLVE, 2, $kernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>`

Example #2 Correlate Imagick::morphology()

`<?php
// Top-left pixel must be black
// Bottom right pixel must be white
// We don't care about the rest.
$imagick = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromMatrix(self::$correlateMatrix, [2, 2]);
$imagick->morphology(\Imagick::MORPHOLOGY_CORRELATE, 1, $kernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>`

Example #3 Erode Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_ERODE, 2, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #4 Erode Intensity Imagick::morphology()

`<?php
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
$canvas->morphology(\Imagick::MORPHOLOGY_ERODE_INTENSITY, 2, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #5 Dilate Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_DILATE, 4, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #6 Dilate intensity Imagick::morphology()

`<?php
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
$canvas->morphology(\Imagick::MORPHOLOGY_DILATE_INTENSITY, 4, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #7 Distance with Chebyshev kernel Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CHEBYSHEV, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #8 Distance with Manhattan kernel Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_MANHATTAN, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #9 Distance with ocatagonal kernel Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGONAL, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #10 Distance with Euclidean kernel Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_EUCLIDEAN, "4");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #11 Edge Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #12 Open Imagick::morphology()

`<?php
// As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_OPEN, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #13 Open intensity Imagick::morphology()

`<?php
// As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_OPEN_INTENSITY, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #14 Close Imagick::morphology()

`<?php
//The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #15 Close Intensity Imagick::morphology()

`<?php
//The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE_INTENSITY, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #16 Smooth Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_SMOOTH, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #17 Edge in Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE_IN, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #18 Edge out Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE_OUT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #19 The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_TOP_HAT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #20 The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_BOTTOM_HAT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #21 Hit and Miss Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
//This finds all the pixels with 3 pixels of the right edge
$matrix = [[1, false, false, 0]];
$kernel = \ImagickKernel::fromMatrix(
$matrix,
[0, 0]
);
$canvas->morphology(\Imagick::MORPHOLOGY_HIT_AND_MISS, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #22 Thinning Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
$rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
$leftEdgeKernel->addKernel($rightEdgeKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_THINNING, 3, $leftEdgeKernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #23 Thicken Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
$rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
$leftEdgeKernel->addKernel($rightEdgeKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, 3, $leftEdgeKernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #24 Thick to generate a convex hull Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$diamondKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "1");
$convexKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CONVEX_HULL, "");
// The thicken morphology doesn't handle small gaps. We close them
// with the close morphology.
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, -1, $convexKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #25 Iterative morphology Imagick::morphology()

`<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "2");
$canvas->morphology(\Imagick::MORPHOLOGY_ITERATIVE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();
?>`

Example #26 Helper function to get an image silhouette Imagick::morphology()

`<?php
function getCharacterOutline() {
$imagick = new \Imagick(realpath("./images/character.png"));
$character = new \Imagick();
$character->newPseudoImage(
$imagick->getImageWidth(),
$imagick->getImageHeight(),
"canvas:white"
);
$canvas = new \Imagick();
$canvas->newPseudoImage(
$imagick->getImageWidth(),
$imagick->getImageHeight(),
"canvas:black"
);
$character->compositeimage(
$imagick,
\Imagick::COMPOSITE_COPYOPACITY,
0, 0
);
$canvas->compositeimage(
$character,
\Imagick::COMPOSITE_ATOP,
0, 0
);
$canvas->setFormat('png');
return $canvas;
}
?>`

# Imagick::mosaicImages

(PECL imagick 2, PECL imagick 3)

Imagick::mosaicImages — Forms a mosaic from images

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::mosaicImages(): Imagick

Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::motionBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::motionBlurImage — Simulates motion blur

### Description

public Imagick::motionBlurImage(
float `$radius`,
float `$sigma`,
float `$angle`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel.

`sigma`

  The standard deviation of the Gaussian, in pixels.

`angle`

  Apply the effect along this angle.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants. The channel argument affects only if Imagick is compiled against ImageMagick version 6.4.4 or greater.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::motionBlurImage()

`<?php
function motionBlurImage($imagePath, $radius, $sigma, $angle, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->motionBlurImage($radius, $sigma, $angle, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::negateImage

(PECL imagick 2, PECL imagick 3)

Imagick::negateImage — Negates the colors in the reference image

### Description

public Imagick::negateImage(bool `$gray`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.

### Parameters

`gray`

  Whether to only negate grayscale pixels within the image.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::negateImage()

`<?php
function negateImage($imagePath, $grayOnly, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->negateImage($grayOnly, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::newImage

(PECL imagick 2, PECL imagick 3)

Imagick::newImage — Creates a new image

### Description

public Imagick::newImage(
int `$cols`,
int `$rows`,
mixed `$background`,
string `$format` = ?
): bool

Creates a new image and associates ImagickPixel value as background color

### Parameters

`cols`

  Columns in the new image

`rows`

  Rows in the new image

`background`

  The background color used for this image

`format`

  Image format. This parameter was added in Imagick version 2.0.1.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Using Imagick::newImage():

Create a new image and display it.

`<?php
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');
header('Content-type: image/png');
echo $image;
?>`

# Imagick::newPseudoImage

(PECL imagick 2, PECL imagick 3)

Imagick::newPseudoImage — Creates a new image

### Description

public Imagick::newPseudoImage(int `$columns`, int `$rows`, string `$pseudoString`): bool

Creates a new image using ImageMagick pseudo-formats.

### Parameters

`columns`

  columns in the new image

`rows`

  rows in the new image

`pseudoString`

  string containing pseudo image definition.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::newPseudoImage()

`<?php
function newPseudoImage($canvasType) {
$imagick = new \Imagick();
$imagick->newPseudoImage(300, 300, $canvasType);
$imagick->setImageFormat("png");
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
//newPseudoImage('gradient:red-rgba(64, 255, 255, 0.5)');
//newPseudoImage("radial-gradient:red-blue");
newPseudoImage("plasma:fractal");
?>`

# Imagick::nextImage

(PECL imagick 2, PECL imagick 3)

Imagick::nextImage — Moves to the next image

### Description

public Imagick::nextImage(): bool

Associates the next image in the image list with an Imagick object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::normalizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::normalizeImage — Enhances the contrast of a color image

### Description

public Imagick::normalizeImage(int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

### Parameters

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::normalizeImage()

`<?php
function normalizeImage($imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$original = clone $imagick;
$original->cropimage($original->getImageWidth() / 2, $original->getImageHeight(), 0, 0);
$imagick->normalizeImage($channel);
$imagick->compositeimage($original, \Imagick::COMPOSITE_ATOP, 0, 0);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::oilPaintImage

(PECL imagick 2, PECL imagick 3)

Imagick::oilPaintImage — Simulates an oil painting

### Description

public Imagick::oilPaintImage(float `$radius`): bool

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

### Parameters

`radius`

  The radius of the circular neighborhood.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::oilPaintImage()

`<?php
function oilPaintImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->oilPaintImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::opaquePaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

### Description

public Imagick::opaquePaintImage(
mixed `$target`,
mixed `$fill`,
float `$fuzz`,
bool `$invert`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Changes any pixel that matches color with the color defined by fill. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

### Parameters

`target`

  ImagickPixel object or a string containing the color to change

`fill`

  The replacement color

`fuzz`

  The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

`invert`

  If `true` paints any pixel that does not match the target color.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

# Imagick::optimizeImageLayers

(PECL imagick 2, PECL imagick 3)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

### Description

public Imagick::optimizeImageLayers(): bool

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::optimizeImageLayers()

Reading, optimizing and writing a GIF image

`<?php
/* create new imagick object */
$im = new Imagick("test.gif");
/* optimize the image layers */
$im->optimizeImageLayers();
/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>`

### See Also

- Imagick::compareImageLayers() - Returns the maximum bounding region between images
- Imagick::writeImages() - Writes an image or image sequence
- Imagick::writeImage() - Writes an image to the specified filename

# Imagick::orderedPosterizeImage

(PECL imagick 2 >= 2.2.2, PECL imagick 3)

Imagick::orderedPosterizeImage — Performs an ordered dither

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::orderedPosterizeImage(string `$threshold_map`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Performs an ordered dither based on a number of pre-defined dithering threshold maps, but over multiple intensity levels, which can be different for different channels, according to the input arguments. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

### Parameters

`threshold_map`

  A string containing the name of the threshold dither map to use

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::orderedPosterizeImage()

`<?php
function orderedPosterizeImage($imagePath, $orderedPosterizeType) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->orderedPosterizeImage($orderedPosterizeType);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
//orderedPosterizeImage($imagePath, 'o4x4,3,3');
//orderedPosterizeImage($imagePath, 'o8x8,6,6');
orderedPosterizeImage($imagePath, 'h8x8a');
?>`

# Imagick::paintFloodfillImage

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::paintFloodfillImage(
mixed `$fill`,
float `$fuzz`,
mixed `$bordercolor`,
int `$x`,
int `$y`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and Imagick::floodfillPaintImage() should be used instead.

### Parameters

`fill`

  ImagickPixel object or a string containing the fill color

`fuzz`

  The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

`bordercolor`

  ImagickPixel object or a string containing the border color

`x`

  X start position of the floodfill

`y`

  Y start position of the floodfill

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

# Imagick::paintOpaqueImage

(PECL imagick 2, PECL imagick 3)

Imagick::paintOpaqueImage — Change any pixel that matches color

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::paintOpaqueImage(
mixed `$target`,
mixed `$fill`,
float `$fuzz`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Changes any pixel that matches color with the color defined by fill.

### Parameters

`target`

  Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color.

`fill`

  An ImagickPixel object or a string representing the fill color.

`fuzz`

  The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.

# Imagick::paintTransparentImage

(PECL imagick 2, PECL imagick 3)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::paintTransparentImage(mixed `$target`, float `$alpha`, float `$fuzz`): bool

Changes any pixel that matches color with the color defined by fill.

### Parameters

`target`

  Change this target color to specified opacity value within the image.

`alpha`

  The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

`fuzz`

  The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

# Imagick::pingImage

(PECL imagick 2, PECL imagick 3)

Imagick::pingImage — Fetch basic attributes about the image

### Description

public Imagick::pingImage(string `$filename`): bool

This method can be used to query image width, height, size, and format without reading the whole image in to memory.

### Parameters

`filename`

  The filename to read the information from.

### Return Values

Returns `true` on success.

# Imagick::pingImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::pingImageBlob — Quickly fetch attributes

### Description

public Imagick::pingImageBlob(string `$image`): bool

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`image`

  A string containing the image.

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::pingImageBlob()

Pinging an image from a string

`<?php
/* read image contents */
$image = file_get_contents("test.jpg");
/* create new imagick object */
$im = new Imagick();
/* pass the string to the imagick object */
$im->pingImageBlob($image);
/* output image width and height */
echo $im->getImageWidth() . 'x' . $im->getImageHeight();
?>`

### See Also

- Imagick::pingImage() - Fetch basic attributes about the image
- Imagick::pingImageFile() - Get basic image attributes in a lightweight manner
- Imagick::readImage() - Reads image from filename
- Imagick::readImageBlob() - Reads image from a binary string
- Imagick::readImageFile() - Reads image from open filehandle

# Imagick::pingImageFile

(PECL imagick 2, PECL imagick 3)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

### Description

public Imagick::pingImageFile(resource `$filehandle`, string `$fileName` = ?): bool

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`filehandle`

  An open filehandle to the image.

`fileName`

  Optional filename for this image.

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::pingImageFile()

Opening a remote location

`<?php
/* fopen a remote location */
$fp = fopen("http://example.com/test.jpg");
/* create new imagick object */
$im = new Imagick();
/* pass the handle to imagick */
$im->pingImageFile($fp);
?>`

### See Also

- Imagick::pingImage() - Fetch basic attributes about the image
- Imagick::pingImageBlob() - Quickly fetch attributes
- Imagick::readImage() - Reads image from filename
- Imagick::readImageBlob() - Reads image from a binary string
- Imagick::readImageFile() - Reads image from open filehandle

# Imagick::polaroidImage

(PECL imagick 2, PECL imagick 3)

Imagick::polaroidImage — Simulates a Polaroid picture

### Description

public Imagick::polaroidImage(ImagickDraw `$properties`, float `$angle`): bool

Simulates a Polaroid picture. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

### Parameters

`properties`

  The polaroid properties

`angle`

  The polaroid angle

### Return Values

Returns `true` on success.

### Examples

Example #1 A Imagick::polaroidImage() example

An example of using Imagick::polaroidImage()

`<?php
/* Create the object */
$image = new Imagick('source.png');
/* Set the opacity */
$image->polaroidImage(new ImagickDraw(), 25);
/* output the image */
header('Content-type: image/png');
echo $image;
?>`

# Imagick::posterizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::posterizeImage — Reduces the image to a limited number of color level

### Description

public Imagick::posterizeImage(int `$levels`, bool `$dither`): bool

Reduces the image to a limited number of color level.

### Parameters

`levels`

`dither`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::posterizeImage()

`<?php
function posterizeImage($imagePath, $posterizeType, $numberLevels) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->posterizeImage($numberLevels, $posterizeType);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
posterizeImage($imagePath, \Imagick::DITHERMETHOD_RIEMERSMA, 8);
?>`

# Imagick::previewImages

(PECL imagick 2, PECL imagick 3)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

### Description

public Imagick::previewImages(int `$preview`): bool

Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.

### Parameters

`preview`

  Preview type. See Preview type constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::previousImage

(PECL imagick 2, PECL imagick 3)

Imagick::previousImage — Move to the previous image in the object

### Description

public Imagick::previousImage(): bool

Associates the previous image in an image list with the Imagick object.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::profileImage

(PECL imagick 2, PECL imagick 3)

Imagick::profileImage — Adds or removes a profile from an image

### Description

public Imagick::profileImage(string `$name`, string `$profile` = ?): bool

Adds or removes a ICC, IPTC, or generic profile from an image. If the `profile` is `null`, it is removed from the image rather than added.

To remove every single profile from the image use `'*'` as the `name` and `null` for the `profile`.

### Parameters

`name`
  The profile name.
`profile`
  The profile data. If `null`, the specified profile will be deleted.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::quantizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::quantizeImage — Analyzes the colors within a reference image

### Description

public Imagick::quantizeImage(
int `$numberColors`,
int `$colorspace`,
int `$treedepth`,
bool `$dither`,
bool `$measureError`
): bool

### Parameters

`numberColors`

`colorspace`

`treedepth`

`dither`

`measureError`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::quantizeImage()

`<?php
function quantizeImage($imagePath, $numberColors, $colorSpace, $treeDepth, $dither) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::quantizeImages

(PECL imagick 2, PECL imagick 3)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

### Description

public Imagick::quantizeImages(
int `$numberColors`,
int `$colorspace`,
int `$treedepth`,
bool `$dither`,
bool `$measureError`
): bool

### Parameters

`numberColors`

`colorspace`

`treedepth`

`dither`

`measureError`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::queryFontMetrics

(PECL imagick 2, PECL imagick 3)

Imagick::queryFontMetrics — Returns an array representing the font metrics

### Description

public Imagick::queryFontMetrics(ImagickDraw `$properties`, string `$text`, bool `$multiline` = ?): array

Returns a multi-dimensional array representing the font metrics.

### Parameters

`properties`

  ImagickDraw object containing font properties

`text`

  The text

`multiline`

  Multiline parameter. If left empty it is autodetected

### Return Values

Returns a multi-dimensional array representing the font metrics.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::queryFontMetrics():

Query the metrics for the text and dump the results on the screen.

`<?php
/* Create a new Imagick object */
$im = new Imagick();
/* Create an ImagickDraw object */
$draw = new ImagickDraw();
/* Set the font */
$draw->setFont('/path/to/font.ttf');
/* Dump the font metrics, autodetect multiline */
var_dump($im->queryFontMetrics($draw, "Hello World!"));
?>`

# Imagick::queryFonts

(PECL imagick 2, PECL imagick 3)

Imagick::queryFonts — Returns the configured fonts

### Description

public static Imagick::queryFonts(string `$pattern` = "*"): array

Returns the configured fonts.

### Parameters

`pattern`

  The query pattern

### Return Values

Returns an array containing the configured fonts.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::queryFonts()

`<?php
$output = '';
$output .= "Fonts that match 'Helvetica*' are:<br/>";
$fontList = \Imagick::queryFonts("Helvetica*");
foreach ($fontList as $fontName) {
$output .= '<li>'. $fontName."</li>";
}
return $output;
?>`

# Imagick::queryFormats

(PECL imagick 2, PECL imagick 3)

Imagick::queryFormats — Returns formats supported by Imagick

### Description

public static Imagick::queryFormats(string `$pattern` = "*"): array

Returns formats supported by Imagick.

### Parameters

`pattern`

### Return Values

Returns an array containing the formats supported by Imagick.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::queryFormats()

`<?php
function render() {
$output = "";
$input = \Imagick::queryformats();
$columns = 6;
$output .= "<table border='2'>";
for ($i=0; $i < count($input); $i += $columns) {
$output .= "<tr>";
for ($c=0; $c<$columns; $c++) {
$output .= "<td>";
if (($i + $c) < count($input)) {
$output .= $input[$i + $c];
}
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
return $output;
}
?>`

# Imagick::radialBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::radialBlurImage — Radial blurs an image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::radialBlurImage(float `$angle`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Radial blurs an image.

### Parameters

`angle`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::radialBlurImage()

`<?php
function radialBlurImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
//Blur 3 times with different radii
$imagick->radialBlurImage(3);
$imagick->radialBlurImage(5);
$imagick->radialBlurImage(7);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::raiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::raiseImage — Creates a simulated 3d button-like effect

### Description

public Imagick::raiseImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`,
bool `$raise`
): bool

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

### Parameters

`width`

`height`

`x`

`y`

`raise`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::raiseImage()

`<?php
function raiseImage($imagePath, $width, $height, $x, $y, $raise) {
$imagick = new \Imagick(realpath($imagePath));
//x and y do nothing?
$imagick->raiseImage($width, $height, $x, $y, $raise);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::randomThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

### Description

public Imagick::randomThresholdImage(float `$low`, float `$high`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`low`

  The low point

`high`

  The high point

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::randomThresholdImage()

`<?php
function randomThresholdimage($imagePath, $lowThreshold, $highThreshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->randomThresholdimage(
$lowThreshold * \Imagick::getQuantum(),
$highThreshold * \Imagick::getQuantum(),
$channel
);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::readImage

(PECL imagick 2, PECL imagick 3)

Imagick::readImage — Reads image from filename

### Description

public Imagick::readImage(string `$filename`): bool

Reads image from filename

### Parameters

`filename`

### Return Values

Returns `true` on success.

# Imagick::readImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::readImageBlob — Reads image from a binary string

### Description

public Imagick::readImageBlob(string `$image`, string `$filename` = ?): bool

Reads image from a binary string

### Parameters

`image`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::readImageBlob()

`<?php
function readImageBlob() {
$base64 = "iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
gCAQBVDLuv+V20dENbMY831wKz4Y/VHb/5RGQ0NDQ0NDQ0NDQ0NDQ0NDQ
0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PzMWtyaGhoaGhoaGhoaGhoaGhoxtb0QGho
aGhoaGhoaGhoaGhoaMbRLEvv50VTQ9OTQ5OpyZ01GpM2g0bfmDQaL7S+ofFC6x
v3ZpxJiywakzbvd9r3RWPS9I2+MWk0+kbf0Hih9Y17U0nTHibrDDQ0NDQ0NDQ0
NDQ0NDQ0NTXbRSL/AK72o6GhoaGhoRlL8951vwsNDQ0NDQ1NDc0WyHtDTEhD
Q0NDQ0NTS5MdGhoaGhoaGhoaGhoaGhoaGhoaGhoaGposzSHAAErMwwQ2HwRQ
AAAAAElFTkSuQmCC";
$imageBlob = base64_decode($base64);
$imagick = new Imagick();
$imagick->readImageBlob($imageBlob);
header("Content-Type: image/png");
echo $imagick;
}
?>`

# Imagick::readImageFile

(PECL imagick 2, PECL imagick 3)

Imagick::readImageFile — Reads image from open filehandle

### Description

public Imagick::readImageFile(resource `$filehandle`, string `$fileName` = `null`): bool

Reads image from open filehandle

### Parameters

`filehandle`

`fileName`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::readimages

(PECL imagick 2, PECL imagick 3)

Imagick::readimages — Reads image from an array of filenames

### Description

public Imagick::readImages(array `$filenames`): bool

Reads image from an array of filenames. All the images are held in a single Imagick object.

### Parameters

`filenames`

### Return Values

Returns `true` on success.

# Imagick::recolorImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::recolorImage — Recolors image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::recolorImage(array `$matrix`): bool

Translate, scale, shear, or rotate image colors. This method supports variable sized matrices but normally 5x5 matrix is used for RGBA and 6x6 is used for CMYK. The last row should contain the normalized values. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`matrix`

  The matrix containing the color values

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::recolorImage()

`<?php
function recolorImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$remapColor = [ 1, 0, 0,
0, 0, 1,
0, 1, 0,];
//$remapColor = [
// 1.438, -0.122, -0.016, 0, 0, -0.03,
// -0.062, 1.378, -0.016, 0, 0, 0.05,
// -0.062, -0.122, 1.483, 0, 0, -0.02,
//];
@$imagick->recolorImage($remapColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::displayImage() - Displays an image

# Imagick::reduceNoiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::reduceNoiseImage — Smooths the contours of an image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::reduceNoiseImage(float `$radius`): bool

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Imagick::reduceNoiseImage() selects a suitable radius for you.

### Parameters

`radius`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::reduceNoiseImage()

`<?php
function reduceNoiseImage($imagePath, $reduceNoise) {
$imagick = new \Imagick(realpath($imagePath));
@$imagick->reduceNoiseImage($reduceNoise);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::remapImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::remapImage — Remaps image colors

### Description

public Imagick::remapImage(Imagick `$replacement`, int `$DITHER`): bool

Replaces colors an image with those defined by `replacement`. The colors are replaced with the closest possible color. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

### Parameters

`replacement`

  An Imagick object containing the replacement colors

`DITHER`

  Refer to this list of dither method constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::removeImage

(PECL imagick 2, PECL imagick 3)

Imagick::removeImage — Removes an image from the image list

### Description

public Imagick::removeImage(): bool

Removes an image from the image list.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::removeImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::removeImageProfile — Removes the named image profile and returns it

### Description

public Imagick::removeImageProfile(string `$name`): string

Removes the named image profile and returns it.

### Parameters

`name`

### Return Values

Returns a string containing the profile of the image.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::render

(PECL imagick 2, PECL imagick 3)

Imagick::render — Renders all preceding drawing commands

### Description

public Imagick::render(): bool

Renders all preceding drawing commands.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::resampleImage

(PECL imagick 2, PECL imagick 3)

Imagick::resampleImage — Resample image to desired resolution

### Description

public Imagick::resampleImage(
float `$x_resolution`,
float `$y_resolution`,
int `$filter`,
float `$blur`
): bool

Resample image to desired resolution.

### Parameters

`x_resolution`

`y_resolution`

`filter`

`blur`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::resampleImage()

`<?php
function resampleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->resampleImage(200, 200, \Imagick::FILTER_LANCZOS, 1);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::resetImagePage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::resetImagePage — Reset image page

### Description

public Imagick::resetImagePage(string `$page`): bool

The page definition as a string. The string is in format WxH+x+y. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`page`

  The page definition. For example `7168x5147+0+0`

### Return Values

Returns `true` on success.

# Imagick::resizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::resizeImage — Scales an image

### Description

public Imagick::resizeImage(
int `$columns`,
int `$rows`,
int `$filter`,
float `$blur`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool

Scales an image to the desired dimensions with a filter.

> Note: The behavior of the parameter `bestfit` changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If `bestfit` parameter is used both width and height must be given.

### Parameters

`columns`

  Width of the image

`rows`

  Height of the image

`filter`

  Refer to the list of filter constants.

`blur`

  The blur factor where > 1 is blurry, < 1 is sharp.

`bestfit`

  Optional fit parameter.

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

### Examples

Example #1 Imagick::resizeImage()

`<?php
function resizeImage($imagePath, $width, $height, $filterType, $blur, $bestFit, $cropZoom) {
//The blur factor where > 1 is blurry, < 1 is sharp.
$imagick = new \Imagick(realpath($imagePath));
$imagick->resizeImage($width, $height, $filterType, $blur, $bestFit);
$cropWidth = $imagick->getImageWidth();
$cropHeight = $imagick->getImageHeight();
if ($cropZoom) {
$newWidth = $cropWidth / 2;
$newHeight = $cropHeight / 2;
$imagick->cropimage(
$newWidth,
$newHeight,
($cropWidth - $newWidth) / 2,
($cropHeight - $newHeight) / 2
);
$imagick->scaleimage(
$imagick->getImageWidth() * 4,
$imagick->getImageHeight() * 4
);
}
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::rollImage

(PECL imagick 2, PECL imagick 3)

Imagick::rollImage — Offsets an image

### Description

public Imagick::rollImage(int `$x`, int `$y`): bool

Offsets an image as defined by x and y.

### Parameters

`x`

  The X offset.

`y`

  The Y offset.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::rollImage()

`<?php
function rollImage($imagePath, $rollX, $rollY) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rollimage($rollX, $rollY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::rotateImage

(PECL imagick 2, PECL imagick 3)

Imagick::rotateImage — Rotates an image

### Description

public Imagick::rotateImage(mixed `$background`, float `$degrees`): bool

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

### Parameters

`background`

  The background color

`degrees`

  Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image clockwise.

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::rotateImage()

`<?php
function rotateImage($imagePath, $angle, $color) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rotateimage($color, $angle);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::rotationalBlurImage

(PECL imagick 3 >= 3.3.0)

Imagick::rotationalBlurImage — Rotational blurs an image

### Description

public Imagick::rotationalBlurImage(float `$angle`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Rotational blurs an image.

### Parameters

`angle`

  The angle to apply the blur over.

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::rotationalBlurImage()

`<?php
function rotationalBlurImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rotationalBlurImage(3);
$imagick->rotationalBlurImage(5);
$imagick->rotationalBlurImage(7);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::roundCorners

(PECL imagick 2, PECL imagick 3)

Imagick::roundCorners — Rounds image corners

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::roundCorners(
float `$x_rounding`,
float `$y_rounding`,
float `$stroke_width` = 10,
float `$displace` = 5,
float `$size_correction` = -6
): bool

Rounds image corners. The first two parameters control the amount of rounding and the three last parameters can be used to fine-tune the rounding process. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. This method is not available if Imagick has been compiled against ImageMagick version 7.0.0 or newer.

### Parameters

`x_rounding`

  x rounding

`y_rounding`

  y rounding

`stroke_width`

  stroke width

`displace`

  image displace

`size_correction`

  size correction

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::roundCorners():

Rounds the image corners

`<?php
$image = new Imagick();
$image->newPseudoImage(100, 100, "magick:rose");
$image->setImageFormat("png");
$image->roundCorners(5,3);
$image->writeImage("rounded.png");
?>`

# Imagick::sampleImage

(PECL imagick 2, PECL imagick 3)

Imagick::sampleImage — Scales an image with pixel sampling

### Description

public Imagick::sampleImage(int `$columns`, int `$rows`): bool

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

### Parameters

`columns`

`rows`

### Return Values

Returns `true` on success.

# Imagick::scaleImage

(PECL imagick 2, PECL imagick 3)

Imagick::scaleImage — Scales the size of an image

### Description

public Imagick::scaleImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$legacy` = `false`
): bool

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

> Note: The behavior of the parameter `bestfit` changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If `bestfit` parameter is used both width and height must be given.

### Parameters

`columns`

`rows`

`bestfit`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

### Examples

Example #1 Imagick::scaleImage()

`<?php
function scaleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->scaleImage(150, 150, true);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::segmentImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::segmentImage — Segments an image

### Description

public Imagick::segmentImage(
int `$COLORSPACE`,
float `$cluster_threshold`,
float `$smooth_threshold`,
bool `$verbose` = `false`
): bool

Analyses the image and identifies units that are similar. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

### Parameters

`COLORSPACE`

  One of the COLORSPACE constants.

`cluster_threshold`

  A percentage describing minimum number of pixels contained in hexedra before it is considered valid.

`smooth_threshold`

  Eliminates noise from the histogram.

`verbose`

  Whether to output detailed information about recognised classes.

### Return Values

### Examples

Example #1 Imagick::segmentImage()

`<?php
function segmentImage($imagePath, $colorSpace, $clusterThreshold, $smoothThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->segmentImage($colorSpace, $clusterThreshold, $smoothThreshold);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
segmentImage($imagePath, \Imagick::COLORSPACE_RGB, 5, 5);
?>`

# Imagick::selectiveBlurImage

(PECL imagick 3 >= 3.3.0)

Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold

### Description

public Imagick::selectiveBlurImage(
float `$radius`,
float `$sigma`,
float `$threshold`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Selectively blur an image within a contrast threshold. It is similar to the unsharpen mask that sharpens everything with contrast above a certain threshold.

### Parameters

`radius`

`sigma`

`threshold`

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::selectiveBlurImage()

`<?php
function selectiveBlurImage($imagePath, $radius, $sigma, $threshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->selectiveBlurImage($radius, $sigma, $threshold, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::separateImageChannel

(PECL imagick 2, PECL imagick 3)

Imagick::separateImageChannel — Separates a channel from the image

### Description

public Imagick::separateImageChannel(int `$channel`): bool

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

### Parameters

`channel`

  Which 'channel' to return. For colorspaces other than RGB, you can still use the CHANNEL_RED, CHANNEL_GREEN, CHANNEL_BLUE constants to indicate the 1st, 2nd and 3rd channels.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::separateImageChannel()

`<?php
function separateImageChannel($imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->separateimagechannel($channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
separateImageChannel($imagePath, \Imagick::CHANNEL_GREEN);
?>`

# Imagick::sepiaToneImage

(PECL imagick 2, PECL imagick 3)

Imagick::sepiaToneImage — Sepia tones an image

### Description

public Imagick::sepiaToneImage(float `$threshold`): bool

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the sepia toning. A threshold of 80 is a good starting point for a reasonable tone.

### Parameters

`threshold`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::sepiaToneImage()

`<?php
function sepiaToneImage($imagePath, $sepia) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sepiaToneImage($sepia);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::setBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::setBackgroundColor — Sets the object's default background color

### Description

public Imagick::setBackgroundColor(mixed `$background`): bool

Sets the object's default background color.

### Parameters

`background`

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

# Imagick::setColorspace

(PECL imagick 3)

Imagick::setColorspace — Set colorspace

### Description

public Imagick::setColorspace(int `$COLORSPACE`): bool

Sets the global colorspace value for the object. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

### Parameters

`COLORSPACE`

  One of the COLORSPACE constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setCompression

(PECL imagick 2, PECL imagick 3)

Imagick::setCompression — Sets the object's default compression type

### Description

public Imagick::setCompression(int `$compression`): bool

Sets the object's default compression type

### Parameters

`compression`

  The compression type. See the Imagick::COMPRESSION_* constants.

### Return Values

Returns `true` on success.

# Imagick::setCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::setCompressionQuality — Sets the object's default compression quality

### Description

public Imagick::setCompressionQuality(int `$quality`): bool

Sets the object's default compression quality.

Caution

This method only works for new images e.g. those created through Imagick::newPseudoImage. For existing images you should use Imagick::setImageCompressionQuality().

### Parameters

`quality`

  An int between 1 and 100, 1 = high compression, 100 low compression.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::setCompressionQuality()

`<?php
function setCompressionQuality($imagePath, $quality) {
$backgroundImagick = new \Imagick(realpath($imagePath));
$imagick = new \Imagick();
$imagick->setCompressionQuality($quality);
$imagick->newPseudoImage(
$backgroundImagick->getImageWidth(),
$backgroundImagick->getImageHeight(),
'canvas:white'
);
$imagick->compositeImage(
$backgroundImagick,
\Imagick::COMPOSITE_ATOP,
0,
0
);
$imagick->setFormat("jpg");
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::setFilename

(PECL imagick 2, PECL imagick 3)

Imagick::setFilename — Sets the filename before you read or write the image

### Description

public Imagick::setFilename(string `$filename`): bool

Sets the filename before you read or write an image file.

### Parameters

`filename`

### Return Values

Returns `true` on success.

# Imagick::setFirstIterator

(PECL imagick 2, PECL imagick 3)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

### Description

public Imagick::setFirstIterator(): bool

Sets the Imagick iterator to the first image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::setFont

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setFont — Sets font

### Description

public Imagick::setFont(string `$font`): bool

Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick configuration or a file by the name of `font` must exist. This method should not be confused with ImagickDraw::setFont() which sets the font for a specific ImagickDraw object. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

### Parameters

`font`

  Font name or a filename

### Return Values

Returns `true` on success.

### Examples

Example #1 A Imagick::setFont() example

Example of using Imagick::setFont

`<?php
/* Create new imagick object */
$im = new Imagick();
/* Set the font for the object */
$im->setFont("example.ttf");
/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");
/* Do something with the image */
?>`

### See Also

- Imagick::getFont() - Gets font
- ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
- ImagickDraw::getFont() - Returns the font

# Imagick::setFormat

(PECL imagick 2, PECL imagick 3)

Imagick::setFormat — Sets the format of the Imagick object

### Description

public Imagick::setFormat(string `$format`): bool

Sets the format of the Imagick object.

### Parameters

`format`

### Return Values

Returns `true` on success.

# Imagick::setGravity

(PECL imagick 2 >= 2.2.0, PECL imagick 3)

Imagick::setGravity — Sets the gravity

### Description

public Imagick::setGravity(int `$gravity`): bool

Sets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

### Parameters

`gravity`

  The gravity property. Refer to the list of gravity constants.

### Return Values

No value is returned.

# Imagick::setImage

(PECL imagick 2, PECL imagick 3)

Imagick::setImage — Replaces image in the object

### Description

public Imagick::setImage(Imagick `$replace`): bool

Replaces the current image sequence with the image from replace object.

### Parameters

`replace`

  The replace Imagick object

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 A Imagick::setImage() example

An example of using Imagick::setImage()

`<?php
/* Create the objects */
$image = new Imagick('source.jpg');
$replace = new Imagick('replace.jpg');
/* source.jpg is replaced with replace.jpg */
$image->setImage($replace);
/* output the image */
header('Content-type: image/jpeg');
echo $image;
?>`

# Imagick::setImageAlphaChannel

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setImageAlphaChannel — Sets image alpha channel

### Description

public Imagick::setImageAlphaChannel(int `$mode`): bool

Activate or deactivate image alpha channel. The `mode` is one of the `Imagick::ALPHACHANNEL_*` constants. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

### Parameters

`mode`

  One of the `Imagick::ALPHACHANNEL_*` constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### See Also

- Imagick::setImageMatte() - Sets the image matte channel
- Imagick Alpha Channel Constants

# Imagick::setImageArtifact

(PECL imagick 3)

Imagick::setImageArtifact — Set image artifact

### Description

public Imagick::setImageArtifact(string `$artifact`, string `$value`): bool

Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

### Parameters

`artifact`

  The name of the artifact

`value`

  The value of the artifact

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::setImageArtifact()

`<?php
function setImageArtifact() {
$src1 = new \Imagick(realpath("./images/artifact/source1.png"));
$src2 = new \Imagick(realpath("./images/artifact/source2.png"));
$src2->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src2->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);
$src1->setImageFormat('png');
header("Content-Type: image/png");
echo $src1->getImagesBlob();
}
?>`

### See Also

- Imagick::getImageArtifact() - Get image artifact
- Imagick::deleteImageArtifact() - Delete image artifact

# Imagick::setImageAttribute

(PECL imagick 2, PECL imagick 3)

Imagick::setImageAttribute — Sets an image attribute

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageAttribute(string `$key`, string `$value`): bool

Sets an image attribute.

### Parameters

`key`

`value`

### Return Values

Returns `true` on success.

# Imagick::setImageBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBackgroundColor — Sets the image background color

### Description

public Imagick::setImageBackgroundColor(mixed `$background`): bool

Sets the image background color.

### Parameters

`background`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

# Imagick::setImageBias

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageBias(float `$bias`): bool

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

### Parameters

`bias`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::setImageBias()

`<?php
//requires ImageMagick version 6.9.0-1 to have an effect on convolveImage
function setImageBias($bias) {
$imagick = new \Imagick(realpath("images/stack.jpg"));
$xKernel = array(
-0.70, 0, 0.70,
-0.70, 0, 0.70,
-0.70, 0, 0.70
);
$imagick->setImageBias($bias * \Imagick::getQuantum());
$imagick->convolveImage($xKernel, \Imagick::CHANNEL_ALL);
$imagick->setImageFormat('png');
header('Content-type: image/png');
echo $imagick->getImageBlob();
}
?>`

# Imagick::setImageBiasQuantum

(PECL imagick 3 >= 3.3.0)

Imagick::setImageBiasQuantum — Sets the image bias

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageBiasQuantum(float `$bias`): void

Sets the image bias. Bias should be scaled with `0` (no adjustment) to `1` (quantum value).

### Parameters

`bias`

### Return Values

# Imagick::setImageBluePrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

### Description

public Imagick::setImageBluePrimary(float `$x`, float `$y`): bool

Sets the image chromaticity blue primary point.

### Parameters

`x`

`y`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageBorderColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBorderColor — Sets the image border color

### Description

public Imagick::setImageBorderColor(mixed `$border`): bool

Sets the image border color.

### Parameters

`border`

  The border color

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

# Imagick::setImageChannelDepth

(PECL imagick 2, PECL imagick 3)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

### Description

public Imagick::setImageChannelDepth(int `$channel`, int `$depth`): bool

Sets the depth of a particular image channel.

### Parameters

`channel`

`depth`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageClipMask

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::setImageClipMask — Sets image clip mask

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageClipMask(Imagick `$clip_mask`): bool

Sets image clip mask from another Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`clip_mask`

  The Imagick object containing the clip mask

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::setImageClipMask()

`<?php
function setImageClipMask($imagePath) {
$imagick = new \Imagick();
$imagick->readImage(realpath($imagePath));
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();
$clipMask = new \Imagick();
$clipMask->newPseudoImage(
$width,
$height,
"canvas:transparent"
);
$draw = new \ImagickDraw();
$draw->setFillColor('white');
$draw->circle(
$width / 2,
$height / 2,
($width / 2) + ($width / 4),
$height / 2
);
$clipMask->drawImage($draw);
$imagick->setImageClipMask($clipMask);
$imagick->negateImage(false);
$imagick->setFormat("png");
header("Content-Type: image/png");
echo $imagick->getImagesBlob();
}
?>`

# Imagick::setImageColormapColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

### Description

public Imagick::setImageColormapColor(int `$index`, ImagickPixel `$color`): bool

Sets the color of the specified colormap index.

### Parameters

`index`

`color`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageColorspace

(PECL imagick 2, PECL imagick 3)

Imagick::setImageColorspace — Sets the image colorspace

### Description

public Imagick::setImageColorspace(int `$colorspace`): bool

Sets the image colorspace. This method should be used when creating new images. To change the colorspace of an existing image, you should use Imagick::transformImageColorspace().

### Parameters

`colorspace`

  One of the COLORSPACE constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageCompose

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompose — Sets the image composite operator

### Description

public Imagick::setImageCompose(int `$compose`): bool

Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method.

### Parameters

`compose`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageCompression

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompression — Sets the image compression

### Description

public Imagick::setImageCompression(int `$compression`): bool

### Parameters

`compression`

  One of the `COMPRESSION` constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompressionQuality — Sets the image compression quality

### Description

public Imagick::setImageCompressionQuality(int `$quality`): bool

Sets the image compression quality.

### Parameters

`quality`

  The image compression quality as an integer

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::setImageCompressionQuality()

`<?php
function setImageCompressionQuality($imagePath, $quality) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageCompressionQuality($quality);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::setImageDelay

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDelay — Sets the image delay

### Description

public Imagick::setImageDelay(int `$delay`): bool

Sets the image delay. For an animated image this is the amount of time that this frame of the image should be displayed for, before displaying the next frame.

The delay can be set individually for each frame in an image.

### Parameters

`delay`

  The amount of time expressed in 'ticks' that the image should be displayed for. For animated GIFs there are 100 ticks per second, so a value of 20 would be 20/100 of a second aka 1/5th of a second.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Modify animated Gif with Imagick::setImageDelay()

`<?php
// Modify an animated Gif so that it's frames are played at a variable speed,
// varying between being shown for 50ms down to 0ms, which will cause the frame
// to be skipped in most browsers.
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();
$frameCount = 0;
foreach ($imagick as $frame) {
$imagick->setImageDelay((($frameCount % 11) * 5));
$frameCount++;
}
$imagick = $imagick->deconstructImages();
$imagick->writeImages("/path/to/save/output.gif", true);
?>`

# Imagick::setImageDepth

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDepth — Sets the image depth

### Description

public Imagick::setImageDepth(int `$depth`): bool

Sets the image depth.

### Parameters

`depth`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageDispose

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDispose — Sets the image disposal method

### Description

public Imagick::setImageDispose(int `$dispose`): bool

Sets the image disposal method.

### Parameters

`dispose`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageExtent

(PECL imagick 2, PECL imagick 3)

Imagick::setImageExtent — Sets the image size

### Description

public Imagick::setImageExtent(int `$columns`, int `$rows`): bool

Sets the image size (i.e. columns & rows).

### Parameters

`columns`

`rows`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageFilename

(PECL imagick 2, PECL imagick 3)

Imagick::setImageFilename — Sets the filename of a particular image

### Description

public Imagick::setImageFilename(string `$filename`): bool

Sets the filename of a particular image in a sequence.

### Parameters

`filename`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageFormat

(PECL imagick 2, PECL imagick 3)

Imagick::setImageFormat — Sets the format of a particular image

### Description

public Imagick::setImageFormat(string `$format`): bool

Sets the format of a particular image in a sequence.

### Parameters

`format`

  String presentation of the image format. Format support depends on the ImageMagick installation.

### Return Values

Returns `true` on success.

# Imagick::setImageGamma

(PECL imagick 2, PECL imagick 3)

Imagick::setImageGamma — Sets the image gamma

### Description

public Imagick::setImageGamma(float `$gamma`): bool

Sets the image gamma.

### Parameters

`gamma`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageGravity

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::setImageGravity — Sets the image gravity

### Description

public Imagick::setImageGravity(int `$gravity`): bool

Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

### Parameters

`gravity`

  The gravity property. Refer to the list of gravity constants.

### Return Values

No value is returned.

# Imagick::setImageGreenPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

### Description

public Imagick::setImageGreenPrimary(float `$x`, float `$y`): bool

Sets the image chromaticity green primary point.

### Parameters

`x`

`y`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageIndex

(PECL imagick 2, PECL imagick 3)

Imagick::setImageIndex — Set the iterator position

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageIndex(int `$index`): bool

Set the iterator to the position in the image list specified with the index parameter.

This method has been deprecated. See Imagick::setIteratorIndex().

### Parameters

`index`

  The position to set the iterator to

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::setImageInterlaceScheme — Sets the image compression

### Description

public Imagick::setImageInterlaceScheme(int `$interlace_scheme`): bool

Sets the image compression.

### Parameters

`interlace_scheme`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageInterpolateMethod

(PECL imagick 2, PECL imagick 3)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

### Description

public Imagick::setImageInterpolateMethod(int `$method`): bool

Sets the image interpolate pixel method.

### Parameters

`method`

  The method is one of the `Imagick::INTERPOLATE_*` constants

### Return Values

Returns `true` on success.

# Imagick::setImageIterations

(PECL imagick 2, PECL imagick 3)

Imagick::setImageIterations — Sets the image iterations

### Description

public Imagick::setImageIterations(int `$iterations`): bool

Sets the number of iterations an animated image is repeated.

### Parameters

`iterations`

  The number of iterations the image should loop over. Set to '0' to loop continuously.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Basic Imagick::setImageIterations() usage

`<?php
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();
$imagick->setImageIterations(1);
$imagick = $imagick->deconstructImages();
$imagick->writeImages('/path/to/save/OnceOnly.gif', true);
?>`

# Imagick::setImageMatte

(PECL imagick 2, PECL imagick 3)

Imagick::setImageMatte — Sets the image matte channel

### Description

public Imagick::setImageMatte(bool `$matte`): bool

Sets the image matte channel. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`matte`

  True activates the matte channel and false disables it.

### Return Values

Returns `true` on success.

# Imagick::setImageMatteColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageMatteColor — Sets the image matte color

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageMatteColor(mixed `$matte`): bool

Sets the image matte color.

### Parameters

`matte`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

# Imagick::setImageOpacity

(PECL imagick 2, PECL imagick 3)

Imagick::setImageOpacity — Sets the image opacity level

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::setImageOpacity(float `$opacity`): bool

Sets the image to the specified opacity level. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer. This method operates on all channels, which means that for example opacity value of 0.5 will set all transparent areas to partially opaque. To add transparency to areas that are not already transparent use Imagick::evaluateImage()

### Parameters

`opacity`

  The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

### Return Values

Returns `true` on success.

### Examples

Example #1 A Imagick::setImageOpacity() example

An example of using Imagick::setImageOpacity()

`<?php
/* Create the object */
$image = new Imagick('source.png');
/* Set the opacity */
$image->setImageOpacity(0.7);
/* output the image */
header('Content-type: image/png');
echo $image;
?>`

# Imagick::setImageOrientation

(PECL imagick 2, PECL imagick 3)

Imagick::setImageOrientation — Sets the image orientation

### Description

public Imagick::setImageOrientation(int `$orientation`): bool

Sets the image orientation.

### Parameters

`orientation`

  One of the orientation constants

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::setImageOrientation()

`<?php
//Doesn't appear to do anything
function setImageOrientation($imagePath, $orientationType) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageOrientation($orientationType);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::setImagePage

(PECL imagick 2, PECL imagick 3)

Imagick::setImagePage — Sets the page geometry of the image

### Description

public Imagick::setImagePage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Sets the page geometry of the image.

### Parameters

`width`

`height`

`x`

`y`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::setImageProfile — Adds a named profile to the Imagick object

### Description

public Imagick::setImageProfile(string `$name`, string `$profile`): bool

Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.

### Parameters

`name`

`profile`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageProperty

(PECL imagick 2, PECL imagick 3)

Imagick::setImageProperty — Sets an image property

### Description

public Imagick::setImageProperty(string `$name`, string `$value`): bool

Sets a named property to the image. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

### Parameters

`name`

`value`

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::setImageProperty():

Setting and getting image properties

`<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>`

### See Also

- Imagick::getImageProperty() - Returns the named image property

# Imagick::setImageRedPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

### Description

public Imagick::setImageRedPrimary(float `$x`, float `$y`): bool

Sets the image chromaticity red primary point.

### Parameters

`x`

`y`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageRenderingIntent

(PECL imagick 2, PECL imagick 3)

Imagick::setImageRenderingIntent — Sets the image rendering intent

### Description

public Imagick::setImageRenderingIntent(int `$rendering_intent`): bool

Sets the image rendering intent.

### Parameters

`rendering_intent`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageResolution

(PECL imagick 2, PECL imagick 3)

Imagick::setImageResolution — Sets the image resolution

### Description

public Imagick::setImageResolution(float `$x_resolution`, float `$y_resolution`): bool

Sets the image resolution.

### Parameters

`x_resolution`

`y_resolution`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::setImageResolution()

`<?php
function setImageResolution($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageResolution(50, 50);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::setImageScene

(PECL imagick 2, PECL imagick 3)

Imagick::setImageScene — Sets the image scene

### Description

public Imagick::setImageScene(int `$scene`): bool

Sets the image scene.

### Parameters

`scene`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setImageTicksPerSecond

(PECL imagick 2, PECL imagick 3)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

### Description

public Imagick::setImageTicksPerSecond(int `$ticks_per_second`): bool

Adjust the amount of time that a frame of an animated image is displayed for.

> Note:

> For animated GIFs, this function does not change the number of 'image ticks' per second, which is always defined as 100. Instead it adjusts the amount of time that the frame is displayed for to simulate the change in 'ticks per second'.

> For example, for an animated GIF where each frame is displayed for 20 ticks (1/5 of a second) when this method is called on each frame of that image with an argument of `50` the frames are adjusted to be displayed for 40 ticks (2/5 of a second) and the animation will play at half the original speed.

### Parameters

`ticks_per_second`

  The duration for which an image should be displayed expressed in ticks per second.

### Return Values

Returns `true` on success.

### Examples

Example #1 Modify animated Gif with Imagick::setImageTicksPerSecond()

`<?php
// Modify an animated gif so the first half of the gif is played at half the
// speed it currently is, and the second half to be played at double the speed
// it currently is
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();
$totalFrames = $imagick->getNumberImages();
$frameCount = 0;
foreach ($imagick as $frame) {
$imagick->setImageTicksPerSecond(50);
if ($frameCount < ($totalFrames / 2)) {
// Modify the frame to be displayed for twice as long as it currently is
$imagick->setImageTicksPerSecond(50);
} else {
// Modify the frame to be displayed for half as long as it currently is
$imagick->setImageTicksPerSecond(200);
}
$frameCount++;
}
$imagick = $imagick->deconstructImages();
$imagick->writeImages("/path/to/save/output.gif", true);
?>`

# Imagick::setImageType

(PECL imagick 2, PECL imagick 3)

Imagick::setImageType — Sets the image type

### Description

public Imagick::setImageType(int `$image_type`): bool

Sets the image type.

### Parameters

`image_type`

### Return Values

Returns `true` on success.

# Imagick::setImageUnits

(PECL imagick 2, PECL imagick 3)

Imagick::setImageUnits — Sets the image units of resolution

### Description

public Imagick::setImageUnits(int `$units`): bool

Sets the image units of resolution.

### Parameters

`units`

### Return Values

Returns `true` on success.

# Imagick::setImageVirtualPixelMethod

(PECL imagick 2, PECL imagick 3)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

### Description

public Imagick::setImageVirtualPixelMethod(int `$method`): bool

Sets the image virtual pixel method.

### Parameters

`method`

### Return Values

Returns `true` on success.

# Imagick::setImageWhitePoint

(PECL imagick 2, PECL imagick 3)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

### Description

public Imagick::setImageWhitePoint(float `$x`, float `$y`): bool

Sets the image chromaticity white point.

### Parameters

`x`

`y`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::setInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::setInterlaceScheme — Sets the image compression

### Description

public Imagick::setInterlaceScheme(int `$interlace_scheme`): bool

Sets the image compression.

### Parameters

`interlace_scheme`

### Return Values

Returns `true` on success.

# Imagick::setIteratorIndex

(PECL imagick 2, PECL imagick 3)

Imagick::setIteratorIndex — Set the iterator position

### Description

public Imagick::setIteratorIndex(int `$index`): bool

Set the iterator to the position in the image list specified with the index parameter. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`index`

  The position to set the iterator to

### Return Values

Returns `true` on success.

### Examples

Example #1 Using Imagick::setIteratorIndex():

Create images, set and get the iterator index

`<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));
$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>`

### See Also

- Imagick::getIteratorIndex() - Gets the index of the current active image
- Imagick::getImageIndex() - Gets the index of the current active image
- Imagick::setImageIndex() - Set the iterator position

# Imagick::setLastIterator

(PECL imagick 2 >= 2.0.1, PECL imagick 3)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

### Description

public Imagick::setLastIterator(): bool

Sets the Imagick iterator to the last image.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::setOption

(PECL imagick 2, PECL imagick 3)

Imagick::setOption — Set an option

### Description

public Imagick::setOption(string `$key`, string `$value`): bool

Associates one or more options with the wand.

### Parameters

`key`

`value`

### Return Values

Returns `true` on success.

### Examples

Example #1 Attempt to reach '$extent' sizeImagick::setOption()

`<?php
function renderJPG($extent) {
$imagePath = $this->control->getImagePath();
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('jpg');
$imagick->setOption('jpeg:extent', $extent);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

Example #2 Imagick::setOption()

`<?php
function renderPNG($imagePath, $format) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('png');
$imagick->setOption('png:format', $format);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
//Save as 64bit PNG.
renderPNG($imagePath, 'png64');
?>`

Example #3 Imagick::setOption()

`<?php
function renderCustomBitDepthPNG() {
$imagePath = $this->control->getImagePath();
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('png');
$imagick->setOption('png:bit-depth', '16');
$imagick->setOption('png:color-type', 6);
header("Content-Type: image/png");
$crash = true;
if ($crash) {
echo $imagick->getImageBlob();
}
else {
$tempFilename = tempnam('./', 'imagick');
$imagick->writeimage(realpath($tempFilename));
echo file_get_contents($tempFilename);
}
}
?>`

# Imagick::setPage

(PECL imagick 2, PECL imagick 3)

Imagick::setPage — Sets the page geometry of the Imagick object

### Description

public Imagick::setPage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Sets the page geometry of the Imagick object.

### Parameters

`width`

`height`

`x`

`y`

### Return Values

Returns `true` on success.

# Imagick::setPointSize

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setPointSize — Sets point size

### Description

public Imagick::setPointSize(float `$point_size`): bool

Sets object's point size property. This method can be used for example to set font size for caption: pseudo-format. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

### Parameters

`point_size`

  Point size

### Return Values

Returns `true` on success.

### Examples

Example #1 A Imagick::setPointSize() example

Example of using Imagick::setPointSize

`<?php
/* Create new imagick object */
$im = new Imagick();
/* Set the font for the object */
$im->setFont("example.ttf");
/* Set the point size */
$im->setPointSize(12);
/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");
/* Do something with the image */
?>`

### See Also

- Imagick::getPointSize() - Gets point size

# Imagick::setProgressMonitor

(PECL imagick 3 >= 3.3.0)

Imagick::setProgressMonitor — Set a callback to be called during processing

### Description

public Imagick::setProgressMonitor(callable `$callback`): bool

Set a callback that will be called during the processing of the Imagick image.

### Parameters

`callback`

  The progress function to call. It should return true if image processing should continue, or false if it should be cancelled. The offset parameter indicates the progress and the span parameter indicates the total amount of work needed to be done.

  callback ( mixed `$offset` , mixed `$span` ): bool
  Caution

  The values passed to the callback function are not consistent. In particular the span parameter can increase during image processing. Because of this calculating the percentage complete of an image operation is not trivial.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::setProgressMonitor()

`<?php
$abortReason = null;
try {
$imagick = new \Imagick(realpath($this->control->getImagePath()));
$startTime = time();
$callback = function ($offset, $span) use ($startTime, &$abortReason) {
if (((100 * $offset) / $span) > 20) {
$abortReason = "Processing reached 20%";
return false;
}
$nowTime = time();
if ($nowTime - $startTime > 5) {
$abortReason = "Image processing took more than 5 seconds";
return false;
}
if (($offset % 5) == 0) {
echo "Progress: $offset / $span <br/>";
}
return true;
};
$imagick->setProgressMonitor($callback);
$imagick->waveImage(2, 15);
echo "Data len is: ".strlen($imagick->getImageBlob());
}
catch(\ImagickException $e) {
if ($abortReason != null) {
echo "Image processing was aborted: ".$abortReason."<br/>";
}
else {
echo "ImagickException caught: ".$e->getMessage()." Exception type is ".get_class($e);
}
}
?>`

# Imagick::setRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::setRegistry — Sets the ImageMagick registry entry named key to value

### Description

public static Imagick::setRegistry(string `$key`, string `$value`): bool

Sets the ImageMagick registry entry named key to value. This is most useful for setting "temporary-path" which controls where ImageMagick creates temporary images e.g. while processing PDFs.

### Parameters

`key`

`value`

### Return Values

Returns `true` on success.

# Imagick::setResolution

(PECL imagick 2, PECL imagick 3)

Imagick::setResolution — Sets the image resolution

### Description

public Imagick::setResolution(float `$x_resolution`, float `$y_resolution`): bool

Sets the image resolution.

### Parameters

`x_resolution`

  The horizontal resolution.

`y_resolution`

  The vertical resolution.

### Return Values

Returns `true` on success.

### Notes

Imagick::setResolution() must be called before loading or creating an image.

### See Also

- Imagick::setImageResolution() - Sets the image resolution
- Imagick::getImageResolution() - Gets the image X and Y resolution

# Imagick::setResourceLimit

(PECL imagick 2, PECL imagick 3)

Imagick::setResourceLimit — Sets the limit for a particular resource

### Description

public static Imagick::setResourceLimit(int `$type`, int `$limit`): bool

This method is used to modify the resource limits of the underlying ImageMagick library.

### Parameters

`type`

  Refer to the list of resourcetype constants.

`limit`

  One of the resourcetype constants. The unit depends on the type of the resource being limited.

### Return Values

Returns `true` on success.

### See Also

- Imagick::getResourceLimit() - Returns the specified resource limit

# Imagick::setSamplingFactors

(PECL imagick 2, PECL imagick 3)

Imagick::setSamplingFactors — Sets the image sampling factors

### Description

public Imagick::setSamplingFactors(array `$factors`): bool

Sets the image sampling factors.

### Parameters

`factors`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::setSamplingFactors()

`<?php
function setSamplingFactors($imagePath) {
$imagePath = "../imagick/images/FineDetail.png";
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('jpg');
$imagick->setSamplingFactors(array('2x2', '1x1', '1x1'));
$compressed = $imagick->getImageBlob();
$reopen = new \Imagick();
$reopen->readImageBlob($compressed);
$reopen->resizeImage(
$reopen->getImageWidth() * 4,
$reopen->getImageHeight() * 4,
\Imagick::FILTER_POINT,
1
);
header("Content-Type: image/jpg");
echo $reopen->getImageBlob();
}
?>`

# Imagick::setSize

(PECL imagick 2, PECL imagick 3)

Imagick::setSize — Sets the size of the Imagick object

### Description

public Imagick::setSize(int `$columns`, int `$rows`): bool

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

### Parameters

`columns`

`rows`

### Return Values

Returns `true` on success.

# Imagick::setSizeOffset

(PECL imagick 2, PECL imagick 3)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

### Description

public Imagick::setSizeOffset(int `$columns`, int `$rows`, int `$offset`): bool

Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`columns`

  The width in pixels.

`rows`

  The height in pixels.

`offset`

  The image offset.

### Return Values

Returns `true` on success.

# Imagick::setType

(PECL imagick 2, PECL imagick 3)

Imagick::setType — Sets the image type attribute

### Description

public Imagick::setType(int `$image_type`): bool

Sets the image type attribute.

### Parameters

`image_type`

### Return Values

Returns `true` on success.

# Imagick::shadeImage

(PECL imagick 2, PECL imagick 3)

Imagick::shadeImage — Creates a 3D effect

### Description

public Imagick::shadeImage(bool `$gray`, float `$azimuth`, float `$elevation`): bool

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`gray`

  A value other than zero shades the intensity of each pixel.

`azimuth`

  Defines the light source direction.

`elevation`

  Defines the light source direction.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on failure.

### Examples

Example #1 Imagick::shadeImage()

`<?php
function shadeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shadeImage(true, 45, 20);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::shadowImage

(PECL imagick 2, PECL imagick 3)

Imagick::shadowImage — Simulates an image shadow

### Description

public Imagick::shadowImage(
float `$opacity`,
float `$sigma`,
int `$x`,
int `$y`
): bool

Simulates an image shadow.

### Parameters

`opacity`

`sigma`

`x`

`y`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::shadowImage()

`<?php
function shadowImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shadowImage(0.4, 10, 50, 5);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::sharpenImage

(PECL imagick 2, PECL imagick 3)

Imagick::sharpenImage — Sharpens an image

### Description

public Imagick::sharpenImage(float `$radius`, float `$sigma`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and Imagick::sharpenImage() selects a suitable radius for you.

### Parameters

`radius`

`sigma`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::sharpenImage()

`<?php
function sharpenImage($imagePath, $radius, $sigma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sharpenimage($radius, $sigma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::shaveImage

(PECL imagick 2, PECL imagick 3)

Imagick::shaveImage — Shaves pixels from the image edges

### Description

public Imagick::shaveImage(int `$columns`, int `$rows`): bool

Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.

### Parameters

`columns`

`rows`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::shaveImage()

`<?php
function shaveImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shaveImage(100, 50);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::shearImage

(PECL imagick 2, PECL imagick 3)

Imagick::shearImage — Creating a parallelogram

### Description

public Imagick::shearImage(mixed `$background`, float `$x_shear`, float `$y_shear`): bool

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

### Parameters

`background`

  The background color

`x_shear`

  The number of degrees to shear on the x axis

`y_shear`

  The number of degrees to shear on the y axis

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::shearImage()

`<?php
function shearImage($imagePath, $color, $shearX, $shearY) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shearimage($color, $shearX, $shearY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::sigmoidalContrastImage

(PECL imagick 2, PECL imagick 3)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

### Description

public Imagick::sigmoidalContrastImage(
bool `$sharpen`,
float `$alpha`,
float `$beta`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to `true` to increase the image contrast otherwise the contrast is reduced.

See also » ImageMagick v6 Examples - Image Transformations — Sigmoidal Non-linearity Contrast

### Parameters

`sharpen`

  If true increase the contrast, if false decrease the contrast.

`alpha`

  The amount of contrast to apply. 1 is very little, 5 is a significant amount, 20 is extreme.

`beta`

  Where the midpoint of the gradient will be. This value should be in the range 0 to 1 - mutliplied by the quantum value for ImageMagick.

`channel`

  Which color channels the contrast will be applied to.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Create a gradient image using Imagick::sigmoidalContrastImage() suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint

`<?php
function generateBlendImage($width, $height, $contrast = 10, $midpoint = 0.5) {
$imagick = new Imagick();
$imagick->newPseudoImage($width, $height, 'gradient:black-white');
$quanta = $imagick->getQuantumRange();
$imagick->sigmoidalContrastImage(true, $contrast, $midpoint * $quanta["quantumRangeLong"]);
return $imagick;
}
?>`

# Imagick::sketchImage

(PECL imagick 2, PECL imagick 3)

Imagick::sketchImage — Simulates a pencil sketch

### Description

public Imagick::sketchImage(float `$radius`, float `$sigma`, float `$angle`): bool

Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`radius`

  The radius of the Gaussian, in pixels, not counting the center pixel

`sigma`

  The standard deviation of the Gaussian, in pixels.

`angle`

  Apply the effect along this angle.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::sketchImage()

`<?php
function sketchImage($imagePath, $radius, $sigma, $angle) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sketchimage($radius, $sigma, $angle);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::smushImages

(PECL imagick 3 >= 3.3.0)

Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them

### Description

public Imagick::smushImages(bool `$stack`, int `$offset`): Imagick

Takes all images from the current image pointer to the end of the image list and smushs them to each other top-to-bottom if the stack parameter is true, otherwise left-to-right.

### Parameters

`stack`

`offset`

### Return Values

The new smushed image.

### Examples

Example #1 Imagick::smushImages()

`<?php
function smushImages($imagePath, $imagePath2) {
$imagick = new \Imagick(realpath($imagePath));
$imagick2 = new \Imagick(realpath($imagePath2));
$imagick->addimage($imagick2);
$smushed = $imagick->smushImages(false, 50);
$smushed->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $smushed->getImageBlob();
}
?>`

# Imagick::solarizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::solarizeImage — Applies a solarizing effect to the image

### Description

public Imagick::solarizeImage(int `$threshold`): bool

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

### Parameters

`threshold`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::solarizeImage()

`<?php
function solarizeImage($imagePath, $solarizeThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->solarizeImage($solarizeThreshold * \Imagick::getQuantum());
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::sparseColorImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::sparseColorImage — Interpolates colors

### Description

public Imagick::sparseColorImage(int `$SPARSE_METHOD`, array `$arguments`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using `sparse_method`. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

### Parameters

`SPARSE_METHOD`

  Refer to this list of sparse method constants

`arguments`

  An array containing the coordinates. The array is in format `array(1,1, 2,45)`

`channel`

  Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to `Imagick::CHANNEL_DEFAULT`. Refer to this list of channel constants

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

`<?php
function renderImageBarycentric2() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(
400, 400,
$points,
\Imagick::SPARSECOLORMETHOD_BARYCENTRIC
);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

Example #2 SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage()

`<?php
function renderImageBilinear() {
$points = [[0.30, 0.10, 'red'], [0.10, 0.80, 'blue'], [0.70, 0.60, 'lime'], [0.80, 0.20, 'yellow'],];
$imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_BILINEAR);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

Example #3 SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage()

`<?php
function renderImageShepards() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(600, 600, $points, \Imagick::SPARSECOLORMETHOD_SPEPARDS);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

Example #4 SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage()

`<?php
function renderImageVoronoi() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_VORONOI);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

Example #5 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

`<?php
function renderImageBarycentric() {
$points = [
[0, 0, 'skyblue'],
[-1, 1, 'skyblue'],
[1, 1, 'black'],
];
$imagick = createGradientImage(600, 200, $points, \Imagick::SPARSECOLORMETHOD_BARYCENTRIC);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

Example #6 createGradientImage is used by other examples. Imagick::sparseColorImage()

`<?php
function createGradientImage($width, $height, $colorPoints, $sparseMethod, $absolute = false) {
$imagick = new \Imagick();
$imagick->newImage($width, $height, "white");
$imagick->setImageFormat("png");
$barycentricPoints = array();
foreach ($colorPoints as $colorPoint) {
if ($absolute == true) {
$barycentricPoints[] = $colorPoint[0];
$barycentricPoints[] = $colorPoint[1];
}
else {
$barycentricPoints[] = $colorPoint[0] * $width;
$barycentricPoints[] = $colorPoint[1] * $height;
}
if (is_string($colorPoint[2])) {
$imagickPixel = new \ImagickPixel($colorPoint[2]);
}
else if ($colorPoint[2] instanceof \ImagickPixel) {
$imagickPixel = $colorPoint[2];
}
else{
$errorMessage = sprintf(
"Value %s is neither a string nor an ImagickPixel class. Cannot use as a color.",
$colorPoint[2]
);
throw new \InvalidArgumentException(
$errorMessage
);
}
$red = $imagickPixel->getColorValue(\Imagick::COLOR_RED);
$green = $imagickPixel->getColorValue(\Imagick::COLOR_GREEN);
$blue = $imagickPixel->getColorValue(\Imagick::COLOR_BLUE);
$alpha = $imagickPixel->getColorValue(\Imagick::COLOR_ALPHA);
$barycentricPoints[] = $red;
$barycentricPoints[] = $green;
$barycentricPoints[] = $blue;
$barycentricPoints[] = $alpha;
}
$imagick->sparseColorImage($sparseMethod, $barycentricPoints);
return $imagick;
}
?>`

# Imagick::spliceImage

(PECL imagick 2, PECL imagick 3)

Imagick::spliceImage — Splices a solid color into the image

### Description

public Imagick::spliceImage(
int `$width`,
int `$height`,
int `$x`,
int `$y`
): bool

Splices a solid color into the image.

### Parameters

`width`

`height`

`x`

`y`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::spliceImage()

`<?php
function spliceImage($imagePath, $startX, $startY, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->spliceImage($width, $height, $startX, $startY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::spreadImage

(PECL imagick 2, PECL imagick 3)

Imagick::spreadImage — Randomly displaces each pixel in a block

### Description

public Imagick::spreadImage(float `$radius`): bool

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

### Parameters

`radius`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::spreadImage()

`<?php
function spreadImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->spreadImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::statisticImage

(PECL imagick 3 >= 3.3.0)

Imagick::statisticImage — Modifies image using a statistics function

### Description

public Imagick::statisticImage(
int `$type`,
int `$width`,
int `$height`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Replace each pixel with corresponding statistic from the neighborhood of the specified width and height.

### Parameters

`type`

`width`

`height`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::statisticImage()

`<?php
function statisticImage($imagePath, $statisticType, $width, $height, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->statisticImage(
$statisticType,
$width,
$height,
$channel
);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
statisticImage($imagePath, \Imagick::STATISTIC_MEDIAN, 5, 5, \Imagick::CHANNEL_DEFAULT);
?>`

# Imagick::steganoImage

(PECL imagick 2, PECL imagick 3)

Imagick::steganoImage — Hides a digital watermark within the image

### Description

public Imagick::steganoImage(Imagick `$watermark_wand`, int `$offset`): Imagick

Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.

### Parameters

`watermark_wand`

`offset`

### Return Values

Returns `true` on success.

# Imagick::stereoImage

(PECL imagick 2, PECL imagick 3)

Imagick::stereoImage — Composites two images

### Description

public Imagick::stereoImage(Imagick `$offset_wand`): bool

Composites two images and produces a single image that is the composite of a left and right image of a stereo pair.

### Parameters

`offset_wand`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::stripImage

(PECL imagick 2, PECL imagick 3)

Imagick::stripImage — Strips an image of all profiles and comments

### Description

public Imagick::stripImage(): bool

Strips an image of all profiles and comments.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

# Imagick::subImageMatch

(PECL imagick 3 >= 3.3.0)

Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image

### Description

public Imagick::subImageMatch(Imagick `$Imagick`, array `&$offset` = ?, float `&$similarity` = ?): Imagick

Searches for a subimage in the current image and returns a similarity image such that an exact match location is completely white and if none of the pixels match, black, otherwise some gray level in-between. You can also pass in the optional parameters bestMatch and similarity. After calling the function similarity will be set to the 'score' of the similarity between the subimage and the matching position in the larger image, bestMatch will contain an associative array with elements x, y, width, height that describe the matching region.

### Parameters

`Imagick`

`offset`

`similarity`

  A new image that displays the amount of similarity at each pixel.

### Return Values

### Examples

Example #1 Imagick::subImageMatch()

`<?php
function subImageMatch($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick2 = clone $imagick;
$imagick2->cropimage(40, 40, 250, 110);
$imagick2->vignetteimage(0, 1, 3, 3);
$similarity = null;
$bestMatch = null;
$comparison = $imagick->subImageMatch($imagick2, $bestMatch, $similarity);
$comparison->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::swirlImage

(PECL imagick 2, PECL imagick 3)

Imagick::swirlImage — Swirls the pixels about the center of the image

### Description

Imagick::swirlImage(float `$degrees`): bool

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

### Parameters

`degrees`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::swirlImage()

`<?php
function swirlImage($imagePath, $swirl) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->swirlImage($swirl);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::textureImage

(PECL imagick 2, PECL imagick 3)

Imagick::textureImage — Repeatedly tiles the texture image

### Description

Imagick::textureImage(Imagick `$texture_wand`): Imagick

Repeatedly tiles the texture image across and down the image canvas.

### Parameters

`texture_wand`

  Imagick object to use as texture image

### Return Values

Returns a new Imagick object that has the repeated texture applied.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::textureImage()

`<?php
function textureImage($imagePath) {
$image = new \Imagick();
$image->newImage(640, 480, new \ImagickPixel('pink'));
$image->setImageFormat("jpg");
$texture = new \Imagick(realpath($imagePath));
$texture->scaleimage($image->getimagewidth() / 4, $image->getimageheight() / 4);
$image = $image->textureImage($texture);
header("Content-Type: image/jpg");
echo $image;
}
?>`

# Imagick::thresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

### Description

public Imagick::thresholdImage(float `$threshold`, int `$channel` = Imagick::CHANNEL_DEFAULT): bool

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

### Parameters

`threshold`

`channel`

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::thresholdImage()

`<?php
function thresholdimage($imagePath, $threshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->thresholdimage($threshold * \Imagick::getQuantum(), $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::thumbnailImage

(PECL imagick 2, PECL imagick 3)

Imagick::thumbnailImage — Changes the size of an image

### Description

public Imagick::thumbnailImage(
int `$columns`,
int `$rows`,
bool `$bestfit` = `false`,
bool `$fill` = `false`,
bool `$legacy` = `false`
): bool

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small, low cost thumbnail images suited for display on the Web. If `true` is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until they match or are smaller than the parameter given for the side.

> Note: The behavior of the parameter `bestfit` changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If `bestfit` parameter is used both width and height must be given.

### Parameters

`columns`

  Image width

`rows`

  Image height

`bestfit`

  Whether to force maximum values

`fill`

  If the image does not fill the box completely then the box is filled with image's background color.

`legacy`

  Round the smaller dimension down instead to the closest integer.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::thumbnailImage()

`<?php
function thumbnailImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(100, 100, true, true);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::tintImage

(PECL imagick 2, PECL imagick 3)

Imagick::tintImage — Applies a color vector to each pixel in the image

### Description

public Imagick::tintImage(mixed `$tint`, mixed `$opacity`, bool `$legacy` = `false`): bool

Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighing function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))).

### Parameters

`tint`

`opacity`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

### Examples

Example #1 Imagick::tintImage()

`<?php
function tintImage($r, $g, $b, $a) {
$a = $a / 100;
$imagick = new \Imagick();
$imagick->newPseudoImage(400, 400, 'gradient:black-white');
$tint = new \ImagickPixel("rgb($r, $g, $b)");
$opacity = new \ImagickPixel("rgb(128, 128, 128, $a)");
$imagick->tintImage($tint, $opacity);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::__toString

(PECL imagick 2, PECL imagick 3)

Imagick::__toString — Returns the image as a string

### Description

public Imagick::__toString(): string

Returns the current image as string. This will only return a single image; it should not be used for Imagick objects that contain multiple images e.g. an animated GIF or PDF with multiple pages.

### Parameters

This function has no parameters.

### Return Values

Returns the string content on success or an empty string on failure.

### See Also

- Imagick::getImageBlob() - Returns the image sequence as a blob
- Imagick::getImagesBlob() - Returns all image sequences as a blob

# Imagick::transformImage

(PECL imagick 2, PECL imagick 3)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Warning

This function has been DEPRECATED as of Imagick 3.4.4. Relying on this function is highly discouraged.

### Description

public Imagick::transformImage(string `$crop`, string `$geometry`): Imagick

A convenience method for setting crop size and the image geometry from strings. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`crop`

  A crop geometry string. This geometry defines a subregion of the image to crop.

`geometry`

  An image geometry string. This geometry defines the final size of the image.

### Return Values

Returns an Imagick object containing the transformed image.

### Examples

Example #1 Using Imagick::transformImage():

The example creates a 100x100 black image.

`<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$new_image = $image->transformImage("100x100", "100x100");
$new_image->writeImage('test_out.jpg');
?>`

### See Also

- Imagick::cropImage() - Extracts a region of the image
- Imagick::resizeImage() - Scales an image
- Imagick::thumbnailImage() - Changes the size of an image

# Imagick::transformImageColorspace

(PECL imagick 3)

Imagick::transformImageColorspace — Transforms an image to a new colorspace

### Description

public Imagick::transformImageColorspace(int `$colorspace`): bool

Transforms an image to a new colorspace.

### Parameters

`colorspace`

  The colorspace the image should be transformed to, one of the COLORSPACE constants e.g. Imagick::COLORSPACE_CMYK.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::transformImageColorspace() example

Transforms an image to a new colorspace, and then extracts a single channel so that the individual channel values can be viewed.

`<?php
function transformImageColorspace($imagePath, $colorSpace, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transformimagecolorspace($colorSpace);
//channel should be one of the channel constants e.g. \Imagick::CHANNEL_BLUE
$imagick->separateImageChannel($channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::setColorSpace() - Set colorspace

# Imagick::transparentPaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::transparentPaintImage — Paints pixels transparent

### Description

public Imagick::transparentPaintImage(
mixed `$target`,
float `$alpha`,
float `$fuzz`,
bool `$invert`
): bool

Paints pixels matching the target color transparent. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

### Parameters

`target`

  The target color to paint

`alpha`

  The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

`fuzz`

  The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

`invert`

  If `true` paints any pixel that does not match the target color.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::transparentPaintImage()

`<?php
function transparentPaintImage($color, $alpha, $fuzz) {
$imagick = new \Imagick(realpath("images/BlueScreen.jpg"));
//Need to be in a format that supports transparency
$imagick->setimageformat('png');
$imagick->transparentPaintImage(
$color, $alpha, $fuzz * \Imagick::getQuantum(), false
);
//Not required, but helps tidy up left over pixels
$imagick->despeckleimage();
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::transposeImage

(PECL imagick 2, PECL imagick 3)

Imagick::transposeImage — Creates a vertical mirror image

### Description

public Imagick::transposeImage(): bool

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::transposeImage()

`<?php
function transposeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transposeImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::transverseImage() - Creates a horizontal mirror image

# Imagick::transverseImage

(PECL imagick 2, PECL imagick 3)

Imagick::transverseImage — Creates a horizontal mirror image

### Description

public Imagick::transverseImage(): bool

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::transverseImage()

`<?php
function transverseImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transverseImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::transposeImage() - Creates a vertical mirror image

# Imagick::trimImage

(PECL imagick 2, PECL imagick 3)

Imagick::trimImage — Remove edges from the image

### Description

public Imagick::trimImage(float `$fuzz`): bool

Remove edges that are the background color from the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`fuzz`

  By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Using Imagick::trimImage():

Trim an image, then display to the browser.

`<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");
/* Trim the image. */
$im->trimImage(0);
/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>`

### See Also

- Imagick::getQuantumDepth() - Gets the quantum depth
- Imagick::getQuantumRange() - Returns the Imagick quantum range
- imagecropauto() - Crop an image automatically using one of the available modes

# Imagick::uniqueImageColors

(PECL imagick 2,PECL imagick 3)

Imagick::uniqueImageColors — Discards all but one of any pixel color

### Description

public Imagick::uniqueImageColors(): bool

Discards all but one of any pixel color. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::uniqueImageColors()

`<?php
function uniqueImageColors($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
//Reduce the image to 256 colours nicely.
$imagick->quantizeImage(256, \Imagick::COLORSPACE_YIQ, 0, false, false);
$imagick->uniqueImageColors();
$imagick->scaleimage($imagick->getImageWidth(), $imagick->getImageHeight() * 20);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# Imagick::unsharpMaskImage

(PECL imagick 2, PECL imagick 3)

Imagick::unsharpMaskImage — Sharpens an image

### Description

public Imagick::unsharpMaskImage(
float `$radius`,
float `$sigma`,
float `$amount`,
float `$threshold`,
int `$channel` = Imagick::CHANNEL_DEFAULT
): bool

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::UnsharpMaskImage() selects a suitable radius for you.

### Parameters

`radius`

`sigma`

`amount`

`threshold`

`channel`

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 Imagick::unsharpMaskImage()

`<?php
function unsharpMaskImage($imagePath, $radius, $sigma, $amount, $unsharpThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->unsharpMaskImage($radius, $sigma, $amount, $unsharpThreshold);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::valid

(PECL imagick 2, PECL imagick 3)

Imagick::valid — Checks if the current item is valid

### Description

public Imagick::valid(): bool

Checks if the current item is valid.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# Imagick::vignetteImage

(PECL imagick 2, PECL imagick 3)

Imagick::vignetteImage — Adds vignette filter to the image

### Description

public Imagick::vignetteImage(
float `$blackPoint`,
float `$whitePoint`,
int `$x`,
int `$y`
): bool

Softens the edges of the image in vignette style. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`blackPoint`

  The black point.

`whitePoint`

  The white point

`x`

  X offset of the ellipse

`y`

  Y offset of the ellipse

### Return Values

Returns `true` on success.

### Examples

Example #1 Imagick::vignetteImage()

`<?php
function vignetteImage($imagePath, $blackPoint, $whitePoint, $x, $y) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->vignetteImage($blackPoint, $whitePoint, $x, $y);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::waveImage() - Applies wave filter to the image
- Imagick::swirlImage() - Swirls the pixels about the center of the image

# Imagick::waveImage

(PECL imagick 2, PECL imagick 3)

Imagick::waveImage — Applies wave filter to the image

### Description

public Imagick::waveImage(float `$amplitude`, float `$length`): bool

Applies a wave filter to the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

### Parameters

`amplitude`

  The amplitude of the wave.

`length`

  The length of the wave.

### Return Values

Returns `true` on success.

### Errors/Exceptions

Throws ImagickException on error.

### Examples

Example #1 WaveImage can be quite slow Imagick::waveImage()

`<?php
function waveImage($imagePath, $amplitude, $length) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->waveImage($amplitude, $length);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

### See Also

- Imagick::solarizeImage() - Applies a solarizing effect to the image
- Imagick::oilpaintImage() - Simulates an oil painting
- Imagick::embossImage() - Returns a grayscale image with a three-dimensional effect
- Imagick::addNoiseImage() - Adds random noise to the image
- Imagick::swirlImage() - Swirls the pixels about the center of the image

# Imagick::whiteThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

### Description

public Imagick::whiteThresholdImage(mixed `$threshold`): bool

Is like Imagick::ThresholdImage() but force all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

### Parameters

`threshold`

### Return Values

Returns `true` on success.

### Changelog

Version | Description
--- | ---
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

### Examples

Example #1 Imagick::whiteThresholdImage()

`<?php
function whiteThresholdImage($imagePath, $color) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->whiteThresholdImage($color);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# Imagick::writeImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImage — Writes an image to the specified filename

### Description

public Imagick::writeImage(string `$filename` = NULL): bool

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::readImage() or Imagick::setImageFilename().

### Parameters

`filename`

  Filename where to write the image. The extension of the filename defines the type of the file. Format can be forced regardless of file extension using format: prefix, for example "jpg:test.png".

### Return Values

Returns `true` on success.

# Imagick::writeImageFile

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImageFile — Writes an image to a filehandle

### Description

public Imagick::writeImageFile(resource `$filehandle`, string `$format` = ?): bool

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`filehandle`

  Filehandle where to write the image.

`format`

  The image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats().

### Return Values

Returns `true` on success.

### See Also

- Imagick::queryFormats() - Returns formats supported by Imagick

# Imagick::writeImages

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImages — Writes an image or image sequence

### Description

public Imagick::writeImages(string `$filename`, bool `$adjoin`): bool

Writes an image or image sequence.

### Parameters

`filename`

`adjoin`

### Return Values

Returns `true` on success.

# Imagick::writeImagesFile

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImagesFile — Writes frames to a filehandle

### Description

public Imagick::writeImagesFile(resource `$filehandle`, string `$format` = ?): bool

Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

### Parameters

`filehandle`

  Filehandle where to write the images.

`format`

  The image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats().

### Return Values

Returns `true` on success.

### See Also

- Imagick::queryFormats() - Returns formats supported by Imagick

## Table of Contents

- Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
- Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
- Imagick::adaptiveSharpenImage — Adaptively sharpen the image
- Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
- Imagick::addImage — Adds new image to Imagick object image list
- Imagick::addNoiseImage — Adds random noise to the image
- Imagick::affineTransformImage — Transforms an image
- Imagick::animateImages — Animates an image or images
- Imagick::annotateImage — Annotates an image with text
- Imagick::appendImages — Append a set of images
- Imagick::autoLevelImage — Adjusts the levels of a particular image channel
- Imagick::averageImages — Average a set of images
- Imagick::blackThresholdImage — Forces all pixels below the threshold into black
- Imagick::blueShiftImage — Mutes the colors of the image
- Imagick::blurImage — Adds blur filter to image
- Imagick::borderImage — Surrounds the image with a border
- Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image
- Imagick::charcoalImage — Simulates a charcoal drawing
- Imagick::chopImage — Removes a region of an image and trims
- Imagick::clampImage — Restricts the color range from 0 to the quantum depth.
- Imagick::clear — Clears all resources associated to Imagick object
- Imagick::clipImage — Clips along the first path from the 8BIM profile
- Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present
- Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
- Imagick::clone — Makes an exact copy of the Imagick object
- Imagick::clutImage — Replaces colors in the image
- Imagick::coalesceImages — Composites a set of images
- Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
- Imagick::colorizeImage — Blends the fill color with the image
- Imagick::colorMatrixImage — Apply color transformation to an image
- Imagick::combineImages — Combines one or more images into a single image
- Imagick::commentImage — Adds a comment to your image
- Imagick::compareImageChannels — Returns the difference in one or more images
- Imagick::compareImageLayers — Returns the maximum bounding region between images
- Imagick::compareImages — Compares an image to a reconstructed image
- Imagick::compositeImage — Composite one image onto another
- Imagick::__construct — The Imagick constructor
- Imagick::contrastImage — Change the contrast of the image
- Imagick::contrastStretchImage — Enhances the contrast of a color image
- Imagick::convolveImage — Applies a custom convolution kernel to the image
- Imagick::count — Get the number of images
- Imagick::cropImage — Extracts a region of the image
- Imagick::cropThumbnailImage — Creates a crop thumbnail
- Imagick::current — Returns a reference to the current Imagick object
- Imagick::cycleColormapImage — Displaces an image's colormap
- Imagick::decipherImage — Deciphers an image
- Imagick::deconstructImages — Returns certain pixel differences between images
- Imagick::deleteImageArtifact — Delete image artifact
- Imagick::deleteImageProperty — Deletes an image property
- Imagick::deskewImage — Removes skew from the image
- Imagick::despeckleImage — Reduces the speckle noise in an image
- Imagick::destroy — Destroys the Imagick object
- Imagick::displayImage — Displays an image
- Imagick::displayImages — Displays an image or image sequence
- Imagick::distortImage — Distorts an image using various distortion methods
- Imagick::drawImage — Renders the ImagickDraw object on the current image
- Imagick::edgeImage — Enhance edges within the image
- Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
- Imagick::encipherImage — Enciphers an image
- Imagick::enhanceImage — Improves the quality of a noisy image
- Imagick::equalizeImage — Equalizes the image histogram
- Imagick::evaluateImage — Applies an expression to an image
- Imagick::exportImagePixels — Exports raw image pixels
- Imagick::extentImage — Set image size
- Imagick::filter — Applies a custom convolution kernel to the image
- Imagick::flattenImages — Merges a sequence of images
- Imagick::flipImage — Creates a vertical mirror image
- Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
- Imagick::flopImage — Creates a horizontal mirror image
- Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)
- Imagick::frameImage — Adds a simulated three-dimensional border
- Imagick::functionImage — Applies a function on the image
- Imagick::fxImage — Evaluate expression for each pixel in the image
- Imagick::gammaImage — Gamma-corrects an image
- Imagick::gaussianBlurImage — Blurs an image
- Imagick::getColorspace — Gets the colorspace
- Imagick::getCompression — Gets the object compression type
- Imagick::getCompressionQuality — Gets the object compression quality
- Imagick::getCopyright — Returns the ImageMagick API copyright as a string
- Imagick::getFilename — The filename associated with an image sequence
- Imagick::getFont — Gets font
- Imagick::getFormat — Returns the format of the Imagick object
- Imagick::getGravity — Gets the gravity
- Imagick::getHomeURL — Returns the ImageMagick home URL
- Imagick::getImage — Returns a new Imagick object
- Imagick::getImageAlphaChannel — Checks if the image has an alpha channel
- Imagick::getImageArtifact — Get image artifact
- Imagick::getImageAttribute — Returns a named attribute
- Imagick::getImageBackgroundColor — Returns the image background color
- Imagick::getImageBlob — Returns the image sequence as a blob
- Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
- Imagick::getImageBorderColor — Returns the image border color
- Imagick::getImageChannelDepth — Gets the depth for a particular image channel
- Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
- Imagick::getImageChannelDistortions — Gets channel distortions
- Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
- Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
- Imagick::getImageChannelMean — Gets the mean and standard deviation
- Imagick::getImageChannelRange — Gets channel range
- Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
- Imagick::getImageClipMask — Gets image clip mask
- Imagick::getImageColormapColor — Returns the color of the specified colormap index
- Imagick::getImageColors — Gets the number of unique colors in the image
- Imagick::getImageColorspace — Gets the image colorspace
- Imagick::getImageCompose — Returns the composite operator associated with the image
- Imagick::getImageCompression — Gets the current image's compression type
- Imagick::getImageCompressionQuality — Gets the current image's compression quality
- Imagick::getImageDelay — Gets the image delay
- Imagick::getImageDepth — Gets the image depth
- Imagick::getImageDispose — Gets the image disposal method
- Imagick::getImageDistortion — Compares an image to a reconstructed image
- Imagick::getImageExtrema — Gets the extrema for the image
- Imagick::getImageFilename — Returns the filename of a particular image in a sequence
- Imagick::getImageFormat — Returns the format of a particular image in a sequence
- Imagick::getImageGamma — Gets the image gamma
- Imagick::getImageGeometry — Gets the width and height as an associative array
- Imagick::getImageGravity — Gets the image gravity
- Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
- Imagick::getImageHeight — Returns the image height
- Imagick::getImageHistogram — Gets the image histogram
- Imagick::getImageIndex — Gets the index of the current active image
- Imagick::getImageInterlaceScheme — Gets the image interlace scheme
- Imagick::getImageInterpolateMethod — Returns the interpolation method
- Imagick::getImageIterations — Gets the image iterations
- Imagick::getImageLength — Returns the image length in bytes
- Imagick::getImageMatte — Return if the image has a matte channel
- Imagick::getImageMatteColor — Returns the image matte color
- Imagick::getImageMimeType — Returns the image mime-type
- Imagick::getImageOrientation — Gets the image orientation
- Imagick::getImagePage — Returns the page geometry
- Imagick::getImagePixelColor — Returns the color of the specified pixel
- Imagick::getImageProfile — Returns the named image profile
- Imagick::getImageProfiles — Returns the image profiles
- Imagick::getImageProperties — Returns the image properties
- Imagick::getImageProperty — Returns the named image property
- Imagick::getImageRedPrimary — Returns the chromaticity red primary point
- Imagick::getImageRegion — Extracts a region of the image
- Imagick::getImageRenderingIntent — Gets the image rendering intent
- Imagick::getImageResolution — Gets the image X and Y resolution
- Imagick::getImagesBlob — Returns all image sequences as a blob
- Imagick::getImageScene — Gets the image scene
- Imagick::getImageSignature — Generates an SHA-256 message digest
- Imagick::getImageSize — Returns the image length in bytes
- Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
- Imagick::getImageTotalInkDensity — Gets the image total ink density
- Imagick::getImageType — Gets the potential image type
- Imagick::getImageUnits — Gets the image units of resolution
- Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
- Imagick::getImageWhitePoint — Returns the chromaticity white point
- Imagick::getImageWidth — Returns the image width
- Imagick::getInterlaceScheme — Gets the object interlace scheme
- Imagick::getIteratorIndex — Gets the index of the current active image
- Imagick::getNumberImages — Returns the number of images in the object
- Imagick::getOption — Returns a value associated with the specified key
- Imagick::getPackageName — Returns the ImageMagick package name
- Imagick::getPage — Returns the page geometry
- Imagick::getPixelIterator — Returns a MagickPixelIterator
- Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
- Imagick::getPointSize — Gets point size
- Imagick::getQuantum — Returns the ImageMagick quantum range
- Imagick::getQuantumDepth — Gets the quantum depth
- Imagick::getQuantumRange — Returns the Imagick quantum range
- Imagick::getRegistry — Get a StringRegistry entry
- Imagick::getReleaseDate — Returns the ImageMagick release date
- Imagick::getResource — Returns the specified resource's memory usage
- Imagick::getResourceLimit — Returns the specified resource limit
- Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
- Imagick::getSize — Returns the size associated with the Imagick object
- Imagick::getSizeOffset — Returns the size offset
- Imagick::getVersion — Returns the ImageMagick API version
- Imagick::haldClutImage — Replaces colors in the image
- Imagick::hasNextImage — Checks if the object has more images
- Imagick::hasPreviousImage — Checks if the object has a previous image
- Imagick::identifyFormat — Formats a string with image details
- Imagick::identifyImage — Identifies an image and fetches attributes
- Imagick::implodeImage — Creates a new image as a copy
- Imagick::importImagePixels — Imports image pixels
- Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)
- Imagick::labelImage — Adds a label to an image
- Imagick::levelImage — Adjusts the levels of an image
- Imagick::linearStretchImage — Stretches with saturation the image intensity
- Imagick::liquidRescaleImage — Animates an image or images
- Imagick::listRegistry — List all the registry settings
- Imagick::magnifyImage — Scales an image proportionally 2x
- Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image
- Imagick::matteFloodfillImage — Changes the transparency value of a color
- Imagick::medianFilterImage — Applies a digital filter
- Imagick::mergeImageLayers — Merges image layers
- Imagick::minifyImage — Scales an image proportionally to half its size
- Imagick::modulateImage — Control the brightness, saturation, and hue
- Imagick::montageImage — Creates a composite image
- Imagick::morphImages — Method morphs a set of images
- Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.
- Imagick::mosaicImages — Forms a mosaic from images
- Imagick::motionBlurImage — Simulates motion blur
- Imagick::negateImage — Negates the colors in the reference image
- Imagick::newImage — Creates a new image
- Imagick::newPseudoImage — Creates a new image
- Imagick::nextImage — Moves to the next image
- Imagick::normalizeImage — Enhances the contrast of a color image
- Imagick::oilPaintImage — Simulates an oil painting
- Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
- Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
- Imagick::orderedPosterizeImage — Performs an ordered dither
- Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
- Imagick::paintOpaqueImage — Change any pixel that matches color
- Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
- Imagick::pingImage — Fetch basic attributes about the image
- Imagick::pingImageBlob — Quickly fetch attributes
- Imagick::pingImageFile — Get basic image attributes in a lightweight manner
- Imagick::polaroidImage — Simulates a Polaroid picture
- Imagick::posterizeImage — Reduces the image to a limited number of color level
- Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
- Imagick::previousImage — Move to the previous image in the object
- Imagick::profileImage — Adds or removes a profile from an image
- Imagick::quantizeImage — Analyzes the colors within a reference image
- Imagick::quantizeImages — Analyzes the colors within a sequence of images
- Imagick::queryFontMetrics — Returns an array representing the font metrics
- Imagick::queryFonts — Returns the configured fonts
- Imagick::queryFormats — Returns formats supported by Imagick
- Imagick::radialBlurImage — Radial blurs an image
- Imagick::raiseImage — Creates a simulated 3d button-like effect
- Imagick::randomThresholdImage — Creates a high-contrast, two-color image
- Imagick::readImage — Reads image from filename
- Imagick::readImageBlob — Reads image from a binary string
- Imagick::readImageFile — Reads image from open filehandle
- Imagick::readimages — Reads image from an array of filenames
- Imagick::recolorImage — Recolors image
- Imagick::reduceNoiseImage — Smooths the contours of an image
- Imagick::remapImage — Remaps image colors
- Imagick::removeImage — Removes an image from the image list
- Imagick::removeImageProfile — Removes the named image profile and returns it
- Imagick::render — Renders all preceding drawing commands
- Imagick::resampleImage — Resample image to desired resolution
- Imagick::resetImagePage — Reset image page
- Imagick::resizeImage — Scales an image
- Imagick::rollImage — Offsets an image
- Imagick::rotateImage — Rotates an image
- Imagick::rotationalBlurImage — Rotational blurs an image
- Imagick::roundCorners — Rounds image corners
- Imagick::sampleImage — Scales an image with pixel sampling
- Imagick::scaleImage — Scales the size of an image
- Imagick::segmentImage — Segments an image
- Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold
- Imagick::separateImageChannel — Separates a channel from the image
- Imagick::sepiaToneImage — Sepia tones an image
- Imagick::setBackgroundColor — Sets the object's default background color
- Imagick::setColorspace — Set colorspace
- Imagick::setCompression — Sets the object's default compression type
- Imagick::setCompressionQuality — Sets the object's default compression quality
- Imagick::setFilename — Sets the filename before you read or write the image
- Imagick::setFirstIterator — Sets the Imagick iterator to the first image
- Imagick::setFont — Sets font
- Imagick::setFormat — Sets the format of the Imagick object
- Imagick::setGravity — Sets the gravity
- Imagick::setImage — Replaces image in the object
- Imagick::setImageAlphaChannel — Sets image alpha channel
- Imagick::setImageArtifact — Set image artifact
- Imagick::setImageAttribute — Sets an image attribute
- Imagick::setImageBackgroundColor — Sets the image background color
- Imagick::setImageBias — Sets the image bias for any method that convolves an image
- Imagick::setImageBiasQuantum — Sets the image bias
- Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
- Imagick::setImageBorderColor — Sets the image border color
- Imagick::setImageChannelDepth — Sets the depth of a particular image channel
- Imagick::setImageClipMask — Sets image clip mask
- Imagick::setImageColormapColor — Sets the color of the specified colormap index
- Imagick::setImageColorspace — Sets the image colorspace
- Imagick::setImageCompose — Sets the image composite operator
- Imagick::setImageCompression — Sets the image compression
- Imagick::setImageCompressionQuality — Sets the image compression quality
- Imagick::setImageDelay — Sets the image delay
- Imagick::setImageDepth — Sets the image depth
- Imagick::setImageDispose — Sets the image disposal method
- Imagick::setImageExtent — Sets the image size
- Imagick::setImageFilename — Sets the filename of a particular image
- Imagick::setImageFormat — Sets the format of a particular image
- Imagick::setImageGamma — Sets the image gamma
- Imagick::setImageGravity — Sets the image gravity
- Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
- Imagick::setImageIndex — Set the iterator position
- Imagick::setImageInterlaceScheme — Sets the image compression
- Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
- Imagick::setImageIterations — Sets the image iterations
- Imagick::setImageMatte — Sets the image matte channel
- Imagick::setImageMatteColor — Sets the image matte color
- Imagick::setImageOpacity — Sets the image opacity level
- Imagick::setImageOrientation — Sets the image orientation
- Imagick::setImagePage — Sets the page geometry of the image
- Imagick::setImageProfile — Adds a named profile to the Imagick object
- Imagick::setImageProperty — Sets an image property
- Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
- Imagick::setImageRenderingIntent — Sets the image rendering intent
- Imagick::setImageResolution — Sets the image resolution
- Imagick::setImageScene — Sets the image scene
- Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
- Imagick::setImageType — Sets the image type
- Imagick::setImageUnits — Sets the image units of resolution
- Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
- Imagick::setImageWhitePoint — Sets the image chromaticity white point
- Imagick::setInterlaceScheme — Sets the image compression
- Imagick::setIteratorIndex — Set the iterator position
- Imagick::setLastIterator — Sets the Imagick iterator to the last image
- Imagick::setOption — Set an option
- Imagick::setPage — Sets the page geometry of the Imagick object
- Imagick::setPointSize — Sets point size
- Imagick::setProgressMonitor — Set a callback to be called during processing
- Imagick::setRegistry — Sets the ImageMagick registry entry named key to value
- Imagick::setResolution — Sets the image resolution
- Imagick::setResourceLimit — Sets the limit for a particular resource
- Imagick::setSamplingFactors — Sets the image sampling factors
- Imagick::setSize — Sets the size of the Imagick object
- Imagick::setSizeOffset — Sets the size and offset of the Imagick object
- Imagick::setType — Sets the image type attribute
- Imagick::shadeImage — Creates a 3D effect
- Imagick::shadowImage — Simulates an image shadow
- Imagick::sharpenImage — Sharpens an image
- Imagick::shaveImage — Shaves pixels from the image edges
- Imagick::shearImage — Creating a parallelogram
- Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
- Imagick::sketchImage — Simulates a pencil sketch
- Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them
- Imagick::solarizeImage — Applies a solarizing effect to the image
- Imagick::sparseColorImage — Interpolates colors
- Imagick::spliceImage — Splices a solid color into the image
- Imagick::spreadImage — Randomly displaces each pixel in a block
- Imagick::statisticImage — Modifies image using a statistics function
- Imagick::steganoImage — Hides a digital watermark within the image
- Imagick::stereoImage — Composites two images
- Imagick::stripImage — Strips an image of all profiles and comments
- Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image
- Imagick::swirlImage — Swirls the pixels about the center of the image
- Imagick::textureImage — Repeatedly tiles the texture image
- Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
- Imagick::thumbnailImage — Changes the size of an image
- Imagick::tintImage — Applies a color vector to each pixel in the image
- Imagick::__toString — Returns the image as a string
- Imagick::transformImage — Convenience method for setting crop size and the image geometry
- Imagick::transformImageColorspace — Transforms an image to a new colorspace
- Imagick::transparentPaintImage — Paints pixels transparent
- Imagick::transposeImage — Creates a vertical mirror image
- Imagick::transverseImage — Creates a horizontal mirror image
- Imagick::trimImage — Remove edges from the image
- Imagick::uniqueImageColors — Discards all but one of any pixel color
- Imagick::unsharpMaskImage — Sharpens an image
- Imagick::valid — Checks if the current item is valid
- Imagick::vignetteImage — Adds vignette filter to the image
- Imagick::waveImage — Applies wave filter to the image
- Imagick::whiteThresholdImage — Force all pixels above the threshold into white
- Imagick::writeImage — Writes an image to the specified filename
- Imagick::writeImageFile — Writes an image to a filehandle
- Imagick::writeImages — Writes an image or image sequence
- Imagick::writeImagesFile — Writes frames to a filehandle

# The ImagickDraw class

(PECL imagick 2, PECL imagick 3)

## Class synopsis

class ImagickDraw {
public affine(array `$affine`): bool
public annotation(float `$x`, float `$y`, string `$text`): bool
public arc(
float `$start_x`,
float `$start_y`,
float `$end_x`,
float `$end_y`,
float `$start_angle`,
float `$end_angle`
): bool
public bezier(array `$coordinates`): bool
public circle(
float `$origin_x`,
float `$origin_y`,
float `$perimeter_x`,
float `$perimeter_y`
): bool
public clear(): bool
public clone(): ImagickDraw
public color(float `$x`, float `$y`, int `$paint`): bool
public comment(string `$comment`): bool
public composite(
int `$composite`,
float `$x`,
float `$y`,
float `$width`,
float `$height`,
Imagick `$image`
): bool
public destroy(): bool
public ellipse(
float `$origin_x`,
float `$origin_y`,
float `$radius_x`,
float `$radius_y`,
float `$angle_start`,
float `$angle_end`
): bool
public getClipPath(): false|string
public getClipRule(): int
public getClipUnits(): int
public getFillColor(): ImagickPixel
public getFillOpacity(): float
public getFillRule(): int
public getFont(): string
public getFontFamily(): string
public getFontSize(): float
public getFontStretch(): int
public getFontStyle(): int
public getFontWeight(): int
public getGravity(): int
public getStrokeAntialias(): bool
public getStrokeColor(): ImagickPixel
public getStrokeDashArray(): array
public getStrokeDashOffset(): float
public getStrokeLineCap(): int
public getStrokeLineJoin(): int
public getStrokeMiterLimit(): int
public getStrokeOpacity(): float
public getStrokeWidth(): float
public getTextAlignment(): int
public getTextAntialias(): bool
public getTextDecoration(): int
public getTextEncoding(): false|string
public getTextInterlineSpacing(): float
public getTextInterwordSpacing(): float
public getTextKerning(): float
public getTextUnderColor(): ImagickPixel
public getVectorGraphics(): string
public line(
float `$start_x`,
float `$start_y`,
float `$end_x`,
float `$end_y`
): bool
public matte(float `$x`, float `$y`, int `$paint`): bool
public pathClose(): bool
public pathCurveToAbsolute(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
public pathCurveToQuadraticBezierAbsolute(
float `$x1`,
float `$y1`,
float `$x_end`,
float `$y`
): bool
public pathCurveToQuadraticBezierRelative(
float `$x1`,
float `$y1`,
float `$x_end`,
float `$y`
): bool
public pathCurveToQuadraticBezierSmoothAbsolute(float `$x`, float `$y`): bool
public pathCurveToQuadraticBezierSmoothRelative(float `$x`, float `$y`): bool
public pathCurveToRelative(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
public pathCurveToSmoothAbsolute(
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
public pathCurveToSmoothRelative(
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
public pathEllipticArcAbsolute(
float `$rx`,
float `$ry`,
float `$x_axis_rotation`,
bool `$large_arc`,
bool `$sweep`,
float `$x`,
float `$y`
): bool
public pathEllipticArcRelative(
float `$rx`,
float `$ry`,
float `$x_axis_rotation`,
bool `$large_arc`,
bool `$sweep`,
float `$x`,
float `$y`
): bool
public pathFinish(): bool
public pathLineToAbsolute(float `$x`, float `$y`): bool
public pathLineToHorizontalAbsolute(float `$x`): bool
public pathLineToHorizontalRelative(float `$x`): bool
public pathLineToRelative(float `$x`, float `$y`): bool
public pathLineToVerticalAbsolute(float `$y`): bool
public pathLineToVerticalRelative(float `$y`): bool
public pathMoveToAbsolute(float `$x`, float `$y`): bool
public pathMoveToRelative(float `$x`, float `$y`): bool
public pathStart(): bool
public point(float `$x`, float `$y`): bool
public polygon(array `$coordinates`): bool
public polyline(array `$coordinates`): bool
public pop(): bool
public popClipPath(): bool
public popDefs(): bool
public popPattern(): bool
public push(): bool
public pushClipPath(string `$clip_mask_id`): bool
public pushDefs(): bool
public pushPattern(
string `$pattern_id`,
float `$x`,
float `$y`,
float `$width`,
float `$height`
): bool
public rectangle(
float `$top_left_x`,
float `$top_left_y`,
float `$bottom_right_x`,
float `$bottom_right_y`
): bool
public render(): bool
public resetVectorGraphics(): bool
public rotate(float `$degrees`): bool
public roundRectangle(
float `$top_left_x`,
float `$top_left_y`,
float `$bottom_right_x`,
float `$bottom_right_y`,
float `$rounding_x`,
float `$rounding_y`
): bool
public scale(float `$x`, float `$y`): bool
public setClipPath(string `$clip_mask`): bool
public setClipRule(int `$fillrule`): bool
public setClipUnits(int `$pathunits`): bool
public setFillAlpha(float `$alpha`): bool
public setFillColor(ImagickPixel|string `$fill_color`): bool
public setFillOpacity(float `$opacity`): bool
public setFillPatternURL(string `$fill_url`): bool
public setFillRule(int `$fillrule`): bool
public setFont(string `$font_name`): bool
public setFontFamily(string `$font_family`): bool
public setFontSize(float `$point_size`): bool
public setFontStretch(int `$stretch`): bool
public setFontStyle(int `$style`): bool
public setFontWeight(int `$weight`): bool
public setGravity(int `$gravity`): bool
public setResolution(float `$resolution_x`, float `$resolution_y`): bool
public setStrokeAlpha(float `$alpha`): bool
public setStrokeAntialias(bool `$enabled`): bool
public setStrokeColor(ImagickPixel|string `$color`): bool
public setStrokeDashArray(?array `$dashes`): bool
public setStrokeDashOffset(float `$dash_offset`): bool
public setStrokeLineCap(int `$linecap`): bool
public setStrokeLineJoin(int `$linejoin`): bool
public setStrokeMiterLimit(int `$miterlimit`): bool
public setStrokeOpacity(float `$opacity`): bool
public setStrokePatternURL(string `$stroke_url`): bool
public setStrokeWidth(float `$width`): bool
public setTextAlignment(int `$align`): bool
public setTextAntialias(bool `$antialias`): bool
public setTextDecoration(int `$decoration`): bool
public setTextEncoding(string `$encoding`): bool
public setTextInterlineSpacing(float `$spacing`): bool
public setTextInterwordSpacing(float `$spacing`): bool
public setTextKerning(float `$kerning`): bool
public setTextUnderColor(ImagickPixel|string `$under_color`): bool
public setVectorGraphics(string `$xml`): bool
public setViewbox(
int `$left_x`,
int `$top_y`,
int `$right_x`,
int `$bottom_y`
): bool
public skewX(float `$degrees`): bool
public skewY(float `$degrees`): bool
public translate(float `$x`, float `$y`): bool
}

# ImagickDraw::affine

(PECL imagick 2, PECL imagick 3)

ImagickDraw::affine — Adjusts the current affine transformation matrix

### Description

public ImagickDraw::affine(array `$affine`): bool
Warning

This function is currently not documented; only its argument list is available.

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

### Parameters

`affine`

  Affine matrix parameters

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::affine() example

`<?php
function affine($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$PI = 3.141592653589794;
$angle = 60 * $PI / 360;
//Scale the drawing co-ordinates.
$affineScale = array("sx" => 1.75, "sy" => 1.75, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);
//Shear the drawing co-ordinates.
$affineShear = array("sx" => 1, "sy" => 1, "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0);
//Rotate the drawing co-ordinates. The shear affine matrix
//produces incorrectly scaled drawings.
$affineRotate = array("sx" => cos($angle), "sy" => cos($angle), "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0,);
//Translate (offset) the drawing
$affineTranslate = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 30, "ty" => 30);
//The identiy affine matrix
$affineIdentity = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);
$examples = [$affineScale, $affineShear, $affineRotate, $affineTranslate, $affineIdentity,];
$count = 0;
foreach ($examples as $example) {
$draw->push();
$draw->translate(($count % 2) * 250, intval($count / 2) * 250);
$draw->translate(100, 100);
$draw->affine($example);
$draw->rectangle(-50, -50, 50, 50);
$draw->pop();
$count++;
}
//Create an image object which the draw commands can be rendered into
$image = new \Imagick();
$image->newImage(500, 750, $backgroundColor);
$image->setImageFormat("png");
//Render the draw commands in the ImagickDraw object
//into the image.
$image->drawImage($draw);
//Send the image to the browser
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::annotation

(PECL imagick 2, PECL imagick 3)

ImagickDraw::annotation — Draws text on the image

### Description

public ImagickDraw::annotation(float `$x`, float `$y`, string `$text`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws text on the image.

### Parameters

`x`

  The x coordinate where text is drawn

`y`

  The y coordinate where text is drawn

`text`

  The text to draw on the image

### Return Values

No value is returned.

# ImagickDraw::arc

(PECL imagick 2, PECL imagick 3)

ImagickDraw::arc — Draws an arc

### Description

public ImagickDraw::arc(
float `$start_x`,
float `$start_y`,
float `$end_x`,
float `$end_y`,
float `$start_angle`,
float `$end_angle`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws an arc falling within a specified bounding rectangle on the image.

### Parameters

`start_x`

  Starting x ordinate of bounding rectangle

`start_y`

  starting y ordinate of bounding rectangle

`end_x`

  ending x ordinate of bounding rectangle

`end_y`

  ending y ordinate of bounding rectangle

`start_angle`

  starting degrees of rotation

`end_angle`

  ending degrees of rotation

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::arc() example

`<?php
function arc($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $startAngle, $endAngle) {
//Create a ImagickDraw object to draw into.
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->arc($startX, $startY, $endX, $endY, $startAngle, $endAngle);
//Create an image object which the draw commands can be rendered into
$image = new \Imagick();
$image->newImage(IMAGE_WIDTH, IMAGE_HEIGHT, $backgroundColor);
$image->setImageFormat("png");
//Render the draw commands in the ImagickDraw object
//into the image.
$image->drawImage($draw);
//Send the image to the browser
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::bezier

(PECL imagick 2, PECL imagick 3)

ImagickDraw::bezier — Draws a bezier curve

### Description

public ImagickDraw::bezier(array `$coordinates`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a bezier curve through a set of points on the image.

### Parameters

`coordinates`

  Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::bezier() example

`<?php
function bezier($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$smoothPointsSet = [
[
['x' => 10.0 * 5, 'y' => 10.0 * 5],
['x' => 30.0 * 5, 'y' => 90.0 * 5],
['x' => 25.0 * 5, 'y' => 10.0 * 5],
['x' => 50.0 * 5, 'y' => 50.0 * 5],
],
[
['x' => 50.0 * 5, 'y' => 50.0 * 5],
['x' => 75.0 * 5, 'y' => 90.0 * 5],
['x' => 70.0 * 5, 'y' => 10.0 * 5],
['x' => 90.0 * 5, 'y' => 40.0 * 5],
],
];
foreach ($smoothPointsSet as $points) {
$draw->bezier($points);
}
$disjointPoints = [
[
['x' => 10 * 5, 'y' => 10 * 5],
['x' => 30 * 5, 'y' => 90 * 5],
['x' => 25 * 5, 'y' => 10 * 5],
['x' => 50 * 5, 'y' => 50 * 5],
],
[
['x' => 50 * 5, 'y' => 50 * 5],
['x' => 80 * 5, 'y' => 50 * 5],
['x' => 70 * 5, 'y' => 10 * 5],
['x' => 90 * 5, 'y' => 40 * 5],
]
];
$draw->translate(0, 200);
foreach ($disjointPoints as $points) {
$draw->bezier($points);
}
//Create an image object which the draw commands can be rendered into
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
//Render the draw commands in the ImagickDraw object
//into the image.
$imagick->drawImage($draw);
//Send the image to the browser
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::circle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::circle — Draws a circle

### Description

public ImagickDraw::circle(
float `$origin_x`,
float `$origin_y`,
float `$perimeter_x`,
float `$perimeter_y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a circle on the image.

### Parameters

`origin_x`

  origin x coordinate

`origin_y`

  origin y coordinate

`perimeter_x`

  perimeter x coordinate

`perimeter_y`

  perimeter y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::circle() example

`<?php
function circle($strokeColor, $fillColor, $backgroundColor, $originX, $originY, $endX, $endY) {
//Create a ImagickDraw object to draw into.
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->circle($originX, $originY, $endX, $endY);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::clear

(PECL imagick 2, PECL imagick 3)

ImagickDraw::clear — Clears the ImagickDraw

### Description

public ImagickDraw::clear(): bool
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

### Return Values

Returns an ImagickDraw object.

# ImagickDraw::clone

(PECL imagick 2, PECL imagick 3)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

### Description

public ImagickDraw::clone(): ImagickDraw
Warning

This function is currently not documented; only its argument list is available.

Makes an exact copy of the specified ImagickDraw object.

### Return Values

returns an exact copy of the specified ImagickDraw object.

# ImagickDraw::color

(PECL imagick 2, PECL imagick 3)

ImagickDraw::color — Draws color on image

### Description

public ImagickDraw::color(float `$x`, float `$y`, int `$paint`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

### Parameters

`x`

  x coordinate of the paint

`y`

  y coordinate of the paint

`paint`

  One of the PAINT constant (`imagick::PAINT_*`).

### Return Values

No value is returned.

# ImagickDraw::comment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::comment — Adds a comment

### Description

public ImagickDraw::comment(string `$comment`): bool
Warning

This function is currently not documented; only its argument list is available.

Adds a comment to a vector output stream.

### Parameters

`comment`

  The comment string to add to vector output stream

### Return Values

No value is returned.

# ImagickDraw::composite

(PECL imagick 2, PECL imagick 3)

ImagickDraw::composite — Composites an image onto the current image

### Description

public ImagickDraw::composite(
int `$composite`,
float `$x`,
float `$y`,
float `$width`,
float `$height`,
Imagick `$image`
): bool
Warning

This function is currently not documented; only its argument list is available.

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

### Parameters

`composite`

  composition operator. One of the Composite Operator constant (`imagick::COMPOSITE_*`).

`x`

  x coordinate of the top left corner.

`y`

  y coordinate of the top left corner.

`width`

  width of the composition image.

`height`

  height of the composition image.

`image`

  the Imagick object where composition image is taken from.

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::composite() example

`<?php
function composite($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setFillOpacity(1);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFont("../fonts/CANDY.TTF");
$draw->setFontSize(140);
$draw->rectangle(0, 0, 1000, 300);
$draw->setFillColor('white');
$draw->setfillopacity(1);
$draw->annotation(50, 180, "Lorem Ipsum!");
//Create an image object which the draw commands can be rendered into
$imagick = new \Imagick();
$imagick->newImage(1000, 302, $backgroundColor);
$imagick->setImageFormat("png");
//Render the draw commands in the ImagickDraw object
//into the image.
$imagick->drawImage($draw);
//Send the image to the browser
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::__construct

(PECL imagick 2, PECL imagick 3)

ImagickDraw::__construct — The ImagickDraw constructor

### Description

public ImagickDraw::__construct()
Warning

This function is currently not documented; only its argument list is available.

The ImagickDraw constructor.

### Return Values

No value is returned.

# ImagickDraw::destroy

(PECL imagick 2, PECL imagick 3)

ImagickDraw::destroy — Frees all associated resources

### Description

public ImagickDraw::destroy(): bool
Warning

This function is currently not documented; only its argument list is available.

Frees all resources associated with the ImagickDraw object.

### Return Values

No value is returned.

# ImagickDraw::ellipse

(PECL imagick 2, PECL imagick 3)

ImagickDraw::ellipse — Draws an ellipse on the image

### Description

public ImagickDraw::ellipse(
float `$origin_x`,
float `$origin_y`,
float `$radius_x`,
float `$radius_y`,
float `$angle_start`,
float `$angle_end`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws an ellipse on the image.

### Parameters

`origin_x`

`origin_y`

`radius_x`

`radius_y`

`angle_start`

`angle_end`

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::ellipse() example

`<?php
function ellipse($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->ellipse(125, 70, 100, 50, 0, 360);
$draw->ellipse(350, 70, 100, 50, 0, 315);
$draw->push();
$draw->translate(125, 250);
$draw->rotate(30);
$draw->ellipse(0, 0, 100, 50, 0, 360);
$draw->pop();
$draw->push();
$draw->translate(350, 250);
$draw->rotate(30);
$draw->ellipse(0, 0, 100, 50, 0, 315);
$draw->pop();
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::getClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipPath — Obtains the current clipping path ID

### Description

public ImagickDraw::getClipPath(): false|string
Warning

This function is currently not documented; only its argument list is available.

Obtains the current clipping path ID.

### Return Values

Returns a string containing the clip path ID or false if no clip path exists.

# ImagickDraw::getClipRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipRule — Returns the current polygon fill rule

### Description

public ImagickDraw::getClipRule(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the current polygon fill rule to be used by the clipping path.

### Return Values

Returns a FILLRULE constant (`imagick::FILLRULE_*`).

# ImagickDraw::getClipUnits

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

### Description

public ImagickDraw::getClipUnits(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the interpretation of clip path units.

### Return Values

Returns an int on success.

# ImagickDraw::getFillColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillColor — Returns the fill color

### Description

public ImagickDraw::getFillColor(): ImagickPixel
Warning

This function is currently not documented; only its argument list is available.

Returns the fill color used for drawing filled objects.

### Return Values

Returns an ImagickPixel object.

# ImagickDraw::getFillOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

### Description

public ImagickDraw::getFillOpacity(): float
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

### Return Values

The opacity.

# ImagickDraw::getFillRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillRule — Returns the fill rule

### Description

public ImagickDraw::getFillRule(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the fill rule used while drawing polygons.

### Return Values

Returns a FILLRULE constant (`imagick::FILLRULE_*`).

# ImagickDraw::getFont

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFont — Returns the font

### Description

public ImagickDraw::getFont(): string
Warning

This function is currently not documented; only its argument list is available.

Returns a string specifying the font used when annotating with text.

### Return Values

Returns a string on success and false if no font is set.

# ImagickDraw::getFontFamily

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontFamily — Returns the font family

### Description

public ImagickDraw::getFontFamily(): string
Warning

This function is currently not documented; only its argument list is available.

Returns the font family to use when annotating with text.

### Return Values

Returns the font family currently selected or false if font family is not set.

# ImagickDraw::getFontSize

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontSize — Returns the font pointsize

### Description

public ImagickDraw::getFontSize(): float
Warning

This function is currently not documented; only its argument list is available.

Returns the font pointsize used when annotating with text.

### Return Values

Returns the font size associated with the current ImagickDraw object.

# ImagickDraw::getFontStretch

(PECL imagick 2 >=2.3.0, PECL imagick 3)

ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text

### Description

public ImagickDraw::getFontStretch(): int

Gets the font stretch to use when annotating with text. Returns a StretchType.

### Parameters

This function has no parameters.

### Return Values

# ImagickDraw::getFontStyle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontStyle — Returns the font style

### Description

public ImagickDraw::getFontStyle(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the font style used when annotating with text.

### Return Values

Returns a STYLE constant (`imagick::STYLE_*`) associated with the ImagickDraw object or 0 if no style is set.

# ImagickDraw::getFontWeight

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontWeight — Returns the font weight

### Description

public ImagickDraw::getFontWeight(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the font weight used when annotating with text.

### Return Values

Returns an int on success and 0 if no weight is set.

# ImagickDraw::getGravity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getGravity — Returns the text placement gravity

### Description

public ImagickDraw::getGravity(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the text placement gravity used when annotating with text.

### Return Values

Returns a GRAVITY constant (`imagick::GRAVITY_*`) on success and 0 if no gravity is set.

# ImagickDraw::getStrokeAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

### Description

public ImagickDraw::getStrokeAntialias(): bool
Warning

This function is currently not documented; only its argument list is available.

Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

### Return Values

Returns `true` if antialiasing is on and `false` if it is off.

# ImagickDraw::getStrokeColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

### Description

public ImagickDraw::getStrokeColor(): ImagickPixel
Warning

This function is currently not documented; only its argument list is available.

Returns the color used for stroking object outlines.

### Parameters

`stroke_color`

### Return Values

Returns an ImagickPixel object which describes the color.

# ImagickDraw::getStrokeDashArray

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

### Description

public ImagickDraw::getStrokeDashArray(): array
Warning

This function is currently not documented; only its argument list is available.

Returns an array representing the pattern of dashes and gaps used to stroke paths.

### Return Values

Returns an array on success and empty array if not set.

# ImagickDraw::getStrokeDashOffset

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

### Description

public ImagickDraw::getStrokeDashOffset(): float
Warning

This function is currently not documented; only its argument list is available.

Returns the offset into the dash pattern to start the dash.

### Return Values

Returns a float representing the offset and 0 if it's not set.

# ImagickDraw::getStrokeLineCap

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

### Description

public ImagickDraw::getStrokeLineCap(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the end of open subpaths when they are stroked.

### Return Values

Returns a LINECAP constant (`imagick::LINECAP_*`), or 0 if stroke linecap is not set.

# ImagickDraw::getStrokeLineJoin

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

### Description

public ImagickDraw::getStrokeLineJoin(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

### Return Values

Returns a LINEJOIN constant (`imagick::LINEJOIN_*`), or 0 if stroke line join is not set.

# ImagickDraw::getStrokeMiterLimit

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

### Description

public ImagickDraw::getStrokeMiterLimit(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

### Return Values

Returns an int describing the miter limit and 0 if no miter limit is set.

# ImagickDraw::getStrokeOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

### Description

public ImagickDraw::getStrokeOpacity(): float
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity of stroked object outlines.

### Return Values

Returns a float describing the opacity.

# ImagickDraw::getStrokeWidth

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

### Description

public ImagickDraw::getStrokeWidth(): float
Warning

This function is currently not documented; only its argument list is available.

Returns the width of the stroke used to draw object outlines.

### Return Values

Returns a float describing the stroke width.

# ImagickDraw::getTextAlignment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextAlignment — Returns the text alignment

### Description

public ImagickDraw::getTextAlignment(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the alignment applied when annotating with text.

### Return Values

Returns a ALIGN constant (`imagick::ALIGN_*`), and 0 if no align is set.

# ImagickDraw::getTextAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

### Description

public ImagickDraw::getTextAntialias(): bool
Warning

This function is currently not documented; only its argument list is available.

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

### Return Values

Returns `true` if text is antialiased and `false` if not.

# ImagickDraw::getTextDecoration

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextDecoration — Returns the text decoration

### Description

public ImagickDraw::getTextDecoration(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the decoration applied when annotating with text.

### Return Values

Returns a DECORATION constant (`imagick::DECORATION_*`), and 0 if no decoration is set.

# ImagickDraw::getTextEncoding

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

### Description

public ImagickDraw::getTextEncoding(): false|string
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the code set used for text annotations.

### Return Values

Returns a string specifying the code set or false if text encoding is not set.

# ImagickDraw::getTextInterlineSpacing

(PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextInterlineSpacing — Gets the text interline spacing

### Description

public ImagickDraw::getTextInterlineSpacing(): float

Gets the text interline spacing.

### Parameters

This function has no parameters.

### Return Values

# ImagickDraw::getTextInterwordSpacing

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing

### Description

public ImagickDraw::getTextInterwordSpacing(): float

Gets the text interword spacing.

### Parameters

This function has no parameters.

### Return Values

# ImagickDraw::getTextKerning

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextKerning — Gets the text kerning

### Description

public ImagickDraw::getTextKerning(): float

Gets the text kerning.

### Parameters

This function has no parameters.

### Return Values

# ImagickDraw::getTextUnderColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextUnderColor — Returns the text under color

### Description

public ImagickDraw::getTextUnderColor(): ImagickPixel
Warning

This function is currently not documented; only its argument list is available.

Returns the color of a background rectangle to place under text annotations.

### Return Values

Returns an ImagickPixel object describing the color.

# ImagickDraw::getVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

### Description

public ImagickDraw::getVectorGraphics(): string
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

### Return Values

Returns a string containing the vector graphics.

# ImagickDraw::line

(PECL imagick 2, PECL imagick 3)

ImagickDraw::line — Draws a line

### Description

public ImagickDraw::line(
float `$start_x`,
float `$start_y`,
float `$end_x`,
float `$end_y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

### Parameters

`start_x`

  starting x coordinate

`start_y`

  starting y coordinate

`end_x`

  ending x coordinate

`end_y`

  ending y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::line() example

`<?php
function line($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->line(125, 70, 100, 50);
$draw->line(350, 170, 100, 150);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::matte

(PECL imagick 2, PECL imagick 3)

ImagickDraw::matte — Paints on the image's opacity channel

### Description

public ImagickDraw::matte(float `$x`, float `$y`, int `$paint`): bool
Warning

This function is currently not documented; only its argument list is available.

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

### Parameters

`x`

  x coordinate of the matte

`y`

  y coordinate of the matte

`paint`

  One of the PAINT constant (`imagick::PAINT_*`).

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ImagickDraw::matte() example

`<?php
function matte($strokeColor, $fillColor, $backgroundColor, $paintType) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->matte(120, 120, $paintType);
$draw->rectangle(100, 100, 300, 200);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::pathClose

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathClose — Adds a path element to the current path

### Description

public ImagickDraw::pathClose(): bool
Warning

This function is currently not documented; only its argument list is available.

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).

### Return Values

No value is returned.

# ImagickDraw::pathCurveToAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

### Description

public ImagickDraw::pathCurveToAbsolute(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x1`

  x coordinate of the first control point

`y1`

  y coordinate of the first control point

`x2`

  x coordinate of the second control point

`y2`

  y coordinate of the first control point

`x`

  x coordinate of the curve end

`y`

  y coordinate of the curve end

### Return Values

No value is returned.

# ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

### Description

public ImagickDraw::pathCurveToQuadraticBezierAbsolute(
float `$x1`,
float `$y1`,
float `$x_end`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x1`

  x coordinate of the control point

`y1`

  y coordinate of the control point

`x_end`

  x coordinate of the end point

`y`

  y coordinate of the end point

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::pathCurveToQuadraticBezierAbsolute() example

`<?php
function pathCurveToQuadraticBezierAbsolute($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);
$draw->pathFinish();
$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

### Description

public ImagickDraw::pathCurveToQuadraticBezierRelative(
float `$x1`,
float `$y1`,
float `$x_end`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x1`

  starting x coordinate

`y1`

  starting y coordinate

`x_end`

  ending x coordinate

`y`

  ending y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

### Description

public ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute(float `$x`, float `$y`): bool

Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

### Parameters

`x`

  ending x coordinate

`y`

  ending y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute() example

`<?php
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);
$draw->pathFinish();
$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>`

# ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

### Description

public ImagickDraw::pathCurveToQuadraticBezierSmoothRelative(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve (using relative coordinates) from the current point to (x, y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point). At the end of the command, the new current point becomes the final (x, y) coordinate pair used in the polybezier.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

### Parameters

`x`

  ending x coordinate

`y`

  ending y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothRelative() example

`<?php
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);
// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);
$draw->pathFinish();
$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>`

# ImagickDraw::pathCurveToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

### Description

public ImagickDraw::pathCurveToRelative(
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x1`

  x coordinate of starting control point

`y1`

  y coordinate of starting control point

`x2`

  x coordinate of ending control point

`y2`

  y coordinate of ending control point

`x`

  ending x coordinate

`y`

  ending y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

### Description

public ImagickDraw::pathCurveToSmoothAbsolute(
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x2`

  x coordinate of the second control point

`y2`

  y coordinate of the second control point

`x`

  x coordinate of the ending point

`y`

  y coordinate of the ending point

### Return Values

No value is returned.

# ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

### Description

public ImagickDraw::pathCurveToSmoothRelative(
float `$x2`,
float `$y2`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using relative coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

### Parameters

`x2`

  x coordinate of the second control point

`y2`

  y coordinate of the second control point

`x`

  x coordinate of the ending point

`y`

  y coordinate of the ending point

### Return Values

No value is returned.

# ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

### Description

public ImagickDraw::pathEllipticArcAbsolute(
float `$rx`,
float `$ry`,
float `$x_axis_rotation`,
bool `$large_arc`,
bool `$sweep`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using absolute coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If `large_arc` is `true` then draw the larger of the available arcs. If `sweep` is true, then draw the arc matching a clock-wise rotation.

### Parameters

`rx`

  x radius

`ry`

  y radius

`x_axis_rotation`

  x axis rotation

`large_arc`

  large arc flag

`sweep`

  sweep flag

`x`

  x coordinate

`y`

  y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathEllipticArcRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

### Description

public ImagickDraw::pathEllipticArcRelative(
float `$rx`,
float `$ry`,
float `$x_axis_rotation`,
bool `$large_arc`,
bool `$sweep`,
float `$x`,
float `$y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If `large_arc` is `true` then draw the larger of the available arcs. If `sweep` is true, then draw the arc matching a clock-wise rotation.

### Parameters

`rx`

  x radius

`ry`

  y radius

`x_axis_rotation`

  x axis rotation

`large_arc`

  large arc flag

`sweep`

  sweep flag

`x`

  x coordinate

`y`

  y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathFinish

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathFinish — Terminates the current path

### Description

public ImagickDraw::pathFinish(): bool
Warning

This function is currently not documented; only its argument list is available.

Terminates the current path.

### Return Values

No value is returned.

# ImagickDraw::pathLineToAbsolute

(PECL imagick 2)

ImagickDraw::pathLineToAbsolute — Draws a line path

### Description

public ImagickDraw::pathLineToAbsolute(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

### Parameters

`x`

  starting x coordinate

`y`

  ending x coordinate

### Return Values

No value is returned.

# ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

### Description

public ImagickDraw::pathLineToHorizontalAbsolute(float `$x`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

### Parameters

`x`

  x coordinate

### Return Values

No value is returned.

# ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

### Description

public ImagickDraw::pathLineToHorizontalRelative(float `$x`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

### Parameters

`x`

  x coordinate

### Return Values

No value is returned.

# ImagickDraw::pathLineToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToRelative — Draws a line path

### Description

public ImagickDraw::pathLineToRelative(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

### Parameters

`x`

  starting x coordinate

`y`

  starting y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

### Description

public ImagickDraw::pathLineToVerticalAbsolute(float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

### Parameters

`y`

  y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

### Description

public ImagickDraw::pathLineToVerticalRelative(float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

### Parameters

`y`

  y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathMoveToAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

### Description

public ImagickDraw::pathMoveToAbsolute(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

### Parameters

`x`

  x coordinate of the starting point

`y`

  y coordinate of the starting point

### Return Values

No value is returned.

# ImagickDraw::pathMoveToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

### Description

public ImagickDraw::pathMoveToRelative(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

### Parameters

`x`

  target x coordinate

`y`

  target y coordinate

### Return Values

No value is returned.

# ImagickDraw::pathStart

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathStart — Declares the start of a path drawing list

### Description

public ImagickDraw::pathStart(): bool
Warning

This function is currently not documented; only its argument list is available.

Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::pathStart() example

`<?php
function pathStart($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pathStart();
$draw->pathMoveToAbsolute(50, 50);
$draw->pathLineToAbsolute(100, 50);
$draw->pathLineToRelative(0, 50);
$draw->pathLineToHorizontalRelative(-50);
$draw->pathFinish();
$draw->pathStart();
$draw->pathMoveToAbsolute(50, 50);
$draw->pathMoveToRelative(300, 0);
$draw->pathLineToRelative(50, 0);
$draw->pathLineToVerticalRelative(50);
$draw->pathLineToHorizontalAbsolute(350);
$draw->pathclose();
$draw->pathFinish();
$draw->pathStart();
$draw->pathMoveToAbsolute(50, 300);
$draw->pathCurveToAbsolute(50, 300, 100, 200, 300, 300);
$draw->pathLineToVerticalAbsolute(350);
$draw->pathFinish();
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::point

(PECL imagick 2, PECL imagick 3)

ImagickDraw::point — Draws a point

### Description

public ImagickDraw::point(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

### Parameters

`x`

  point's x coordinate

`y`

  point's y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::point() example

`<?php
function point($fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setFillColor($fillColor);
for ($x = 0; $x < 10000; $x++) {
$draw->point(rand(0, 500), rand(0, 500));
}
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::polygon

(PECL imagick 2, PECL imagick 3)

ImagickDraw::polygon — Draws a polygon

### Description

public ImagickDraw::polygon(array `$coordinates`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

### Parameters

`coordinates`

  multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::polygon() example

`<?php
function polygon($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(4);
$draw->setFillColor($fillColor);
$points = [
['x' => 40 * 5, 'y' => 10 * 5],
['x' => 20 * 5, 'y' => 20 * 5],
['x' => 70 * 5, 'y' => 50 * 5],
['x' => 60 * 5, 'y' => 15 * 5],
];
$draw->polygon($points);
$image = new \Imagick();
$image->newImage(500, 300, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::polyline

(PECL imagick 2, PECL imagick 3)

ImagickDraw::polyline — Draws a polyline

### Description

public ImagickDraw::polyline(array `$coordinates`): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

### Parameters

`coordinates`

  array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::polyline() example

`<?php
function polyline($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(5);
$points = [
['x' => 40 * 5, 'y' => 10 * 5],
['x' => 20 * 5, 'y' => 20 * 5],
['x' => 70 * 5, 'y' => 50 * 5],
['x' => 60 * 5, 'y' => 15 * 5]
];
$draw->polyline($points);
$image = new \Imagick();
$image->newImage(500, 300, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::pop

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

### Description

public ImagickDraw::pop(): bool
Warning

This function is currently not documented; only its argument list is available.

Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw. Multiple ImagickDraws may exist. It is an error to attempt to pop more ImagickDraws than have been pushed, and it is proper form to pop all ImagickDraws which have been pushed.

### Return Values

Returns `true` on success or `false` on failure.

# ImagickDraw::popClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popClipPath — Terminates a clip path definition

### Description

public ImagickDraw::popClipPath(): bool
Warning

This function is currently not documented; only its argument list is available.

Terminates a clip path definition.

### Return Values

No value is returned.

# ImagickDraw::popDefs

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popDefs — Terminates a definition list

### Description

public ImagickDraw::popDefs(): bool
Warning

This function is currently not documented; only its argument list is available.

Terminates a definition list.

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::popDefs() example

`<?php
function popDefs($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setstrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pushDefs();
$draw->setStrokeColor('white');
$draw->rectangle(50, 50, 200, 200);
$draw->popDefs();
$draw->rectangle(300, 50, 450, 200);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::popPattern

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popPattern — Terminates a pattern definition

### Description

public ImagickDraw::popPattern(): bool
Warning

This function is currently not documented; only its argument list is available.

Terminates a pattern definition.

### Return Values

Returns `true` on success or `false` on failure.

# ImagickDraw::push

(PECL imagick 2, PECL imagick 3)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

### Description

public ImagickDraw::push(): bool
Warning

This function is currently not documented; only its argument list is available.

Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking ImagickDraw::pop(). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ImagickDraw::push() example

`<?php
function push($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillModifiedColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->push();
$draw->translate(50, 50);
$draw->rectangle(200, 200, 300, 300);
$draw->pop();
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::pushClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushClipPath — Starts a clip path definition

### Description

public ImagickDraw::pushClipPath(string `$clip_mask_id`): bool
Warning

This function is currently not documented; only its argument list is available.

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

### Parameters

`clip_mask_id`

  Clip mask Id

### Return Values

No value is returned.

# ImagickDraw::pushDefs

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

### Description

public ImagickDraw::pushDefs(): bool
Warning

This function is currently not documented; only its argument list is available.

Indicates that commands up to a terminating ImagickDraw::popDefs() command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

### Return Values

No value is returned.

# ImagickDraw::pushPattern

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

### Description

public ImagickDraw::pushPattern(
string `$pattern_id`,
float `$x`,
float `$y`,
float `$width`,
float `$height`
): bool
Warning

This function is currently not documented; only its argument list is available.

Indicates that subsequent commands up to a DrawPopPattern() command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

### Parameters

`pattern_id`

  the pattern Id

`x`

  x coordinate of the top-left corner

`y`

  y coordinate of the top-left corner

`width`

  width of the pattern

`height`

  height of the pattern

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ImagickDraw::pushPattern() example

`<?php
function pushPattern($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->pushPattern("MyFirstPattern", 0, 0, 50, 50);
for ($x = 0; $x < 50; $x += 10) {
for ($y = 0; $y < 50; $y += 5) {
$positionX = $x + (($y / 5) % 5);
$draw->rectangle($positionX, $y, $positionX + 5, $y + 5);
}
}
$draw->popPattern();
$draw->setFillOpacity(0);
$draw->rectangle(100, 100, 400, 400);
$draw->setFillOpacity(1);
$draw->setFillOpacity(1);
$draw->push();
$draw->setFillPatternURL('#MyFirstPattern');
$draw->setFillColor('yellow');
$draw->rectangle(100, 100, 400, 400);
$draw->pop();
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::rectangle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::rectangle — Draws a rectangle

### Description

public ImagickDraw::rectangle(
float `$top_left_x`,
float `$top_left_y`,
float `$bottom_right_x`,
float `$bottom_right_y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

### Parameters

`top_left_x`

  x coordinate of the top left corner

`top_left_y`

  y coordinate of the top left corner

`bottom_right_x`

  x coordinate of the bottom right corner

`bottom_right_y`

  y coordinate of the bottom right corner

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::rectangle() example

`<?php
function rectangle($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::render

(PECL imagick 2, PECL imagick 3)

ImagickDraw::render — Renders all preceding drawing commands onto the image

### Description

public ImagickDraw::render(): bool
Warning

This function is currently not documented; only its argument list is available.

Renders all preceding drawing commands onto the image.

### Return Values

Returns `true` on success or `false` on failure.

# ImagickDraw::resetVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::resetVectorGraphics — Resets the vector graphics

### Description

public ImagickDraw::resetVectorGraphics(): bool

Resets the vector graphics.

### Parameters

This function has no parameters.

### Return Values

Returns `true` on success.

# ImagickDraw::rotate

(PECL imagick 2, PECL imagick 3)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

### Description

public ImagickDraw::rotate(float `$degrees`): bool
Warning

This function is currently not documented; only its argument list is available.

Applies the specified rotation to the current coordinate space.

### Parameters

`degrees`

  degrees to rotate.

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::rotate() example

`<?php
function rotate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeOpacity(1);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$draw->setFillColor($fillModifiedColor);
$draw->rotate(15);
$draw->rectangle(200, 200, 300, 300);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::roundRectangle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::roundRectangle — Draws a rounded rectangle

### Description

public ImagickDraw::roundRectangle(
float `$top_left_x`,
float `$top_left_y`,
float `$bottom_right_x`,
float `$bottom_right_y`,
float `$rounding_x`,
float `$rounding_y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

### Parameters

`top_left_x`

  x coordinate of the top left corner

`top_left_y`

  y coordinate of the top left corner

`bottom_right_x`

  x coordinate of the bottom right

`bottom_right_y`

  y coordinate of the bottom right

`rounding_x`

  x rounding

`rounding_y`

  y rounding

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::roundRectangle() example

`<?php
function roundRectangle($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $roundX, $roundY) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->roundRectangle($startX, $startY, $endX, $endY, $roundX, $roundY);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::scale

(PECL imagick 2, PECL imagick 3)

ImagickDraw::scale — Adjusts the scaling factor

### Description

public ImagickDraw::scale(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

### Parameters

`x`

  horizontal factor

`y`

  vertical factor

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::scale() example

`<?php
function scale($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(4);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$draw->setFillColor($fillModifiedColor);
$draw->scale(1.4, 1.4);
$draw->rectangle(200, 200, 300, 300);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipPath — Associates a named clipping path with the image

### Description

public ImagickDraw::setClipPath(string `$clip_mask`): bool
Warning

This function is currently not documented; only its argument list is available.

Associates a named clipping path with the image. Only the areas drawn on by the clipping path will be modified as long as it remains in effect.

### Parameters

`clip_mask`

  the clipping path name

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setClipPath() example

`<?php
function setClipPath($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$clipPathName = 'testClipPath';
$draw->pushClipPath($clipPathName);
$draw->rectangle(0, 0, 250, 250);
$draw->popClipPath();
$draw->setClipPath($clipPathName);
$draw->rectangle(100, 100, 400, 400);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setClipRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

### Description

public ImagickDraw::setClipRule(int `$fillrule`): bool
Warning

This function is currently not documented; only its argument list is available.

Set the polygon fill rule to be used by the clipping path.

### Parameters

`fillrule`

  One of the FILLRULE constant (`imagick::FILLRULE_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setClipRule() example

`<?php
function setClipRule($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
//\Imagick::FILLRULE_EVENODD
//\Imagick::FILLRULE_NONZERO
$clipPathName = 'testClipPath';
$draw->pushClipPath($clipPathName);
$draw->setClipRule(\Imagick::FILLRULE_EVENODD);
$draw->rectangle(0, 0, 300, 500);
$draw->rectangle(200, 0, 500, 500);
$draw->popClipPath();
$draw->setClipPath($clipPathName);
$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setClipUnits

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

### Description

public ImagickDraw::setClipUnits(int `$pathunits`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the interpretation of clip path units.

### Parameters

`pathunits`

  the number of clip units

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setClipUnits() example

`<?php
function setClipUnits($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$clipPathName = 'testClipPath';
$draw->setClipUnits(\Imagick::RESOLUTION_PIXELSPERINCH);
$draw->pushClipPath($clipPathName);
$draw->rectangle(0, 0, 250, 250);
$draw->popClipPath();
$draw->setClipPath($clipPathName);
//RESOLUTION_PIXELSPERINCH
//RESOLUTION_PIXELSPERCENTIMETER
$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFillAlpha

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

### Description

public ImagickDraw::setFillAlpha(float `$alpha`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

### Parameters

`alpha`

  fill alpha

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFillAlpha() example

`<?php
function setFillAlpha($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->rectangle(100, 200, 200, 300);
@$draw->setFillAlpha(0.4);
$draw->rectangle(300, 200, 400, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFillColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

### Description

public ImagickDraw::setFillColor(ImagickPixel|string `$fill_color`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the fill color to be used for drawing filled objects.

### Parameters

`fill_color`

  ImagickPixel to use to set the color

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFillColor()

`<?php
function setFillColor($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(1.5);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle(50, 50, 150, 150);
$draw->setFillColor("rgb(200, 32, 32)");
$draw->rectangle(200, 50, 300, 150);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setFillOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

### Description

public ImagickDraw::setFillOpacity(float `$opacity`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

### Parameters

`opacity`

  the fill opacity

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFillOpacity()

`<?php
function setFillOpacity($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->rectangle(100, 200, 200, 300);
$draw->setFillOpacity(0.4);
$draw->rectangle(300, 200, 400, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFillPatternURL

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

### Description

public ImagickDraw::setFillPatternURL(string `$fill_url`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.

### Parameters

`fill_url`

  URL to use to obtain fill pattern.

### Return Values

Returns `true` on success or `false` on failure.

# ImagickDraw::setFillRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

### Description

public ImagickDraw::setFillRule(int `$fillrule`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the fill rule to use while drawing polygons.

### Parameters

`fillrule`

  One of the FILLRULE constant (`imagick::FILLRULE_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFillRule() example

`<?php
function setFillRule($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$fillRules = [\Imagick::FILLRULE_NONZERO, \Imagick::FILLRULE_EVENODD];
$points = 11;
$size = 150;
$draw->translate(175, 160);
for ($x = 0; $x < 2; $x++) {
$draw->setFillRule($fillRules[$x]);
$draw->pathStart();
for ($n = 0; $n < $points * 2; $n++) {
if ($n >= $points) {
$angle = fmod($n * 360 * 4 / $points, 360) * pi() / 180;
}
else {
$angle = fmod($n * 360 * 3 / $points, 360) * pi() / 180;
}
$positionX = $size * sin($angle);
$positionY = $size * cos($angle);
if ($n == 0) {
$draw->pathMoveToAbsolute($positionX, $positionY);
}
else {
$draw->pathLineToAbsolute($positionX, $positionY);
}
}
$draw->pathClose();
$draw->pathFinish();
$draw->translate(325, 0);
}
$image = new \Imagick();
$image->newImage(700, 320, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setFont

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

### Description

public ImagickDraw::setFont(string `$font_name`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the fully-specified font to use when annotating with text.

### Parameters

`font_name`

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::setFont() example

`<?php
function setFont($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(36);
$draw->setFont("../fonts/Arial.ttf");
$draw->annotation(50, 50, "Lorem Ipsum!");
$draw->setFont("../fonts/Consolas.ttf");
$draw->annotation(50, 100, "Lorem Ipsum!");
$draw->setFont("../fonts/CANDY.TTF");
$draw->annotation(50, 150, "Lorem Ipsum!");
$draw->setFont("../fonts/Inconsolata-dz.otf");
$draw->annotation(50, 200, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(500, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFontFamily

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

### Description

public ImagickDraw::setFontFamily(string `$font_family`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the font family to use when annotating with text.

### Parameters

`font_family`

  the font family

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::setFontFamily() example

`<?php
function setFontFamily($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(48);
$draw->setFontFamily("Times");
$draw->annotation(50, 50, "Lorem Ipsum!");
$draw->setFontFamily("AvantGarde");
$draw->annotation(50, 100, "Lorem Ipsum!");
$draw->setFontFamily("NewCenturySchlbk");
$draw->annotation(50, 150, "Lorem Ipsum!");
$draw->setFontFamily("Palatino");
$draw->annotation(50, 200, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(450, 250, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFontSize

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

### Description

public ImagickDraw::setFontSize(float `$point_size`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the font pointsize to use when annotating with text.

### Parameters

`point_size`

  the point size

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFontSize() example

`<?php
function setFontSize($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFont("../fonts/Arial.ttf");
$sizes = [24, 36, 48, 60, 72];
foreach ($sizes as $size) {
$draw->setFontSize($size);
$draw->annotation(50, ($size * $size / 16), "Lorem Ipsum!");
}
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFontStretch

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

### Description

public ImagickDraw::setFontStretch(int `$stretch`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

### Parameters

`stretch`

  One of the STRETCH constant (`imagick::STRETCH_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFontStretch() example

`<?php
function setFontStretch($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(36);
$fontStretchTypes = [
\Imagick::STRETCH_ULTRACONDENSED,
\Imagick::STRETCH_CONDENSED,
\Imagick::STRETCH_SEMICONDENSED,
\Imagick::STRETCH_SEMIEXPANDED,
\Imagick::STRETCH_EXPANDED,
\Imagick::STRETCH_EXTRAEXPANDED,
\Imagick::STRETCH_ULTRAEXPANDED,
\Imagick::STRETCH_ANY
];
$offset = 0;
foreach ($fontStretchTypes as $fontStretch) {
$draw->setFontStretch($fontStretch);
$draw->annotation(50, 75 + $offset, "Lorem Ipsum!");
$offset += 50;
}
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFontStyle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

### Description

public ImagickDraw::setFontStyle(int `$style`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

### Parameters

`style`

  One of the STYLE constant (`imagick::STYLE_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setFontStyle() example

`<?php
function setFontStyle($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(36);
$draw->setFontStyle(\Imagick::STYLE_NORMAL);
$draw->annotation(50, 50, "Lorem Ipsum!");
$draw->setFontStyle(\Imagick::STYLE_ITALIC);
$draw->annotation(50, 100, "Lorem Ipsum!");
$draw->setFontStyle(\Imagick::STYLE_OBLIQUE);
$draw->annotation(50, 150, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(350, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setFontWeight

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontWeight — Sets the font weight

### Description

public ImagickDraw::setFontWeight(int `$weight`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the font weight to use when annotating with text.

### Parameters

`weight`

### Return Values

### Examples

Example #1 ImagickDraw::setFontWeight() example

`<?php
function setFontWeight($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(36);
$draw->setFontWeight(100);
$draw->annotation(50, 50, "Lorem Ipsum!");
$draw->setFontWeight(200);
$draw->annotation(50, 100, "Lorem Ipsum!");
$draw->setFontWeight(400);
$draw->annotation(50, 150, "Lorem Ipsum!");
$draw->setFontWeight(800);
$draw->annotation(50, 200, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setGravity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setGravity — Sets the text placement gravity

### Description

public ImagickDraw::setGravity(int `$gravity`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the text placement gravity to use when annotating with text.

### Parameters

`gravity`

  One of the GRAVITY constant (`imagick::GRAVITY_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setGravity() example

`<?php
function setGravity($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(24);
$gravitySettings = array(
\Imagick::GRAVITY_NORTHWEST => 'NorthWest',
\Imagick::GRAVITY_NORTH => 'North',
\Imagick::GRAVITY_NORTHEAST => 'NorthEast',
\Imagick::GRAVITY_WEST => 'West',
\Imagick::GRAVITY_CENTER => 'Centre',
\Imagick::GRAVITY_SOUTHWEST => 'SouthWest',
\Imagick::GRAVITY_SOUTH => 'South',
\Imagick::GRAVITY_SOUTHEAST => 'SouthEast',
\Imagick::GRAVITY_EAST => 'East'
);
$draw->setFont("../fonts/Arial.ttf");
foreach ($gravitySettings as $type => $description) {
$draw->setGravity($type);
$draw->annotation(50, 50, '"' . $description . '"');
}
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setResolution

(PECL imagick 3 >= 3.1.0)

ImagickDraw::setResolution — Sets the resolution

### Description

public ImagickDraw::setResolution(float `$resolution_x`, float `$resolution_y`): bool

Sets the resolution.

### Parameters

`resolution_x`

`resolution_y`

### Return Values

Returns `true` on success.

# ImagickDraw::setStrokeAlpha

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

### Description

public ImagickDraw::setStrokeAlpha(float `$alpha`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

### Parameters

`alpha`

  opacity

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeAlpha() example

`<?php
function setStrokeAlpha($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeOpacity(0.1);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

### Description

public ImagickDraw::setStrokeAntialias(bool `$enabled`): bool
Warning

This function is currently not documented; only its argument list is available.

Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

### Parameters

`enabled`

  the antialias setting

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeAntialias() example

`<?php
function setStrokeAntialias($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setStrokeAntialias(false);
$draw->line(100, 100, 400, 105);
$draw->line(100, 140, 400, 185);
$draw->setStrokeAntialias(true);
$draw->line(100, 110, 400, 115);
$draw->line(100, 150, 400, 195);
$image = new \Imagick();
$image->newImage(500, 250, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

### Description

public ImagickDraw::setStrokeColor(ImagickPixel|string `$color`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the color used for stroking object outlines.

### Parameters

`color`

  the stroke color

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeColor() example

`<?php
function setStrokeColor($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(5);
$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeOpacity(0.1);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeDashArray

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

### Description

public ImagickDraw::setStrokeDashArray(?array `$dashes`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the pattern of dashes and gaps used to stroke paths. The strokeDashArray represents an array of numbers that specify the lengths of alternating dashes and gaps in pixels. If an odd number of values is provided, then the list of values is repeated to yield an even number of values. To remove an existing dash array, pass a zero number_elements argument and null dash_array. A typical strokeDashArray_ array might contain the members 5 3 2.

### Parameters

`dashes`

  array of floats

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickDraw::setStrokeDashArray() example

`<?php
function setStrokeDashArray($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->setStrokeDashArray([10, 10]);
$draw->rectangle(100, 50, 225, 175);
$draw->setStrokeDashArray([20, 5, 20, 5, 5, 5,]);
$draw->rectangle(275, 50, 400, 175);
$draw->setStrokeDashArray([20, 5, 20, 5, 5]);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeDashArray([1, 1, 1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 13, 13, 21, 21, 34, 34, 55, 55, 89, 89, 144, 144, 233, 233, 377, 377, 610, 610, 987, 987, 1597, 1597, 2584, 2584, 4181, 4181,]);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeDashOffset

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

### Description

public ImagickDraw::setStrokeDashOffset(float `$dash_offset`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the offset into the dash pattern to start the dash.

### Parameters

`dash_offset`

  dash offset

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeDashOffset() example

`<?php
function setStrokeDashOffset($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->setStrokeDashArray([20, 20]);
$draw->setStrokeDashOffset(0);
$draw->rectangle(100, 50, 225, 175);
//Start the dash effect halfway through the solid portion
$draw->setStrokeDashOffset(10);
$draw->rectangle(275, 50, 400, 175);
//Start the dash effect on the space portion
$draw->setStrokeDashOffset(20);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeDashOffset(5);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeLineCap

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

### Description

public ImagickDraw::setStrokeLineCap(int `$linecap`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the end of open subpaths when they are stroked.

### Parameters

`linecap`

  One of the LINECAP constant (`imagick::LINECAP_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeLineCap() example

`<?php
function setStrokeLineCap($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(25);
$lineTypes = [\Imagick::LINECAP_BUTT, \Imagick::LINECAP_ROUND, \Imagick::LINECAP_SQUARE,];
$offset = 0;
foreach ($lineTypes as $lineType) {
$draw->setStrokeLineCap($lineType);
$draw->line(50 + $offset, 50, 50 + $offset, 250);
$offset += 50;
}
$imagick = new \Imagick();
$imagick->newImage(300, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setStrokeLineJoin

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

### Description

public ImagickDraw::setStrokeLineJoin(int `$linejoin`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

### Parameters

`linejoin`

  One of the LINEJOIN constant (`imagick::LINEJOIN_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeLineJoin() example

`<?php
function setStrokeLineJoin($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(20);
$offset = 220;
$lineJoinStyle = [
\Imagick::LINEJOIN_MITER,
\Imagick::LINEJOIN_ROUND,
\Imagick::LINEJOIN_BEVEL,
];
for ($x = 0; $x < count($lineJoinStyle); $x++) {
$draw->setStrokeLineJoin($lineJoinStyle[$x]);
$points = [
['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
['x' => 20 * 5, 'y' => 20 * 5 + $x * $offset],
['x' => 70 * 5, 'y' => 50 * 5 + $x * $offset],
['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
];
$draw->polyline($points);
}
$image = new \Imagick();
$image->newImage(500, 700, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeMiterLimit

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

### Description

public ImagickDraw::setStrokeMiterLimit(int `$miterlimit`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

### Parameters

`miterlimit`

  the miter limit

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeMiterLimit() example

`<?php
function setStrokeMiterLimit($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeOpacity(0.6);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(10);
$yOffset = 100;
$draw->setStrokeLineJoin(\Imagick::LINEJOIN_MITER);
for ($y = 0; $y < 3; $y++) {
$draw->setStrokeMiterLimit(40 * $y);
$points = [
['x' => 22 * 3, 'y' => 15 * 4 + $y * $yOffset],
['x' => 20 * 3, 'y' => 20 * 4 + $y * $yOffset],
['x' => 70 * 5, 'y' => 45 * 4 + $y * $yOffset],
];
$draw->polygon($points);
}
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
$image->setImageType(\Imagick::IMGTYPE_PALETTE);
$image->setImageCompressionQuality(100);
$image->stripImage();
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokeOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

### Description

public ImagickDraw::setStrokeOpacity(float `$opacity`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

### Parameters

`opacity`

  stroke opacity. 1.0 is fully opaque

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeOpacity() example

`<?php
function setStrokeOpacity($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(10);
$draw->setStrokeOpacity(1);
$draw->line(100, 80, 400, 125);
$draw->rectangle(25, 200, 150, 350);
$draw->setStrokeOpacity(0.5);
$draw->line(100, 100, 400, 145);
$draw->rectangle(200, 200, 325, 350);
$draw->setStrokeOpacity(0.2);
$draw->line(100, 120, 400, 165);
$draw->rectangle(375, 200, 500, 350);
$image = new \Imagick();
$image->newImage(550, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setStrokePatternURL

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

### Description

public ImagickDraw::setStrokePatternURL(string `$stroke_url`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the pattern used for stroking object outlines.

### Parameters

`stroke_url`

  stroke URL

### Return Values

Returns `true` on success.

# ImagickDraw::setStrokeWidth

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

### Description

public ImagickDraw::setStrokeWidth(float `$width`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the width of the stroke used to draw object outlines.

### Parameters

`width`

  stroke width

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setStrokeWidth() example

`<?php
function setStrokeWidth($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeWidth(5);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::setTextAlignment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextAlignment — Specifies a text alignment

### Description

public ImagickDraw::setTextAlignment(int `$align`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies a text alignment to be applied when annotating with text.

### Parameters

`align`

  One of the ALIGN constant (`imagick::ALIGN_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setTextAlignment() example

`<?php
function setTextAlignment($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(36);
$draw->setTextAlignment(\Imagick::ALIGN_LEFT);
$draw->annotation(250, 75, "Lorem Ipsum!");
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$draw->annotation(250, 150, "Lorem Ipsum!");
$draw->setTextAlignment(\Imagick::ALIGN_RIGHT);
$draw->annotation(250, 225, "Lorem Ipsum!");
$draw->line(250, 0, 250, 500);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setTextAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

### Description

public ImagickDraw::setTextAntialias(bool `$antialias`): bool
Warning

This function is currently not documented; only its argument list is available.

Controls whether text is antialiased. Text is antialiased by default.

### Parameters

`antialias`

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setTextAntialias() example

`<?php
function setTextAntialias($fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor('none');
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(32);
$draw->setTextAntialias(false);
$draw->annotation(5, 30, "Lorem Ipsum!");
$draw->setTextAntialias(true);
$draw->annotation(5, 65, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(220, 80, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
//Scale the image so that people can see the aliasing.
$imagick->scaleImage(220 * 6, 80 * 6);
$imagick->cropImage(640, 480, 0, 0);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setTextDecoration

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextDecoration — Specifies a decoration

### Description

public ImagickDraw::setTextDecoration(int `$decoration`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies a decoration to be applied when annotating with text.

### Parameters

`decoration`

  One of the DECORATION constant (`imagick::DECORATION_*`).

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setTextDecoration() example

`<?php
function setTextDecoration($strokeColor, $fillColor, $backgroundColor, $textDecoration) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->setTextDecoration($textDecoration);
$draw->annotation(50, 75, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(500, 200, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setTextEncoding

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextEncoding — Specifies the text code set

### Description

public ImagickDraw::setTextEncoding(string `$encoding`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

### Parameters

`encoding`

  the encoding name

### Return Values

No value is returned.

# ImagickDraw::setTextInterlineSpacing

(PECL imagick 3 >= 3.1.0)

ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing

### Description

public ImagickDraw::setTextInterlineSpacing(float `$spacing`): bool

Sets the text interline spacing.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`spacing`

### Return Values

Returns `true` on success.

# ImagickDraw::setTextInterwordSpacing

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing

### Description

public ImagickDraw::setTextInterwordSpacing(float `$spacing`): bool

Sets the text interword spacing.

### Parameters

`spacing`

### Return Values

Returns `true` on success.

# ImagickDraw::setTextKerning

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickDraw::setTextKerning — Sets the text kerning

### Description

public ImagickDraw::setTextKerning(float `$kerning`): bool

Sets the text kerning

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`kerning`

### Return Values

Returns `true` on success.

# ImagickDraw::setTextUnderColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

### Description

public ImagickDraw::setTextUnderColor(ImagickPixel|string `$under_color`): bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the color of a background rectangle to place under text annotations.

### Parameters

`under_color`

  the under color

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setTextUnderColor() example

`<?php
function setTextUnderColor($strokeColor, $fillColor, $backgroundColor, $textUnderColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->annotation(50, 75, "Lorem Ipsum!");
$draw->setTextUnderColor($textUnderColor);
$draw->annotation(50, 175, "Lorem Ipsum!");
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setVectorGraphics — Sets the vector graphics

### Description

public ImagickDraw::setVectorGraphics(string `$xml`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the vector graphics associated with the specified ImagickDraw object. Use this method with ImagickDraw::getVectorGraphics() as a method to persist the vector graphics state.

### Parameters

`xml`

  xml containing the vector graphics

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 ImagickDraw::setVectorGraphics() example

`<?php
function setVectorGraphics() {
//Setup a draw object with some drawing in it.
$draw = new \ImagickDraw();
$draw->setFillColor("red");
$draw->circle(20, 20, 50, 50);
$draw->setFillColor("blue");
$draw->circle(50, 70, 50, 50);
$draw->rectangle(50, 120, 80, 150);
//Get the drawing as a string
$SVG = $draw->getVectorGraphics();
//$svg is a string, and could be saved anywhere a string can be saved
//Use the saved drawing to generate a new draw object
$draw2 = new \ImagickDraw();
//Apparently the SVG text is missing the root element.
$draw2->setVectorGraphics("<root>".$SVG."</root>");
$imagick = new \Imagick();
$imagick->newImage(200, 200, 'white');
$imagick->setImageFormat("png");
$imagick->drawImage($draw2);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::setViewbox

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setViewbox — Sets the overall canvas size

### Description

public ImagickDraw::setViewbox(
int `$left_x`,
int `$top_y`,
int `$right_x`,
int `$bottom_y`
): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

### Parameters

`left_x`

  left x coordinate

`top_y`

  left y coordinate

`right_x`

  right x coordinate

`bottom_y`

  right y coordinate

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::setViewBox() example

`<?php
function setViewBox($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
/*
Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.
*/
$draw->circle(250, 250, 250, 0);
$draw->setviewbox(0, 0, 200, 200);
$draw->circle(125, 250, 250, 250);
$draw->translate(250, 125);
$draw->circle(0, 0, 125, 0);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickDraw::skewX

(PECL imagick 2, PECL imagick 3)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

### Description

public ImagickDraw::skewX(float `$degrees`): bool
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the horizontal direction.

### Parameters

`degrees`

  degrees to skew

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::skewX() example

`<?php
function skewX($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $skew) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);
$draw->setFillColor($fillModifiedColor);
$draw->skewX($skew);
$draw->rectangle($startX, $startY, $endX, $endY);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::skewY

(PECL imagick 2, PECL imagick 3)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

### Description

public ImagickDraw::skewY(float `$degrees`): bool
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the vertical direction.

### Parameters

`degrees`

  degrees to skew

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::skewY() example

`<?php
function skewY($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $skew) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);
$draw->setFillColor($fillModifiedColor);
$draw->skewY($skew);
$draw->rectangle($startX, $startY, $endX, $endY);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickDraw::translate

(PECL imagick 2, PECL imagick 3)

ImagickDraw::translate — Applies a translation to the current coordinate system

### Description

public ImagickDraw::translate(float `$x`, float `$y`): bool
Warning

This function is currently not documented; only its argument list is available.

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

### Parameters

`x`

  horizontal translation

`y`

  vertical translation

### Return Values

No value is returned.

### Examples

Example #1 ImagickDraw::translate() example

`<?php
function translate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $translateX, $translateY) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);
$draw->setFillColor($fillModifiedColor);
$draw->translate($translateX, $translateY);
$draw->rectangle($startX, $startY, $endX, $endY);
$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

## Table of Contents

- ImagickDraw::affine — Adjusts the current affine transformation matrix
- ImagickDraw::annotation — Draws text on the image
- ImagickDraw::arc — Draws an arc
- ImagickDraw::bezier — Draws a bezier curve
- ImagickDraw::circle — Draws a circle
- ImagickDraw::clear — Clears the ImagickDraw
- ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
- ImagickDraw::color — Draws color on image
- ImagickDraw::comment — Adds a comment
- ImagickDraw::composite — Composites an image onto the current image
- ImagickDraw::__construct — The ImagickDraw constructor
- ImagickDraw::destroy — Frees all associated resources
- ImagickDraw::ellipse — Draws an ellipse on the image
- ImagickDraw::getClipPath — Obtains the current clipping path ID
- ImagickDraw::getClipRule — Returns the current polygon fill rule
- ImagickDraw::getClipUnits — Returns the interpretation of clip path units
- ImagickDraw::getFillColor — Returns the fill color
- ImagickDraw::getFillOpacity — Returns the opacity used when drawing
- ImagickDraw::getFillRule — Returns the fill rule
- ImagickDraw::getFont — Returns the font
- ImagickDraw::getFontFamily — Returns the font family
- ImagickDraw::getFontSize — Returns the font pointsize
- ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text
- ImagickDraw::getFontStyle — Returns the font style
- ImagickDraw::getFontWeight — Returns the font weight
- ImagickDraw::getGravity — Returns the text placement gravity
- ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
- ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
- ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
- ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
- ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
- ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
- ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
- ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
- ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
- ImagickDraw::getTextAlignment — Returns the text alignment
- ImagickDraw::getTextAntialias — Returns the current text antialias setting
- ImagickDraw::getTextDecoration — Returns the text decoration
- ImagickDraw::getTextEncoding — Returns the code set used for text annotations
- ImagickDraw::getTextInterlineSpacing — Gets the text interline spacing
- ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing
- ImagickDraw::getTextKerning — Gets the text kerning
- ImagickDraw::getTextUnderColor — Returns the text under color
- ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
- ImagickDraw::line — Draws a line
- ImagickDraw::matte — Paints on the image's opacity channel
- ImagickDraw::pathClose — Adds a path element to the current path
- ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
- ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
- ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
- ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
- ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
- ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
- ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
- ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
- ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
- ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
- ImagickDraw::pathFinish — Terminates the current path
- ImagickDraw::pathLineToAbsolute — Draws a line path
- ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
- ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
- ImagickDraw::pathLineToRelative — Draws a line path
- ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
- ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
- ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
- ImagickDraw::pathMoveToRelative — Starts a new sub-path
- ImagickDraw::pathStart — Declares the start of a path drawing list
- ImagickDraw::point — Draws a point
- ImagickDraw::polygon — Draws a polygon
- ImagickDraw::polyline — Draws a polyline
- ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
- ImagickDraw::popClipPath — Terminates a clip path definition
- ImagickDraw::popDefs — Terminates a definition list
- ImagickDraw::popPattern — Terminates a pattern definition
- ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
- ImagickDraw::pushClipPath — Starts a clip path definition
- ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
- ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
- ImagickDraw::rectangle — Draws a rectangle
- ImagickDraw::render — Renders all preceding drawing commands onto the image
- ImagickDraw::resetVectorGraphics — Resets the vector graphics
- ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
- ImagickDraw::roundRectangle — Draws a rounded rectangle
- ImagickDraw::scale — Adjusts the scaling factor
- ImagickDraw::setClipPath — Associates a named clipping path with the image
- ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
- ImagickDraw::setClipUnits — Sets the interpretation of clip path units
- ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
- ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
- ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
- ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
- ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
- ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
- ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
- ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
- ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
- ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
- ImagickDraw::setFontWeight — Sets the font weight
- ImagickDraw::setGravity — Sets the text placement gravity
- ImagickDraw::setResolution — Sets the resolution
- ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
- ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
- ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
- ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
- ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
- ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
- ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
- ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
- ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
- ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
- ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
- ImagickDraw::setTextAlignment — Specifies a text alignment
- ImagickDraw::setTextAntialias — Controls whether text is antialiased
- ImagickDraw::setTextDecoration — Specifies a decoration
- ImagickDraw::setTextEncoding — Specifies the text code set
- ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing
- ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing
- ImagickDraw::setTextKerning — Sets the text kerning
- ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
- ImagickDraw::setVectorGraphics — Sets the vector graphics
- ImagickDraw::setViewbox — Sets the overall canvas size
- ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
- ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
- ImagickDraw::translate — Applies a translation to the current coordinate system

# The ImagickDrawException class

(PECL imagick 3)

## Introduction

## Class synopsis

class ImagickDrawException extends Exception implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
/* Inherited methods */
}

# The ImagickException class

(PECL imagick 3)

## Introduction

## Class synopsis

class ImagickException extends Exception implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
/* Inherited methods */
}

# The ImagickKernel class

(PECL imagick >= 3.3.0)

## Introduction

## Class synopsis

class ImagickKernel {
/* Methods */
public addKernel(ImagickKernel `$ImagickKernel`): void
public addUnityKernel(float `$scale`): void
public static fromBuiltin(int `$kernelType`, string `$kernelString`): ImagickKernel
public static fromMatrix(array `$matrix`, array `$origin` = ?): ImagickKernel
public getMatrix(): array
public scale(float `$scale`, int `$normalizeFlag` = ?): void
public separate(): array
}

# ImagickKernel::addKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addKernel — Attach another kernel to a kernel list

### Description

public ImagickKernel::addKernel(ImagickKernel `$ImagickKernel`): void

Attach another kernel to this kernel to allow them to both be applied in a single morphology or filter function. Returns the new combined kernel.

### Parameters

`ImagickKernel`

### Return Values

### Examples

Example #1 ImagickKernel::addKernel()

`<?php
function addKernel($imagePath) {
$matrix1 = [
[-1, -1, -1],
[ 0, 0, 0],
[ 1, 1, 1],
];
$matrix2 = [
[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1],
];
$kernel1 = ImagickKernel::fromMatrix($matrix1);
$kernel2 = ImagickKernel::fromMatrix($matrix2);
$kernel1->addKernel($kernel2);
$imagick = new \Imagick(realpath($imagePath));
$imagick->filter($kernel1);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# ImagickKernel::addUnityKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list

### Description

public ImagickKernel::addUnityKernel(float `$scale`): void

Adds a given amount of the 'Unity' Convolution Kernel to the given pre-scaled and normalized Kernel. This in effect adds that amount of the original image into the resulting convolution kernel. The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp kernels or into sharpening kernels.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 ImagickKernel::addUnityKernel()

`<?php
function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";
foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
return $output;
}
$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];
$kernel = \ImagickKernel::fromMatrix($matrix);
$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
$output = "Before adding unity kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());
$kernel->addUnityKernel(0.5);
$output .= "After adding unity kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());
$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
$output .= "After renormalizing kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());
echo $output;
?>`

Example #2 ImagickKernel::addUnityKernel()

`<?php
function addUnityKernel($imagePath) {
$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];
$kernel = ImagickKernel::fromMatrix($matrix);
$kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
$kernel->addUnityKernel(0.5);
$imagick = new \Imagick(realpath($imagePath));
$imagick->filter($kernel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>`

# ImagickKernel::fromBuiltIn

(PECL imagick >= 3.3.0)

ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel

### Description

public static ImagickKernel::fromBuiltin(int `$kernelType`, string `$kernelString`): ImagickKernel

Create a kernel from a builtin in kernel. See http://www.imagemagick.org/Usage/morphology/#kernel for examples. Currently the 'rotation' symbols are not supported. Example: $diamondKernel = ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "2");

### Parameters

`kerneltype`

  The type of kernel to build e.g. \Imagick::KERNEL_DIAMOND

`kernelString`

  A string that describes the parameters e.g. "4,2.5"

### Return Values

### Examples

Example #1 ImagickKernel::fromBuiltin()

`<?php
function renderKernel(ImagickKernel $imagickKernel) {
$matrix = $imagickKernel->getMatrix();
$imageMargin = 20;
$tileSize = 20;
$tileSpace = 4;
$shadowSigma = 4;
$shadowDropX = 20;
$shadowDropY = 0;
$radius = ($tileSize / 2) * 0.9;
$rows = count($matrix);
$columns = count($matrix[0]);
$imagickDraw = new \ImagickDraw();
$imagickDraw->setFillColor('#afafaf');
$imagickDraw->setStrokeColor('none');
$imagickDraw->translate($imageMargin, $imageMargin);
$imagickDraw->push();
ksort($matrix);
foreach ($matrix as $row) {
ksort($row);
$imagickDraw->push();
foreach ($row as $cell) {
if ($cell !== false) {
$color = intval(255 * $cell);
$colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
$imagickDraw->setFillColor($colorString);
$imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
}
$imagickDraw->translate(($tileSize + $tileSpace), 0);
}
$imagickDraw->pop();
$imagickDraw->translate(0, ($tileSize + $tileSpace));
}
$imagickDraw->pop();
$width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
$height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);
$imagickDraw->push();
$imagickDraw->translate($width/2 , $height/2);
$imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
$imagickDraw->setStrokeColor('white');
$imagickDraw->circle(0, 0, $radius - 1, 0);
$imagickDraw->setStrokeColor('black');
$imagickDraw->circle(0, 0, $radius, 0);
$imagickDraw->pop();
$canvasWidth = $width + (2 * $imageMargin);
$canvasHeight = $height + (2 * $imageMargin);
$kernel = new \Imagick();
$kernel->newPseudoImage(
$canvasWidth,
$canvasHeight,
'canvas:none'
);
$kernel->setImageFormat('png');
$kernel->drawImage($imagickDraw);
/* create drop shadow on it's own layer */
$canvas = $kernel->clone();
$canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
$canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);
$canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
$canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);
/* composite original text_layer onto shadow_layer */
$canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
$canvas->setImageFormat('png');
return $canvas;
}
function createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
$string = '';
if ($kernelFirstTerm != false && strlen(trim($kernelFirstTerm)) != 0) {
$string .= $kernelFirstTerm;
if ($kernelSecondTerm != false && strlen(trim($kernelSecondTerm)) != 0) {
$string .= ','.$kernelSecondTerm;
if ($kernelThirdTerm != false && strlen(trim($kernelThirdTerm)) != 0) {
$string .= ','.$kernelThirdTerm;
}
}
}
$kernel = ImagickKernel::fromBuiltIn(
$kernelType,
$string
);
return $kernel;
}
function fromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
$diamondKernel = createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm);
$imagick = renderKernel($diamondKernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
fromBuiltin(\Imagick::KERNEL_DIAMOND, 2, false, false);
?>`

# ImagickKernel::fromMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values

### Description

public static ImagickKernel::fromMatrix(array `$matrix`, array `$origin` = ?): ImagickKernel

Create a kernel from an 2d matrix of values. Each value should either be a float (if the element should be used) or 'false' if the element should be skipped. For matrices that are odd sizes in both dimensions the origin pixel will default to the centre of the kernel. For all other kernel sizes the origin pixel must be specified.

### Parameters

`array`

  A matrix (i.e. 2d array) of values that define the kernel. Each element should be either a float value, or FALSE if that element shouldn't be used by the kernel.

`array`

  Which element of the kernel should be used as the origin pixel. e.g. For a 3x3 matrix specifying the origin as [2, 2] would specify that the bottom right element should be the origin pixel.

### Return Values

The generated ImagickKernel.

### Examples

Example #1 ImagickKernel::fromMatrix()

`<?php
function renderKernel(ImagickKernel $imagickKernel) {
$matrix = $imagickKernel->getMatrix();
$imageMargin = 20;
$tileSize = 20;
$tileSpace = 4;
$shadowSigma = 4;
$shadowDropX = 20;
$shadowDropY = 0;
$radius = ($tileSize / 2) * 0.9;
$rows = count($matrix);
$columns = count($matrix[0]);
$imagickDraw = new \ImagickDraw();
$imagickDraw->setFillColor('#afafaf');
$imagickDraw->setStrokeColor('none');
$imagickDraw->translate($imageMargin, $imageMargin);
$imagickDraw->push();
ksort($matrix);
foreach ($matrix as $row) {
ksort($row);
$imagickDraw->push();
foreach ($row as $cell) {
if ($cell !== false) {
$color = intval(255 * $cell);
$colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
$imagickDraw->setFillColor($colorString);
$imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
}
$imagickDraw->translate(($tileSize + $tileSpace), 0);
}
$imagickDraw->pop();
$imagickDraw->translate(0, ($tileSize + $tileSpace));
}
$imagickDraw->pop();
$width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
$height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);
$imagickDraw->push();
$imagickDraw->translate($width/2 , $height/2);
$imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
$imagickDraw->setStrokeColor('white');
$imagickDraw->circle(0, 0, $radius - 1, 0);
$imagickDraw->setStrokeColor('black');
$imagickDraw->circle(0, 0, $radius, 0);
$imagickDraw->pop();
$canvasWidth = $width + (2 * $imageMargin);
$canvasHeight = $height + (2 * $imageMargin);
$kernel = new \Imagick();
$kernel->newPseudoImage(
$canvasWidth,
$canvasHeight,
'canvas:none'
);
$kernel->setImageFormat('png');
$kernel->drawImage($imagickDraw);
/* create drop shadow on it's own layer */
$canvas = $kernel->clone();
$canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
$canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);
$canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
$canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);
/* composite original text_layer onto shadow_layer */
$canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
$canvas->setImageFormat('png');
return $canvas;
}
function createFromMatrix() {
$matrix = [
[0.5, 0, 0.2],
[0, 1, 0],
[0.9, 0, false],
];
$kernel = \ImagickKernel::fromMatrix($matrix);
return $kernel;
}
function fromMatrix() {
$kernel = createFromMatrix();
$imagick = renderKernel($kernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>`

# ImagickKernel::getMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel

### Description

public ImagickKernel::getMatrix(): array

Get the 2d matrix of values used in this kernel. The elements are either float for elements that are used or 'false' if the element should be skipped.

### Parameters

This function has no parameters.

### Return Values

A matrix (2d array) of the values that represent the kernel.

### Examples

Example #1 ImagickKernel::getMatrix()

`<?php
function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";
foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
return $output;
}
$output = "The built-in kernel name 'ring' with parameters of '2,3.5':<br/>";
$kernel = \ImagickKernel::fromBuiltIn(
\Imagick::KERNEL_RING,
"2,3.5"
);
$matrix = $kernel->getMatrix();
$output .= renderKernelTable($matrix);
echo $output;
?>`

# ImagickKernel::scale

(PECL imagick >= 3.3.0)

ImagickKernel::scale — Scales a kernel list by the given amount

### Description

public ImagickKernel::scale(float `$scale`, int `$normalizeFlag` = ?): void

Scales the given kernel list by the given amount, with or without normalization of the sum of the kernel values (as per given flags). The exact behaviour of this function depends on the normalization type being used please see http://www.imagemagick.org/api/morphology.php#ScaleKernelInfo for details.

### Parameters

`scale`

`normalizeFlag`

  - Imagick::NORMALIZE_KERNEL_NONE
  - Imagick::NORMALIZE_KERNEL_VALUE
  - Imagick::NORMALIZE_KERNEL_CORRELATE
  - Imagick::NORMALIZE_KERNEL_PERCENT

### Return Values

### Examples

Example #1 ImagickKernel::scale()

`<?php
function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";
foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
return $output;
}
$output = "";
$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];
$kernel = \ImagickKernel::fromMatrix($matrix);
$kernelClone = clone $kernel;
$output .= "Start kernel<br/>";
$output .= renderKernelTable($kernel->getMatrix());
$output .= "Scaling with NORMALIZE_KERNEL_VALUE. The <br/>";
$kernel->scale(2, \Imagick::NORMALIZE_KERNEL_VALUE);
$output .= renderKernelTable($kernel->getMatrix());
$kernel = clone $kernelClone;
$output .= "Scaling by percent<br/>";
$kernel->scale(2, \Imagick::NORMALIZE_KERNEL_PERCENT);
$output .= renderKernelTable($kernel->getMatrix());
$matrix2 = [
[-1, -1, 1],
[ -1, false, 1],
[1, 1, 1],
];
$kernel = \ImagickKernel::fromMatrix($matrix2);
$output .= "Scaling by correlate<br/>";
$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_CORRELATE);
$output .= renderKernelTable($kernel->getMatrix());
return $output;
?>`

# ImagickKernel::separate

(PECL imagick >= 3.3.0)

ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels

### Description

public ImagickKernel::separate(): array

Separates a linked set of kernels and returns an array of ImagickKernels.

### Parameters

This function has no parameters.

### Return Values

### Examples

Example #1 ImagickKernel::separate()

`<?php
function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";
foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
return $output;
}
$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];
$kernel = \ImagickKernel::fromMatrix($matrix);
$kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
$diamondKernel = \ImagickKernel::fromBuiltIn(
\Imagick::KERNEL_DIAMOND,
"2"
);
$kernel->addKernel($diamondKernel);
$kernelList = $kernel->separate();
$output = '';
$count = 0;
foreach ($kernelList as $kernel) {
$output .= "<br/>Kernel $count<br/>";
$output .= renderKernelTable($kernel->getMatrix());
$count++;
}
return $output;
?>`

## Table of Contents

- ImagickKernel::addKernel — Attach another kernel to a kernel list
- ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list
- ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel
- ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values
- ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel
- ImagickKernel::scale — Scales a kernel list by the given amount
- ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels

# The ImagickKernelException class

(PECL imagick 3)

## Introduction

## Class synopsis

class ImagickKernelException extends Exception {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
/* Inherited methods */
}

# The ImagickPixel class

(PECL imagick 2, PECL imagick 3)

## Class synopsis

class ImagickPixel {
public clear(): bool
public __construct(string `$color` = ?)
public destroy(): bool
public getColor(int `$normalized` = 0): array
public getColorAsString(): string
public getColorCount(): int
public getColorQuantum(): array
public getColorValue(int `$color`): float
public getColorValueQuantum(int `$color`): int|float
public getHSL(): array
public getIndex(): int
public isPixelSimilar(ImagickPixel `$color`, float `$fuzz`): bool
public isPixelSimilarQuantum(string `$color`, string `$fuzz` = ?): bool
public isSimilar(ImagickPixel `$color`, float `$fuzz`): bool
public setColor(string `$color`): bool
public setcolorcount(int `$colorCount`): bool
public setColorValue(int `$color`, float `$value`): bool
public setColorValueQuantum(int `$color`, int|float `$value`): bool
public setHSL(float `$hue`, float `$saturation`, float `$luminosity`): bool
public setIndex(int `$index`): bool
}

# ImagickPixel::clear

(PECL imagick 2, PECL imagick 3)

ImagickPixel::clear — Clears resources associated with this object

### Description

public ImagickPixel::clear(): bool
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

### Return Values

Returns `true` on success.

# ImagickPixel::__construct

(PECL imagick 2, PECL imagick 3)

ImagickPixel::__construct — The ImagickPixel constructor

### Description

public ImagickPixel::__construct(string `$color` = ?)
Warning

This function is currently not documented; only its argument list is available.

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

### Parameters

`color`

  The optional color string to use as the initial value of this object.

### Return Values

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

### Examples

Example #1 ImagickPixel::construct()

`<?php
function construct() {
$columns = 4;
$exampleColors = array(
"rgba(100%, 0%, 0%, 0.5)",
"hsb(33.3333%, 100%, 75%)", // medium green
"hsl(120, 255, 191.25)", //medium green
"graya(50%, 0.5)", // semi-transparent mid gray
"LightCoral", "none", //"cmyk(0.9, 0.48, 0.83, 0.50)",
"#f00", // #rgb
"#ff0000", // #rrggbb
"#ff0000ff", // #rrggbbaa
"#ffff00000000", // #rrrrggggbbbb
"#ffff00000000ffff", // #rrrrggggbbbbaaaa
"rgb(255, 0, 0)", // an integer in the range 0—255 for each component
"rgb(100.0%, 0.0%, 0.0%)", // a float in the range 0—100% for each component
"rgb(255, 0, 0)", // range 0 - 255
"rgba(255, 0, 0, 1.0)", // the same, with an explicit alpha value
"rgb(100%, 0%, 0%)", // range 0.0% - 100.0%
"rgba(100%, 0%, 0%, 1.0)", // the same, with an explicit alpha value
);
$draw = new \ImagickDraw();
$count = 0;
$black = new \ImagickPixel('rgb(0, 0, 0)');
foreach ($exampleColors as $exampleColor) {
$color = new \ImagickPixel($exampleColor);
$draw->setstrokewidth(1.0);
$draw->setStrokeColor($black);
$draw->setFillColor($color);
$offsetX = ($count % $columns) * 50 + 5;
$offsetY = intval($count / $columns) * 50 + 5;
$draw->rectangle(0 + $offsetX, 0 + $offsetY, 40 + $offsetX, 40 + $offsetY);
$count++;
}
$image = new \Imagick();
$image->newImage(350, 350, "blue");
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickPixel::destroy

(PECL imagick 2, PECL imagick 3)

ImagickPixel::destroy — Deallocates resources associated with this object

### Description

public ImagickPixel::destroy(): bool
Warning

This function is currently not documented; only its argument list is available.

Deallocates any resources used by the ImagickPixel object, and unsets any associated color. The object should not be used after the destroy function has been called.

### Return Values

Returns `true` on success.

# ImagickPixel::getColor

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColor — Returns the color

### Description

public ImagickPixel::getColor(int `$normalized` = 0): array

Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

### Parameters

`normalized`

  Normalize the color values. Possible values are `0`, `1` or `2`.

  List of possible values for `normalized`
  `normalized` | Description
  --- | ---
  `0` | The RGB values are returned as ints in the range `0` to `255` (inclusive.) The alpha value is returned as int and is either `0` or `1`.
  `1` | The RGBA values are returned as floats in the range `0` to `1` (inclusive.)
  `2` | The RGBA values are returned as ints in the range `0` to `255` (inclusive.)

### Return Values

An array of channel values. Throws ImagickPixelException on error.

### Examples

Example #1 Basic Imagick::getColor() usage

`<?php
//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');
//Set the color to have an alpha of 25%
$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);
$colorInfo = $color->getColor();
echo "Standard values".PHP_EOL;
print_r($colorInfo);
$colorInfo = $color->getColor(1);
echo "Normalized values:".PHP_EOL;
print_r($colorInfo);
?>`

The above example will output:

    Standard values
    Array
    (
        [r] => 165
        [g] => 42
        [b] => 42
        [a] => 0
    )
    Normalized values:
    Array
    (
        [r] => 0.64705882352941
        [g] => 0.16470588235294
        [b] => 0.16470588235294
        [a] => 0.25000381475547
    )

# ImagickPixel::getColorAsString

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

ImagickPixel::getColorAsString — Returns the color as a string

### Description

public ImagickPixel::getColorAsString(): string

Returns the color of the ImagickPixel object as a string.

### Parameters

This function has no parameters.

### Return Values

Returns the color of the ImagickPixel object as a string.

### Examples

Example #1 Basic Imagick::getColorAsString() usage

`<?php
//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');
$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);
$colorInfo = $color->getColorAsString();
print_r($colorInfo);
?>`

The above example will output:

    rgb(165,42,42)

### Notes

> Note: Alpha not returned

> This function does not return the alpha value of the color in the string.

# ImagickPixel::getColorCount

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColorCount — Returns the color count associated with this color

### Description

public ImagickPixel::getColorCount(): int

Returns the color count associated with this color.

The color count is the number of pixels in the image that have the same color as this ImagickPixel.

ImagickPixel::getColorCount appears to only work for ImagickPixel objects created through Imagick::getImageHistogram()

### Parameters

This function has no parameters.

### Return Values

Returns the color count as an integer on success, throws ImagickPixelException on failure.

### Examples

Example #1 ImagickPixel getColorCount()

`<?php
$imagick = new \Imagick();
$imagick->newPseudoImage(640, 480, "magick:logo");
$histogramElements = $imagick->getImageHistogram();
$lastColor = array_pop($histogramElements);
echo "Last pixel color count is: ".$lastColor->getColorCount();
?>`

The output for this will be similar to:

    Last pixel color count is: 256244

# ImagickPixel::getColorQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values

### Description

public ImagickPixel::getColorQuantum(): array

Returns the color of the pixel in an array as Quantum values. If ImageMagick was compiled as HDRI these will be floats, otherwise they will be integers.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

Returns an array with keys `"r"`, `"g"`, `"b"`, `"a"`.

# ImagickPixel::getColorValue

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

### Description

public ImagickPixel::getColorValue(int `$color`): float

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

### Parameters

`color`

  The color to get the value of, specified as one of the Imagick color constants. This can be one of the RGB colors, CMYK colors, alpha and opacity e.g (Imagick::COLOR_BLUE, Imagick::COLOR_MAGENTA).

### Return Values

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

### Examples

Example #1 Basic Imagick::getColorValue() usage

`<?php
$color = new ImagickPixel('rgba(90%, 20%, 20%, 0.75)');
echo "Alpha value is ".$color->getColorValue(Imagick::COLOR_ALPHA).PHP_EOL;
echo "".PHP_EOL;
echo "Red value is ".$color->getColorValue(Imagick::COLOR_RED).PHP_EOL;
echo "Green value is ".$color->getColorValue(Imagick::COLOR_GREEN).PHP_EOL;
echo "Blue value is ".$color->getColorValue(Imagick::COLOR_BLUE).PHP_EOL;
echo "".PHP_EOL;
echo "Cyan value is ".$color->getColorValue(Imagick::COLOR_CYAN).PHP_EOL;
echo "Magenta value is ".$color->getColorValue(Imagick::COLOR_MAGENTA).PHP_EOL;
echo "Yellow value is ".$color->getColorValue(Imagick::COLOR_YELLOW).PHP_EOL;
echo "Black value is ".$color->getColorValue(Imagick::COLOR_BLACK).PHP_EOL;
?>`

The above example will output:

    Alpha value is 0.74999618524453

    Red value is 0.90000762951095
    Green value is 0.2
    Blue value is 0.2

    Cyan value is 0.90000762951095
    Magenta value is 0.2
    Yellow value is 0.2
    Black value is 0

# ImagickPixel::getColorValueQuantum

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel

### Description

public ImagickPixel::getColorValueQuantum(int `$color`): int|float

Gets the quantum value of a color in the ImagickPixel. Return value is a float if ImageMagick was compiled with HDRI, otherwise an integer.

### Parameters

This function has no parameters.

### Return Values

The quantum value of the color element. Float if ImageMagick was compiled with HDRI, otherwise an int.

### Examples

Example #1 ImagickPixel::getColorValueQuantum()

`<?php
$color = new \ImagickPixel('rgb(128, 5, 255)');
$colorRed = $color->getColorValueQuantum(\Imagick::COLOR_RED);
$colorGreen = $color->getColorValueQuantum(\Imagick::COLOR_GREEN);
$colorBlue = $color->getColorValueQuantum(\Imagick::COLOR_BLUE);
$colorAlpha = $color->getColorValueQuantum(\Imagick::COLOR_ALPHA);
printf(
"Red: %s Green: %s Blue %s Alpha: %s",
$colorRed,
$colorGreen,
$colorBlue,
$colorAlpha
);
?>`

# ImagickPixel::getHSL

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

### Description

public ImagickPixel::getHSL(): array

Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.

### Parameters

This function has no parameters.

### Return Values

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

### Examples

Example #1 Basic Imagick::getHSL() example

`<?php
$color = new ImagickPixel('rgb(90%, 10%, 10%)');
$colorInfo = $color->getHSL();
print_r($colorInfo);
?>`

The above example will output:

    Array
    (
        [hue] => 0
        [saturation] => 0.80001220740379
        [luminosity] => 0.50000762951095
    )

### Notes

> Note:

> Available with ImageMagick library version 6.2.9 and higher.

# ImagickPixel::getIndex

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::getIndex — Gets the colormap index of the pixel wand

### Description

public ImagickPixel::getIndex(): int

Gets the colormap index of the pixel wand.

### Parameters

This function has no parameters.

### Return Values

# ImagickPixel::isPixelSimilar

(PECL imagick 3 >= 3.3.0)

ImagickPixel::isPixelSimilar — Check the distance between this color and another

### Description

public ImagickPixel::isPixelSimilar(ImagickPixel `$color`, float `$fuzz`): bool

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. This method replaces ImagickPixel::isSimilar() and correctly normalises the fuzz value to ImageMagick QuantumRange.

### Parameters

`color`

  The ImagickPixel object to compare this object against.

`fuzz`

  The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

### Return Values

Returns `true` on success.

# ImagickPixel::isPixelSimilarQuantum

(PECL imagick 3 >= 3.3.0)

ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance

### Description

public ImagickPixel::isPixelSimilarQuantum(string `$color`, string `$fuzz` = ?): bool

Returns true if the distance between two colors is less than the specified distance. The fuzz value should be in the range 0-QuantumRange. The maximum value represents the longest possible distance in the colorspace. e.g. from RGB(0, 0, 0) to RGB(255, 255, 255) for the RGB colorspace

### Parameters

`color`

`fuzz`

### Return Values

# ImagickPixel::isSimilar

(PECL imagick 2, PECL imagick 3)

ImagickPixel::isSimilar — Check the distance between this color and another

### Description

public ImagickPixel::isSimilar(ImagickPixel `$color`, float `$fuzz`): bool
Warning

This function is currently not documented; only its argument list is available.

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. Deprecated in favour of ImagickPixel::isPixelSimilar().

### Parameters

`color`

  The ImagickPixel object to compare this object against.

`fuzz`

  The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixel::isSimilar()

`<?php
// The tests below are written with the maximum distance expressed as 255
// so we need to scale them by the square root of 3 - the diagonal length
// of a unit cube.
$root3 = 1.732050807568877;
$tests = array(
['rgb(245, 0, 0)', 'rgb(255, 0, 0)', 9 / $root3, false,],
['rgb(245, 0, 0)', 'rgb(255, 0, 0)', 10 / $root3, true,],
['rgb(0, 0, 0)', 'rgb(7, 7, 0)', 9 / $root3, false,],
['rgb(0, 0, 0)', 'rgb(7, 7, 0)', 10 / $root3, true,],
['rgba(0, 0, 0, 1)', 'rgba(7, 7, 0, 1)', 9 / $root3, false,],
['rgba(0, 0, 0, 1)', 'rgba(7, 7, 0, 1)', 10 / $root3, true,],
['rgb(128, 128, 128)', 'rgb(128, 128, 120)', 7 / $root3, false,],
['rgb(128, 128, 128)', 'rgb(128, 128, 120)', 8 / $root3, true,],
['rgb(0, 0, 0)', 'rgb(255, 255, 255)', 254.9, false,],
['rgb(0, 0, 0)', 'rgb(255, 255, 255)', 255, true,],
['rgb(255, 0, 0)', 'rgb(0, 255, 255)', 254.9, false,],
['rgb(255, 0, 0)', 'rgb(0, 255, 255)', 255, true,],
['black', 'rgba(0, 0, 0)', 0.0, true],
['black', 'rgba(10, 0, 0, 1.0)', 10.0 / $root3, true],);
$output = "<table width='100%' class='infoTable'><thead>
<tr>
<th>
Color 1
</th>
<th>
Color 2
</th>
<th>
Test distance * 255
</th>
<th>
Is within distance
</th>
</tr>
</thead>";
$output .= "<tbody>";
foreach ($tests as $testInfo) {
$color1 = $testInfo[0];
$color2 = $testInfo[1];
$distance = $testInfo[2];
$expectation = $testInfo[3];
$testDistance = ($distance / 255.0);
$color1Pixel = new \ImagickPixel($color1);
$color2Pixel = new \ImagickPixel($color2);
$isSimilar = $color1Pixel->isPixelSimilar($color2Pixel, $testDistance);
if ($isSimilar !== $expectation) {
echo "Test distance failed. Color [$color1] compared to color [$color2] is not within distance $testDistance FAILED.".NL;
}
$layout = "<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td style='text-align: center;'>%s</td>
</tr>";
$output .= sprintf(
$layout,
$color1,
$color2,
$distance,
$isSimilar ? 'yes' : 'no'
);
}
$output .= "</tbody></table>";
return $output;
?>`

# ImagickPixel::setColor

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColor — Sets the color

### Description

public ImagickPixel::setColor(string `$color`): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

### Parameters

`color`

  The color definition to use in order to initialise the ImagickPixel object.

### Return Values

Returns `true` if the specified color was set, `false` otherwise.

### Examples

Example #1 ImagickPixel::setColor()

`<?php
function setColor() {
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel('green');
$fillColor = new \ImagickPixel();
$fillColor->setColor('rgba(100%, 75%, 0%, 1.0)');
$draw->setstrokewidth(3.0);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$image = new \Imagick();
$image->newImage(500, 500, "SteelBlue2");
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickPixel::setColorCount

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColorCount — Sets the color count associated with this color

### Description

public ImagickPixel::setcolorcount(int `$colorCount`): bool

Sets the color count associated with this color.

### Parameters

`colorCount`

### Return Values

Returns `true` on success.

# ImagickPixel::setColorValue

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

### Description

public ImagickPixel::setColorValue(int `$color`, float `$value`): bool

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object.

### Parameters

`color`

  One of the Imagick color constants e.g. \Imagick::COLOR_GREEN or \Imagick::COLOR_ALPHA.

`value`

  The value to set this channel to, ranging from 0 to 1.

### Return Values

Returns `true` on success.

### Examples

Example #1 Basic Imagick::setColorValue() usage

`<?php
$color = new \ImagickPixel('firebrick');
$color->setColorValue(Imagick::COLOR_ALPHA, 0.5);
print_r($color->getcolor(true));
?>`

The above example will output:

    Array
    (
        [r] => 0.69803921568627
        [g] => 0.13333333333333
        [b] => 0.13333333333333
        [a] => 0.50000762951095
    )

# ImagickPixel::setColorValueQuantum

(PECL imagick 2 >=2.3.0, PECL imagick 3)

ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel

### Description

public ImagickPixel::setColorValueQuantum(int `$color`, int|float `$value`): bool

Sets the quantum value of a color element of the ImagickPixel.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`color`

  Which color element to set e.g. \Imagick::COLOR_GREEN.

`value`

  The quantum value to set the color element to. This should be a float if ImageMagick was compiled with HDRI otherwise an int in the range 0 to Imagick::getQuantum().

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixel::setColorValueQuantum()

`<?php
function setColorValueQuantum() {
$image = new \Imagick();
$quantumRange = $image->getQuantumRange();
$draw = new \ImagickDraw();
$color = new \ImagickPixel('blue');
$color->setcolorValueQuantum(\Imagick::COLOR_RED, 128 * $quantumRange['quantumRangeLong'] / 256);
$draw->setstrokewidth(1.0);
$draw->setStrokeColor($color);
$draw->setFillColor($color);
$draw->rectangle(200, 200, 300, 300);
$image->newImage(500, 500, "SteelBlue2");
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>`

# ImagickPixel::setHSL

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setHSL — Sets the normalized HSL color

### Description

public ImagickPixel::setHSL(float `$hue`, float `$saturation`, float `$luminosity`): bool

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

### Parameters

`hue`

  The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red.

`saturation`

  The normalized value for saturation, with 1 as full saturation.

`luminosity`

  The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity.

### Return Values

Returns `true` on success.

### Examples

Example #1 Use ImagickPixel::setHSL() to modify a color

`<?php
//Create an almost pure red color
$color = new ImagickPixel('rgb(90%, 10%, 10%)');
//Get it's HSL values
$colorInfo = $color->getHSL();
//Rotate the hue by 180 degrees
$newHue = $colorInfo['hue'] + 0.5;
if ($newHue > 1) {
$newHue = $newHue - 1;
}
//Set the ImagickPixel to the new color
$colorInfo = $color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']);
//Check that the new color is blue/green
$colorInfo = $color->getcolor();
print_r($colorInfo);
?>`

The above example will output:

    Array
    (
        [r] => 26
        [g] => 230
        [b] => 230
        [a] => 255
    )

### Notes

> Note:

> Available with ImageMagick library version 6.2.9 and higher.

# ImagickPixel::setIndex

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::setIndex — Sets the colormap index of the pixel wand

### Description

public ImagickPixel::setIndex(int `$index`): bool

Sets the colormap index of the pixel wand.

### Parameters

`index`

### Return Values

Returns `true` on success.

## Table of Contents

- ImagickPixel::clear — Clears resources associated with this object
- ImagickPixel::__construct — The ImagickPixel constructor
- ImagickPixel::destroy — Deallocates resources associated with this object
- ImagickPixel::getColor — Returns the color
- ImagickPixel::getColorAsString — Returns the color as a string
- ImagickPixel::getColorCount — Returns the color count associated with this color
- ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values
- ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
- ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel
- ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
- ImagickPixel::getIndex — Gets the colormap index of the pixel wand
- ImagickPixel::isPixelSimilar — Check the distance between this color and another
- ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance
- ImagickPixel::isSimilar — Check the distance between this color and another
- ImagickPixel::setColor — Sets the color
- ImagickPixel::setColorCount — Sets the color count associated with this color
- ImagickPixel::setColorValue — Sets the normalized value of one of the channels
- ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel
- ImagickPixel::setHSL — Sets the normalized HSL color
- ImagickPixel::setIndex — Sets the colormap index of the pixel wand

# The ImagickPixelException class

(PECL imagick 3)

## Introduction

## Class synopsis

class ImagickPixelException extends Exception implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
/* Inherited methods */
}

# The ImagickPixelIterator class

(PECL imagick 2, PECL imagick 3)

## Class synopsis

class ImagickPixelIterator {
public clear(): bool
public __construct(Imagick `$wand`)
public destroy(): bool
public getCurrentIteratorRow(): array
public getIteratorRow(): int
public getNextIteratorRow(): array
public getPreviousIteratorRow(): array
public newPixelIterator(Imagick `$wand`): bool
public newPixelRegionIterator(
Imagick `$wand`,
int `$x`,
int `$y`,
int `$columns`,
int `$rows`
): bool
public resetIterator(): bool
public setIteratorFirstRow(): bool
public setIteratorLastRow(): bool
public setIteratorRow(int `$row`): bool
public syncIterator(): bool
}

# ImagickPixelIterator::clear

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

### Description

public ImagickPixelIterator::clear(): bool
Warning

This function is currently not documented; only its argument list is available.

Clear resources associated with a PixelIterator.

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixelIterator::clear()

`<?php
function clear($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelRegionIterator(100, 100, 250, 200);
/* Loop through pixel rows */
foreach ($imageIterator as $pixels) {
/** @var $pixel \ImagickPixel */
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}
$imageIterator->clear();
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# ImagickPixelIterator::__construct

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

### Description

public ImagickPixelIterator::__construct(Imagick `$wand`)
Warning

This function is currently not documented; only its argument list is available.

The ImagickPixelIterator constructor

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixelIterator::construct()

`<?php
function construct($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = new \ImagickPixelIterator($imagick);
/* Loop through pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# ImagickPixelIterator::destroy

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

### Description

public ImagickPixelIterator::destroy(): bool
Warning

This function is currently not documented; only its argument list is available.

Deallocates resources associated with a PixelIterator.

### Return Values

Returns `true` on success.

# ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

### Description

public ImagickPixelIterator::getCurrentIteratorRow(): array
Warning

This function is currently not documented; only its argument list is available.

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

### Return Values

Returns a row as an array of ImagickPixel objects that can themselves be iterated.

# ImagickPixelIterator::getIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

### Description

public ImagickPixelIterator::getIteratorRow(): int
Warning

This function is currently not documented; only its argument list is available.

Returns the current pixel iterator row.

### Return Values

Returns the integer offset of the row, throwing ImagickPixelIteratorException on error.

# ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

### Description

public ImagickPixelIterator::getNextIteratorRow(): array
Warning

This function is currently not documented; only its argument list is available.

Returns the next row as an array of pixel wands from the pixel iterator.

### Return Values

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

### Examples

Example #1 ImagickPixelIterator::getNextIteratorRow()

`<?php
function getNextIteratorRow($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelIterator();
$count = 0;
while ($pixels = $imageIterator->getNextIteratorRow()) {
if (($count % 3) == 0) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}
$count += 1;
}
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

### Description

public ImagickPixelIterator::getPreviousIteratorRow(): array
Warning

This function is currently not documented; only its argument list is available.

Returns the previous row as an array of pixel wands from the pixel iterator.

### Return Values

Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error.

# ImagickPixelIterator::newPixelIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

### Description

public ImagickPixelIterator::newPixelIterator(Imagick `$wand`): bool
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

### Return Values

Returns `true` on success. Throwing ImagickPixelIteratorException.

# ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

### Description

public ImagickPixelIterator::newPixelRegionIterator(
Imagick `$wand`,
int `$x`,
int `$y`,
int `$columns`,
int `$rows`
): bool
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

### Parameters

`wand`

`x`

`y`

`columns`

`rows`

### Return Values

Returns a new ImagickPixelIterator on success; on failure, throws ImagickPixelIteratorException.

# ImagickPixelIterator::resetIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

### Description

public ImagickPixelIterator::resetIterator(): bool
Warning

This function is currently not documented; only its argument list is available.

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixelIterator::resetIterator()

`<?php
function resetIterator($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelIterator();
/* Loop trough pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {
/* Make every second pixel 25% red*/
$pixel->setColorValue(\Imagick::COLOR_RED, 64);
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}
$imageIterator->resetiterator();
/* Loop trough pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 3) {
$pixel->setColorValue(\Imagick::COLOR_BLUE, 64); /* Make every second pixel a little blue*/
//$pixel->setColor("rgba(0, 0, 128, 0)"); /* Paint every second pixel black*/
}
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}
$imageIterator->clear();
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

### Description

public ImagickPixelIterator::setIteratorFirstRow(): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the first pixel row.

### Return Values

Returns `true` on success.

# ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

### Description

public ImagickPixelIterator::setIteratorLastRow(): bool
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the last pixel row.

### Return Values

Returns `true` on success.

# ImagickPixelIterator::setIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

### Description

public ImagickPixelIterator::setIteratorRow(int `$row`): bool
Warning

This function is currently not documented; only its argument list is available.

Set the pixel iterator row.

### Parameters

`row`

### Return Values

Returns `true` on success.

### Examples

Example #1 ImagickPixelIterator::setIteratorRow()

`<?php
function setIteratorRow($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelRegionIterator(200, 100, 200, 200);
for ($x = 0; $x < 20; $x++) {
$imageIterator->setIteratorRow($x * 5);
$pixels = $imageIterator->getCurrentIteratorRow();
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $pixel) {
/** @var $pixel \ImagickPixel */
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}
header("Content-Type: image/jpg");
echo $imagick;
}
?>`

# ImagickPixelIterator::syncIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

### Description

public ImagickPixelIterator::syncIterator(): bool
Warning

This function is currently not documented; only its argument list is available.

Syncs the pixel iterator.

### Return Values

Returns `true` on success.

## Table of Contents

- ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
- ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
- ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
- ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
- ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
- ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
- ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
- ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
- ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
- ImagickPixelIterator::resetIterator — Resets the pixel iterator
- ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
- ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
- ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
- ImagickPixelIterator::syncIterator — Syncs the pixel iterator

# The ImagickPixelIteratorException class

(PECL imagick 3)

## Introduction

## Class synopsis

class ImagickPixelIteratorException extends Exception implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Methods */
/* Inherited methods */
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Examples
  - Basic usage
- Imagick — The Imagick class
  - Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
  - Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
  - Imagick::adaptiveSharpenImage — Adaptively sharpen the image
  - Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
  - Imagick::addImage — Adds new image to Imagick object image list
  - Imagick::addNoiseImage — Adds random noise to the image
  - Imagick::affineTransformImage — Transforms an image
  - Imagick::animateImages — Animates an image or images
  - Imagick::annotateImage — Annotates an image with text
  - Imagick::appendImages — Append a set of images
  - Imagick::autoLevelImage — Adjusts the levels of a particular image channel
  - Imagick::averageImages — Average a set of images
  - Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  - Imagick::blueShiftImage — Mutes the colors of the image
  - Imagick::blurImage — Adds blur filter to image
  - Imagick::borderImage — Surrounds the image with a border
  - Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image
  - Imagick::charcoalImage — Simulates a charcoal drawing
  - Imagick::chopImage — Removes a region of an image and trims
  - Imagick::clampImage — Restricts the color range from 0 to the quantum depth.
  - Imagick::clear — Clears all resources associated to Imagick object
  - Imagick::clipImage — Clips along the first path from the 8BIM profile
  - Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present
  - Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
  - Imagick::clone — Makes an exact copy of the Imagick object
  - Imagick::clutImage — Replaces colors in the image
  - Imagick::coalesceImages — Composites a set of images
  - Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
  - Imagick::colorizeImage — Blends the fill color with the image
  - Imagick::colorMatrixImage — Apply color transformation to an image
  - Imagick::combineImages — Combines one or more images into a single image
  - Imagick::commentImage — Adds a comment to your image
  - Imagick::compareImageChannels — Returns the difference in one or more images
  - Imagick::compareImageLayers — Returns the maximum bounding region between images
  - Imagick::compareImages — Compares an image to a reconstructed image
  - Imagick::compositeImage — Composite one image onto another
  - Imagick::__construct — The Imagick constructor
  - Imagick::contrastImage — Change the contrast of the image
  - Imagick::contrastStretchImage — Enhances the contrast of a color image
  - Imagick::convolveImage — Applies a custom convolution kernel to the image
  - Imagick::count — Get the number of images
  - Imagick::cropImage — Extracts a region of the image
  - Imagick::cropThumbnailImage — Creates a crop thumbnail
  - Imagick::current — Returns a reference to the current Imagick object
  - Imagick::cycleColormapImage — Displaces an image's colormap
  - Imagick::decipherImage — Deciphers an image
  - Imagick::deconstructImages — Returns certain pixel differences between images
  - Imagick::deleteImageArtifact — Delete image artifact
  - Imagick::deleteImageProperty — Deletes an image property
  - Imagick::deskewImage — Removes skew from the image
  - Imagick::despeckleImage — Reduces the speckle noise in an image
  - Imagick::destroy — Destroys the Imagick object
  - Imagick::displayImage — Displays an image
  - Imagick::displayImages — Displays an image or image sequence
  - Imagick::distortImage — Distorts an image using various distortion methods
  - Imagick::drawImage — Renders the ImagickDraw object on the current image
  - Imagick::edgeImage — Enhance edges within the image
  - Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
  - Imagick::encipherImage — Enciphers an image
  - Imagick::enhanceImage — Improves the quality of a noisy image
  - Imagick::equalizeImage — Equalizes the image histogram
  - Imagick::evaluateImage — Applies an expression to an image
  - Imagick::exportImagePixels — Exports raw image pixels
  - Imagick::extentImage — Set image size
  - Imagick::filter — Applies a custom convolution kernel to the image
  - Imagick::flattenImages — Merges a sequence of images
  - Imagick::flipImage — Creates a vertical mirror image
  - Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
  - Imagick::flopImage — Creates a horizontal mirror image
  - Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)
  - Imagick::frameImage — Adds a simulated three-dimensional border
  - Imagick::functionImage — Applies a function on the image
  - Imagick::fxImage — Evaluate expression for each pixel in the image
  - Imagick::gammaImage — Gamma-corrects an image
  - Imagick::gaussianBlurImage — Blurs an image
  - Imagick::getColorspace — Gets the colorspace
  - Imagick::getCompression — Gets the object compression type
  - Imagick::getCompressionQuality — Gets the object compression quality
  - Imagick::getCopyright — Returns the ImageMagick API copyright as a string
  - Imagick::getFilename — The filename associated with an image sequence
  - Imagick::getFont — Gets font
  - Imagick::getFormat — Returns the format of the Imagick object
  - Imagick::getGravity — Gets the gravity
  - Imagick::getHomeURL — Returns the ImageMagick home URL
  - Imagick::getImage — Returns a new Imagick object
  - Imagick::getImageAlphaChannel — Checks if the image has an alpha channel
  - Imagick::getImageArtifact — Get image artifact
  - Imagick::getImageAttribute — Returns a named attribute
  - Imagick::getImageBackgroundColor — Returns the image background color
  - Imagick::getImageBlob — Returns the image sequence as a blob
  - Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
  - Imagick::getImageBorderColor — Returns the image border color
  - Imagick::getImageChannelDepth — Gets the depth for a particular image channel
  - Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
  - Imagick::getImageChannelDistortions — Gets channel distortions
  - Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
  - Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
  - Imagick::getImageChannelMean — Gets the mean and standard deviation
  - Imagick::getImageChannelRange — Gets channel range
  - Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
  - Imagick::getImageClipMask — Gets image clip mask
  - Imagick::getImageColormapColor — Returns the color of the specified colormap index
  - Imagick::getImageColors — Gets the number of unique colors in the image
  - Imagick::getImageColorspace — Gets the image colorspace
  - Imagick::getImageCompose — Returns the composite operator associated with the image
  - Imagick::getImageCompression — Gets the current image's compression type
  - Imagick::getImageCompressionQuality — Gets the current image's compression quality
  - Imagick::getImageDelay — Gets the image delay
  - Imagick::getImageDepth — Gets the image depth
  - Imagick::getImageDispose — Gets the image disposal method
  - Imagick::getImageDistortion — Compares an image to a reconstructed image
  - Imagick::getImageExtrema — Gets the extrema for the image
  - Imagick::getImageFilename — Returns the filename of a particular image in a sequence
  - Imagick::getImageFormat — Returns the format of a particular image in a sequence
  - Imagick::getImageGamma — Gets the image gamma
  - Imagick::getImageGeometry — Gets the width and height as an associative array
  - Imagick::getImageGravity — Gets the image gravity
  - Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
  - Imagick::getImageHeight — Returns the image height
  - Imagick::getImageHistogram — Gets the image histogram
  - Imagick::getImageIndex — Gets the index of the current active image
  - Imagick::getImageInterlaceScheme — Gets the image interlace scheme
  - Imagick::getImageInterpolateMethod — Returns the interpolation method
  - Imagick::getImageIterations — Gets the image iterations
  - Imagick::getImageLength — Returns the image length in bytes
  - Imagick::getImageMatte — Return if the image has a matte channel
  - Imagick::getImageMatteColor — Returns the image matte color
  - Imagick::getImageMimeType — Returns the image mime-type
  - Imagick::getImageOrientation — Gets the image orientation
  - Imagick::getImagePage — Returns the page geometry
  - Imagick::getImagePixelColor — Returns the color of the specified pixel
  - Imagick::getImageProfile — Returns the named image profile
  - Imagick::getImageProfiles — Returns the image profiles
  - Imagick::getImageProperties — Returns the image properties
  - Imagick::getImageProperty — Returns the named image property
  - Imagick::getImageRedPrimary — Returns the chromaticity red primary point
  - Imagick::getImageRegion — Extracts a region of the image
  - Imagick::getImageRenderingIntent — Gets the image rendering intent
  - Imagick::getImageResolution — Gets the image X and Y resolution
  - Imagick::getImagesBlob — Returns all image sequences as a blob
  - Imagick::getImageScene — Gets the image scene
  - Imagick::getImageSignature — Generates an SHA-256 message digest
  - Imagick::getImageSize — Returns the image length in bytes
  - Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
  - Imagick::getImageTotalInkDensity — Gets the image total ink density
  - Imagick::getImageType — Gets the potential image type
  - Imagick::getImageUnits — Gets the image units of resolution
  - Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
  - Imagick::getImageWhitePoint — Returns the chromaticity white point
  - Imagick::getImageWidth — Returns the image width
  - Imagick::getInterlaceScheme — Gets the object interlace scheme
  - Imagick::getIteratorIndex — Gets the index of the current active image
  - Imagick::getNumberImages — Returns the number of images in the object
  - Imagick::getOption — Returns a value associated with the specified key
  - Imagick::getPackageName — Returns the ImageMagick package name
  - Imagick::getPage — Returns the page geometry
  - Imagick::getPixelIterator — Returns a MagickPixelIterator
  - Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
  - Imagick::getPointSize — Gets point size
  - Imagick::getQuantum — Returns the ImageMagick quantum range
  - Imagick::getQuantumDepth — Gets the quantum depth
  - Imagick::getQuantumRange — Returns the Imagick quantum range
  - Imagick::getRegistry — Get a StringRegistry entry
  - Imagick::getReleaseDate — Returns the ImageMagick release date
  - Imagick::getResource — Returns the specified resource's memory usage
  - Imagick::getResourceLimit — Returns the specified resource limit
  - Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
  - Imagick::getSize — Returns the size associated with the Imagick object
  - Imagick::getSizeOffset — Returns the size offset
  - Imagick::getVersion — Returns the ImageMagick API version
  - Imagick::haldClutImage — Replaces colors in the image
  - Imagick::hasNextImage — Checks if the object has more images
  - Imagick::hasPreviousImage — Checks if the object has a previous image
  - Imagick::identifyFormat — Formats a string with image details
  - Imagick::identifyImage — Identifies an image and fetches attributes
  - Imagick::implodeImage — Creates a new image as a copy
  - Imagick::importImagePixels — Imports image pixels
  - Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)
  - Imagick::labelImage — Adds a label to an image
  - Imagick::levelImage — Adjusts the levels of an image
  - Imagick::linearStretchImage — Stretches with saturation the image intensity
  - Imagick::liquidRescaleImage — Animates an image or images
  - Imagick::listRegistry — List all the registry settings
  - Imagick::magnifyImage — Scales an image proportionally 2x
  - Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image
  - Imagick::matteFloodfillImage — Changes the transparency value of a color
  - Imagick::medianFilterImage — Applies a digital filter
  - Imagick::mergeImageLayers — Merges image layers
  - Imagick::minifyImage — Scales an image proportionally to half its size
  - Imagick::modulateImage — Control the brightness, saturation, and hue
  - Imagick::montageImage — Creates a composite image
  - Imagick::morphImages — Method morphs a set of images
  - Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.
  - Imagick::mosaicImages — Forms a mosaic from images
  - Imagick::motionBlurImage — Simulates motion blur
  - Imagick::negateImage — Negates the colors in the reference image
  - Imagick::newImage — Creates a new image
  - Imagick::newPseudoImage — Creates a new image
  - Imagick::nextImage — Moves to the next image
  - Imagick::normalizeImage — Enhances the contrast of a color image
  - Imagick::oilPaintImage — Simulates an oil painting
  - Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
  - Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
  - Imagick::orderedPosterizeImage — Performs an ordered dither
  - Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
  - Imagick::paintOpaqueImage — Change any pixel that matches color
  - Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
  - Imagick::pingImage — Fetch basic attributes about the image
  - Imagick::pingImageBlob — Quickly fetch attributes
  - Imagick::pingImageFile — Get basic image attributes in a lightweight manner
  - Imagick::polaroidImage — Simulates a Polaroid picture
  - Imagick::posterizeImage — Reduces the image to a limited number of color level
  - Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
  - Imagick::previousImage — Move to the previous image in the object
  - Imagick::profileImage — Adds or removes a profile from an image
  - Imagick::quantizeImage — Analyzes the colors within a reference image
  - Imagick::quantizeImages — Analyzes the colors within a sequence of images
  - Imagick::queryFontMetrics — Returns an array representing the font metrics
  - Imagick::queryFonts — Returns the configured fonts
  - Imagick::queryFormats — Returns formats supported by Imagick
  - Imagick::radialBlurImage — Radial blurs an image
  - Imagick::raiseImage — Creates a simulated 3d button-like effect
  - Imagick::randomThresholdImage — Creates a high-contrast, two-color image
  - Imagick::readImage — Reads image from filename
  - Imagick::readImageBlob — Reads image from a binary string
  - Imagick::readImageFile — Reads image from open filehandle
  - Imagick::readimages — Reads image from an array of filenames
  - Imagick::recolorImage — Recolors image
  - Imagick::reduceNoiseImage — Smooths the contours of an image
  - Imagick::remapImage — Remaps image colors
  - Imagick::removeImage — Removes an image from the image list
  - Imagick::removeImageProfile — Removes the named image profile and returns it
  - Imagick::render — Renders all preceding drawing commands
  - Imagick::resampleImage — Resample image to desired resolution
  - Imagick::resetImagePage — Reset image page
  - Imagick::resizeImage — Scales an image
  - Imagick::rollImage — Offsets an image
  - Imagick::rotateImage — Rotates an image
  - Imagick::rotationalBlurImage — Rotational blurs an image
  - Imagick::roundCorners — Rounds image corners
  - Imagick::sampleImage — Scales an image with pixel sampling
  - Imagick::scaleImage — Scales the size of an image
  - Imagick::segmentImage — Segments an image
  - Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold
  - Imagick::separateImageChannel — Separates a channel from the image
  - Imagick::sepiaToneImage — Sepia tones an image
  - Imagick::setBackgroundColor — Sets the object's default background color
  - Imagick::setColorspace — Set colorspace
  - Imagick::setCompression — Sets the object's default compression type
  - Imagick::setCompressionQuality — Sets the object's default compression quality
  - Imagick::setFilename — Sets the filename before you read or write the image
  - Imagick::setFirstIterator — Sets the Imagick iterator to the first image
  - Imagick::setFont — Sets font
  - Imagick::setFormat — Sets the format of the Imagick object
  - Imagick::setGravity — Sets the gravity
  - Imagick::setImage — Replaces image in the object
  - Imagick::setImageAlphaChannel — Sets image alpha channel
  - Imagick::setImageArtifact — Set image artifact
  - Imagick::setImageAttribute — Sets an image attribute
  - Imagick::setImageBackgroundColor — Sets the image background color
  - Imagick::setImageBias — Sets the image bias for any method that convolves an image
  - Imagick::setImageBiasQuantum — Sets the image bias
  - Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
  - Imagick::setImageBorderColor — Sets the image border color
  - Imagick::setImageChannelDepth — Sets the depth of a particular image channel
  - Imagick::setImageClipMask — Sets image clip mask
  - Imagick::setImageColormapColor — Sets the color of the specified colormap index
  - Imagick::setImageColorspace — Sets the image colorspace
  - Imagick::setImageCompose — Sets the image composite operator
  - Imagick::setImageCompression — Sets the image compression
  - Imagick::setImageCompressionQuality — Sets the image compression quality
  - Imagick::setImageDelay — Sets the image delay
  - Imagick::setImageDepth — Sets the image depth
  - Imagick::setImageDispose — Sets the image disposal method
  - Imagick::setImageExtent — Sets the image size
  - Imagick::setImageFilename — Sets the filename of a particular image
  - Imagick::setImageFormat — Sets the format of a particular image
  - Imagick::setImageGamma — Sets the image gamma
  - Imagick::setImageGravity — Sets the image gravity
  - Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
  - Imagick::setImageIndex — Set the iterator position
  - Imagick::setImageInterlaceScheme — Sets the image compression
  - Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
  - Imagick::setImageIterations — Sets the image iterations
  - Imagick::setImageMatte — Sets the image matte channel
  - Imagick::setImageMatteColor — Sets the image matte color
  - Imagick::setImageOpacity — Sets the image opacity level
  - Imagick::setImageOrientation — Sets the image orientation
  - Imagick::setImagePage — Sets the page geometry of the image
  - Imagick::setImageProfile — Adds a named profile to the Imagick object
  - Imagick::setImageProperty — Sets an image property
  - Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
  - Imagick::setImageRenderingIntent — Sets the image rendering intent
  - Imagick::setImageResolution — Sets the image resolution
  - Imagick::setImageScene — Sets the image scene
  - Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
  - Imagick::setImageType — Sets the image type
  - Imagick::setImageUnits — Sets the image units of resolution
  - Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
  - Imagick::setImageWhitePoint — Sets the image chromaticity white point
  - Imagick::setInterlaceScheme — Sets the image compression
  - Imagick::setIteratorIndex — Set the iterator position
  - Imagick::setLastIterator — Sets the Imagick iterator to the last image
  - Imagick::setOption — Set an option
  - Imagick::setPage — Sets the page geometry of the Imagick object
  - Imagick::setPointSize — Sets point size
  - Imagick::setProgressMonitor — Set a callback to be called during processing
  - Imagick::setRegistry — Sets the ImageMagick registry entry named key to value
  - Imagick::setResolution — Sets the image resolution
  - Imagick::setResourceLimit — Sets the limit for a particular resource
  - Imagick::setSamplingFactors — Sets the image sampling factors
  - Imagick::setSize — Sets the size of the Imagick object
  - Imagick::setSizeOffset — Sets the size and offset of the Imagick object
  - Imagick::setType — Sets the image type attribute
  - Imagick::shadeImage — Creates a 3D effect
  - Imagick::shadowImage — Simulates an image shadow
  - Imagick::sharpenImage — Sharpens an image
  - Imagick::shaveImage — Shaves pixels from the image edges
  - Imagick::shearImage — Creating a parallelogram
  - Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
  - Imagick::sketchImage — Simulates a pencil sketch
  - Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them
  - Imagick::solarizeImage — Applies a solarizing effect to the image
  - Imagick::sparseColorImage — Interpolates colors
  - Imagick::spliceImage — Splices a solid color into the image
  - Imagick::spreadImage — Randomly displaces each pixel in a block
  - Imagick::statisticImage — Modifies image using a statistics function
  - Imagick::steganoImage — Hides a digital watermark within the image
  - Imagick::stereoImage — Composites two images
  - Imagick::stripImage — Strips an image of all profiles and comments
  - Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image
  - Imagick::swirlImage — Swirls the pixels about the center of the image
  - Imagick::textureImage — Repeatedly tiles the texture image
  - Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
  - Imagick::thumbnailImage — Changes the size of an image
  - Imagick::tintImage — Applies a color vector to each pixel in the image
  - Imagick::__toString — Returns the image as a string
  - Imagick::transformImage — Convenience method for setting crop size and the image geometry
  - Imagick::transformImageColorspace — Transforms an image to a new colorspace
  - Imagick::transparentPaintImage — Paints pixels transparent
  - Imagick::transposeImage — Creates a vertical mirror image
  - Imagick::transverseImage — Creates a horizontal mirror image
  - Imagick::trimImage — Remove edges from the image
  - Imagick::uniqueImageColors — Discards all but one of any pixel color
  - Imagick::unsharpMaskImage — Sharpens an image
  - Imagick::valid — Checks if the current item is valid
  - Imagick::vignetteImage — Adds vignette filter to the image
  - Imagick::waveImage — Applies wave filter to the image
  - Imagick::whiteThresholdImage — Force all pixels above the threshold into white
  - Imagick::writeImage — Writes an image to the specified filename
  - Imagick::writeImageFile — Writes an image to a filehandle
  - Imagick::writeImages — Writes an image or image sequence
  - Imagick::writeImagesFile — Writes frames to a filehandle
- ImagickDraw — The ImagickDraw class
  - ImagickDraw::affine — Adjusts the current affine transformation matrix
  - ImagickDraw::annotation — Draws text on the image
  - ImagickDraw::arc — Draws an arc
  - ImagickDraw::bezier — Draws a bezier curve
  - ImagickDraw::circle — Draws a circle
  - ImagickDraw::clear — Clears the ImagickDraw
  - ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
  - ImagickDraw::color — Draws color on image
  - ImagickDraw::comment — Adds a comment
  - ImagickDraw::composite — Composites an image onto the current image
  - ImagickDraw::__construct — The ImagickDraw constructor
  - ImagickDraw::destroy — Frees all associated resources
  - ImagickDraw::ellipse — Draws an ellipse on the image
  - ImagickDraw::getClipPath — Obtains the current clipping path ID
  - ImagickDraw::getClipRule — Returns the current polygon fill rule
  - ImagickDraw::getClipUnits — Returns the interpretation of clip path units
  - ImagickDraw::getFillColor — Returns the fill color
  - ImagickDraw::getFillOpacity — Returns the opacity used when drawing
  - ImagickDraw::getFillRule — Returns the fill rule
  - ImagickDraw::getFont — Returns the font
  - ImagickDraw::getFontFamily — Returns the font family
  - ImagickDraw::getFontSize — Returns the font pointsize
  - ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text
  - ImagickDraw::getFontStyle — Returns the font style
  - ImagickDraw::getFontWeight — Returns the font weight
  - ImagickDraw::getGravity — Returns the text placement gravity
  - ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
  - ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
  - ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
  - ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
  - ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
  - ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
  - ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
  - ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
  - ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
  - ImagickDraw::getTextAlignment — Returns the text alignment
  - ImagickDraw::getTextAntialias — Returns the current text antialias setting
  - ImagickDraw::getTextDecoration — Returns the text decoration
  - ImagickDraw::getTextEncoding — Returns the code set used for text annotations
  - ImagickDraw::getTextInterlineSpacing — Gets the text interline spacing
  - ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing
  - ImagickDraw::getTextKerning — Gets the text kerning
  - ImagickDraw::getTextUnderColor — Returns the text under color
  - ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
  - ImagickDraw::line — Draws a line
  - ImagickDraw::matte — Paints on the image's opacity channel
  - ImagickDraw::pathClose — Adds a path element to the current path
  - ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
  - ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
  - ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
  - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
  - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
  - ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
  - ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
  - ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
  - ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
  - ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
  - ImagickDraw::pathFinish — Terminates the current path
  - ImagickDraw::pathLineToAbsolute — Draws a line path
  - ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
  - ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
  - ImagickDraw::pathLineToRelative — Draws a line path
  - ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
  - ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
  - ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
  - ImagickDraw::pathMoveToRelative — Starts a new sub-path
  - ImagickDraw::pathStart — Declares the start of a path drawing list
  - ImagickDraw::point — Draws a point
  - ImagickDraw::polygon — Draws a polygon
  - ImagickDraw::polyline — Draws a polyline
  - ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
  - ImagickDraw::popClipPath — Terminates a clip path definition
  - ImagickDraw::popDefs — Terminates a definition list
  - ImagickDraw::popPattern — Terminates a pattern definition
  - ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
  - ImagickDraw::pushClipPath — Starts a clip path definition
  - ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
  - ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
  - ImagickDraw::rectangle — Draws a rectangle
  - ImagickDraw::render — Renders all preceding drawing commands onto the image
  - ImagickDraw::resetVectorGraphics — Resets the vector graphics
  - ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
  - ImagickDraw::roundRectangle — Draws a rounded rectangle
  - ImagickDraw::scale — Adjusts the scaling factor
  - ImagickDraw::setClipPath — Associates a named clipping path with the image
  - ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
  - ImagickDraw::setClipUnits — Sets the interpretation of clip path units
  - ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
  - ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
  - ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
  - ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
  - ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
  - ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
  - ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
  - ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
  - ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
  - ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
  - ImagickDraw::setFontWeight — Sets the font weight
  - ImagickDraw::setGravity — Sets the text placement gravity
  - ImagickDraw::setResolution — Sets the resolution
  - ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
  - ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
  - ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
  - ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
  - ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
  - ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
  - ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
  - ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
  - ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
  - ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
  - ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
  - ImagickDraw::setTextAlignment — Specifies a text alignment
  - ImagickDraw::setTextAntialias — Controls whether text is antialiased
  - ImagickDraw::setTextDecoration — Specifies a decoration
  - ImagickDraw::setTextEncoding — Specifies the text code set
  - ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing
  - ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing
  - ImagickDraw::setTextKerning — Sets the text kerning
  - ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
  - ImagickDraw::setVectorGraphics — Sets the vector graphics
  - ImagickDraw::setViewbox — Sets the overall canvas size
  - ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
  - ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
  - ImagickDraw::translate — Applies a translation to the current coordinate system
- ImagickDrawException — The ImagickDrawException class
- ImagickException — The ImagickException class
- ImagickKernel — The ImagickKernel class
  - ImagickKernel::addKernel — Attach another kernel to a kernel list
  - ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list
  - ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel
  - ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values
  - ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel
  - ImagickKernel::scale — Scales a kernel list by the given amount
  - ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels
- ImagickKernelException — The ImagickKernelException class
- ImagickPixel — The ImagickPixel class
  - ImagickPixel::clear — Clears resources associated with this object
  - ImagickPixel::__construct — The ImagickPixel constructor
  - ImagickPixel::destroy — Deallocates resources associated with this object
  - ImagickPixel::getColor — Returns the color
  - ImagickPixel::getColorAsString — Returns the color as a string
  - ImagickPixel::getColorCount — Returns the color count associated with this color
  - ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values
  - ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  - ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel
  - ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  - ImagickPixel::getIndex — Gets the colormap index of the pixel wand
  - ImagickPixel::isPixelSimilar — Check the distance between this color and another
  - ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance
  - ImagickPixel::isSimilar — Check the distance between this color and another
  - ImagickPixel::setColor — Sets the color
  - ImagickPixel::setColorCount — Sets the color count associated with this color
  - ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  - ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel
  - ImagickPixel::setHSL — Sets the normalized HSL color
  - ImagickPixel::setIndex — Sets the colormap index of the pixel wand
- ImagickPixelException — The ImagickPixelException class
- ImagickPixelIterator — The ImagickPixelIterator class
  - ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
  - ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
  - ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
  - ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
  - ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
  - ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
  - ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
  - ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
  - ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
  - ImagickPixelIterator::resetIterator — Resets the pixel iterator
  - ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
  - ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
  - ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
  - ImagickPixelIterator::syncIterator — Syncs the pixel iterator
- ImagickPixelIteratorException — The ImagickPixelIteratorException class

- Exif — Exchangeable image information
  - Installing/Configuring
  - Predefined Constants
  - Exif Functions
- GD — Image Processing and GD
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - GD and Image Functions
  - GdImage — The GdImage class
  - GdFont — The GdFont class
- Gmagick
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Gmagick — The Gmagick class
  - GmagickDraw — The GmagickDraw class
  - GmagickPixel — The GmagickPixel class
- ImageMagick — Image Processing (ImageMagick)
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - Imagick — The Imagick class
  - ImagickDraw — The ImagickDraw class
  - ImagickDrawException — The ImagickDrawException class
  - ImagickException — The ImagickException class
  - ImagickKernel — The ImagickKernel class
  - ImagickKernelException — The ImagickKernelException class
  - ImagickPixel — The ImagickPixel class
  - ImagickPixelException — The ImagickPixelException class
  - ImagickPixelIterator — The ImagickPixelIterator class
  - ImagickPixelIteratorException — The ImagickPixelIteratorException class

# Mail Related Extensions

# IMAP, POP3 and NNTP

# Introduction

Warning

This extension is DEPRECATED and UNBUNDLED as of PHP 8.4.0.

These functions enable you to operate with the IMAP protocol, as well as the NNTP, POP3 and local mailbox access methods.

Be warned, however, that some IMAP functions will not work correctly with the POP protocol.

Warning

The IMAP extension is not thread-safe; it should not be used with ZTS builds.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration
- Resource Types

## Requirements

This extension requires the c-client library to be installed. Grab the latest version from » https://github.com/uw-imap/imap and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

> Note:

> To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.

> Note: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.

## Installation

## PHP 8.4

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 8.4.0

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: » https://pecl.php.net/package/imap.

## PHP < 8.4

To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini.

> Note: Depending on how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos to the PHP configure line.

Warning

The IMAP extension is not thread-safe; it should not be used with ZTS builds.

Warning

The IMAP, recode and YAZ extensions cannot be used in conjunction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

IMAP Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
imap.enable_insecure_rsh | "0" | `INI_SYSTEM` | Available as of PHP 7.1.25, 7.2.13 and 7.3.0. Formerly, it was implicitly enabled.

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`imap.enable_insecure_rsh` bool

  Establishing a connection to a server may invoke rsh or ssh commands, unless this php.ini option is disabled.

  Warning

  Neither PHP nor the IMAP library filter mailbox names before passing them to rsh or ssh commands, thus passing untrusted data to this function without disabling this php.ini option is insecure.

## Resource Types

Prior to PHP 8.1.0, this extension defined the resource type `imap` as returned by imap_open() references an opened IMAP stream.

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

`NIL` (int)
  Deprecated as of PHP 8.1.0.
`OP_DEBUG` (int)
`OP_READONLY` (int)
  Open mailbox read-only
`OP_ANONYMOUS` (int)
  Don't use or update a .newsrc for news (NNTP only)
`OP_SHORTCACHE` (int)
`OP_SILENT` (int)
`OP_PROTOTYPE` (int)
`OP_HALFOPEN` (int)
  For IMAP and NNTP names, open a connection but don't open a mailbox.
`OP_EXPUNGE` (int)
`OP_SECURE` (int)
`CL_EXPUNGE` (int)
  silently expunge the mailbox before closing when calling imap_close()
`FT_UID` (int)
  The parameter is a UID
`FT_PEEK` (int)
  Do not set the \Seen flag if not already set
`FT_NOT` (int)
`FT_INTERNAL` (int)
  The return string is in internal format, will not canonicalize to CRLF.
`FT_PREFETCHTEXT` (int)
`ST_UID` (int)
  The sequence argument contains UIDs instead of sequence numbers
`ST_SILENT` (int)
`ST_SET` (int)
`CP_UID` (int)
  the sequence numbers contain UIDS
`CP_MOVE` (int)
  Delete the messages from the current mailbox after copying with imap_mail_copy()
`SE_UID` (int)
  Return UIDs instead of sequence numbers
`SE_FREE` (int)
`SE_NOPREFETCH` (int)
  Don't prefetch searched messages
`SO_FREE` (int)
`SO_NOSERVER` (int)
`SA_MESSAGES` (int)
`SA_RECENT` (int)
`SA_UNSEEN` (int)
`SA_UIDNEXT` (int)
`SA_UIDVALIDITY` (int)
`SA_ALL` (int)
`LATT_NOINFERIORS` (int)
  This mailbox has no "children" (there are no mailboxes below this one).
`LATT_NOSELECT` (int)
  This is only a container, not a mailbox - you cannot open it.
`LATT_MARKED` (int)
  This mailbox is marked. Only used by UW-IMAPD.
`LATT_UNMARKED` (int)
  This mailbox is not marked. Only used by UW-IMAPD.
`LATT_REFERRAL` (int)
  This container has a referral to a remote mailbox.
`LATT_HASCHILDREN` (int)
  This mailbox has selectable inferiors.
`LATT_HASNOCHILDREN` (int)
  This mailbox has no selectable inferiors.
`SORTDATE` (int)
  Sort criteria for imap_sort(): message Date
`SORTARRIVAL` (int)
  Sort criteria for imap_sort(): arrival date
`SORTFROM` (int)
  Sort criteria for imap_sort(): mailbox in first From address
`SORTSUBJECT` (int)
  Sort criteria for imap_sort(): message subject
`SORTTO` (int)
  Sort criteria for imap_sort(): mailbox in first To address
`SORTCC` (int)
  Sort criteria for imap_sort(): mailbox in first cc address
`SORTSIZE` (int)
  Sort criteria for imap_sort(): size of message in octets
`TYPETEXT` (int)
  Primary body type: unformatted text
`TYPEMULTIPART` (int)
  Primary body type: multiple part
`TYPEMESSAGE` (int)
  Primary body type: encapsulated message
`TYPEAPPLICATION` (int)
  Primary body type: application data
`TYPEAUDIO` (int)
  Primary body type: audio
`TYPEIMAGE` (int)
  Primary body type: static image
`TYPEVIDEO` (int)
  Primary body type: video
`TYPEMODEL` (int)
  Primary body type: model
`TYPEOTHER` (int)
  Primary body type: unknown
`ENC7BIT` (int)
  Body encoding: 7 bit SMTP semantic data
`ENC8BIT` (int)
  Body encoding: 8 bit SMTP semantic data
`ENCBINARY` (int)
  Body encoding: 8 bit binary data
`ENCBASE64` (int)
  Body encoding: base-64 encoded data
`ENCQUOTEDPRINTABLE` (int)
  Body encoding: human-readable 8-as-7 bit data
`ENCOTHER` (int)
  Body encoding: unknown
`IMAP_OPENTIMEOUT` (int)
`IMAP_READTIMEOUT` (int)
`IMAP_WRITETIMEOUT` (int)
`IMAP_CLOSETIMEOUT` (int)
`IMAP_GC_ELT` (int)
  Garbage collector, clear message cache elements.
`IMAP_GC_ENV` (int)
  Garbage collector, clear envelopes and bodies.
`IMAP_GC_TEXTS` (int)
  Garbage collector, clear texts.

# IMAP Functions

# See Also

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

- » RFC2821: `Simple Mail Transfer Protocol` (SMTP).
- » RFC2822: `Standard for ARPA internet text messages`.
- » RFC2060: `Internet Message Access Protocol` (IMAP) Version 4rev1.
- » RFC1939: `Post Office Protocol Version 3` (POP3).
- » RFC977: `Network News Transfer Protocol` (NNTP).
- » RFC2076: `Common Internet Message Headers`.
- » RFC2045 , » RFC2046 , » RFC2047 , » RFC2048 & » RFC2049: `Multipurpose Internet Mail Extensions` (MIME).

A detailed overview is also available in the books » `Programming Internet Email` by David Wood and » Managing IMAP by Dianna Mullet & Kevin Mullet.

# imap_8bit

(PHP 4, PHP 5, PHP 7, PHP 8)

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

### Description

imap_8bit(string `$string`): string|false

Convert an 8bit string to a quoted-printable string (according to » RFC2045, section 6.7).

### Parameters

`string`

  The 8bit string to convert

### Return Values

Returns a quoted-printable string, or `false` on failure.

### See Also

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

# imap_alerts

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_alerts — Returns all IMAP alert messages that have occurred

### Description

imap_alerts(): array|false

Returns all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page.

When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

### Parameters

This function has no parameters.

### Return Values

Returns an array of all of the IMAP alert messages generated or `false` if no alert messages are available.

### See Also

- imap_errors() - Returns all of the IMAP errors that have occurred

# imap_append

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_append — Append a string message to a specified mailbox

### Description

imap_append(
IMAP\Connection `$imap`,
string `$folder`,
string `$message`,
?string `$options` = `null`,
?string `$internal_date` = `null`
): bool

Appends a string `message` to the specified `folder`.

### Parameters

`imap`

  An IMAP\Connection instance.

`folder`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`message`

  The message to be append, as a string

  When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail

`options`

  If provided, the `options` will also be written to the `folder`

`internal_date`

  If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a date string that conforms to the rfc2060 specifications for a date_time value.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | `options` and `internal_date` are now nullable.

### Examples

Example #1 imap_append() example

`<?php
$imap = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");
$check = imap_check($imap);
echo "Msg Count before append: ". $check->Nmsgs . "\n";
imap_append($imap, "{imap.example.org}INBOX.Drafts"
, "From: me@example.com\r\n"
. "To: you@example.com\r\n"
. "Subject: test\r\n"
. "\r\n"
. "this is a test message, please ignore\r\n"
);
$check = imap_check($imap);
echo "Msg Count after append : ". $check->Nmsgs . "\n";
imap_close($imap);
?>`

# imap_base64

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_base64 — Decode BASE64 encoded text

### Description

imap_base64(string `$string`): string|false

Decodes the given BASE-64 encoded `string`.

### Parameters

`string`

  The encoded text

### Return Values

Returns the decoded message as a string, or `false` on failure.

### See Also

- imap_binary() - Convert an 8bit string to a base64 string
- base64_encode() - Encodes data with MIME base64
- base64_decode() - Decodes data encoded with MIME base64
- » RFC2045, Section 6.8

# imap_binary

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_binary — Convert an 8bit string to a base64 string

### Description

imap_binary(string `$string`): string|false

Convert an 8bit string to a base64 string according to » RFC2045, Section 6.8.

### Parameters

`string`

  The 8bit string

### Return Values

Returns a base64 encoded string, or `false` on failure.

### See Also

- imap_base64() - Decode BASE64 encoded text

# imap_body

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_body — Read the message body

### Description

imap_body(IMAP\Connection `$imap`, int `$message_num`, int `$flags` = 0): string|false

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

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`flags`

  The optional `flags` are a bit mask with one or more of the following:

  - `FT_UID` - The `message_num` is a UID
  - `FT_PEEK` - Do not set the \Seen flag if not already set
  - `FT_INTERNAL` - The return string is in internal format, will not canonicalize to CRLF.

### Return Values

Returns the body of the specified message, as a string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

# imap_bodystruct

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_bodystruct — Read the structure of a specified body section of a specific message

### Description

imap_bodystruct(IMAP\Connection `$imap`, int `$message_num`, string `$section`): stdClass|false

Read the structure of a specified body section of a specific message.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`section`

  The body section to read

### Return Values

Returns the information in an object, or `false` on failure. For a detailed description of the object structure and properties see imap_fetchstructure().

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_fetchstructure() - Read the structure of a particular message

# imap_check

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_check — Check current mailbox

### Description

imap_check(IMAP\Connection `$imap`): stdClass|false

Checks information about the current mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Returns the information in an object with following properties:

- `Date` - current system time formatted according to » RFC2822
- `Driver` - protocol used to access this mailbox: POP3, IMAP, NNTP
- `Mailbox` - the mailbox name
- `Nmsgs` - number of messages in the mailbox
- `Recent` - number of recent messages in the mailbox

Returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_check() example

`<?php
$imap = imap_check($imap_stream);
var_dump($imap);
?>`

The above example will output something similar to:

    object(stdClass)(5) {
      ["Date"]=>
      string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
      ["Driver"]=>
      string(4) "imap"
      ["Mailbox"]=>
      string(54)
      "{www.example.com:143/imap/user="foo@example.com"}INBOX"
      ["Nmsgs"]=>
      int(1)
      ["Recent"]=>
      int(0)
    }

# imap_clearflag_full

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_clearflag_full — Clears flags on messages

### Description

imap_clearflag_full(
IMAP\Connection `$imap`,
string `$sequence`,
string `$flag`,
int `$options` = 0
): true

This function causes a store to delete the specified `flag` to the flags set for the messages in the specified `sequence`.

### Parameters

`imap`

  An IMAP\Connection instance.

`sequence`

  A sequence of message numbers. You can enumerate desired messages with the `X,Y` syntax, or retrieve all messages within an interval with the `X:Y` syntax

`flag`

  The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by » RFC2060)

`options`

  `options` are a bit mask and may contain the single option:

  - `ST_UID` - The sequence argument contains UIDs instead of sequence numbers

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws a ValueError if `options` is invalid.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | A ValueError is now thrown on invalid `options` parameter values. Previously, a warning was emitted and the function returned `false`.

### See Also

- imap_setflag_full() - Sets flags on messages

# imap_close

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_close — Close an IMAP stream

### Description

imap_close(IMAP\Connection `$imap`, int `$flags` = 0): true

Closes the imap stream.

### Parameters

`imap`

  An IMAP\Connection instance.

`flags`

  If set to `CL_EXPUNGE`, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws a ValueError if `flags` is invalid.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | A ValueError is now thrown on invalid `flags` parameter values. Previously, a warning was emitted and the function returned `false`.

### See Also

- imap_open() - Open an IMAP stream to a mailbox

# imap_create

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_create — Alias of imap_createmailbox()

### Description

This function is an alias of: imap_createmailbox().

# imap_createmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_createmailbox — Create a new mailbox

### Description

imap_createmailbox(IMAP\Connection `$imap`, string `$mailbox`): bool

Creates a new mailbox specified by `mailbox`.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_createmailbox() example

`<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewböx"); // phpnewb&w7Y-x
$newname = $name1;
echo "Newname will be '$name1'<br />\n";
// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finally remove it to restore
// your inbox to its initial state
if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
$status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
if ($status) {
echo "your new mailbox '$name1' has the following status:<br />\n";
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
$newname = $name2;
} else {
echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
}
} else {
echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
}
if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
echo "new mailbox removed to restore initial state<br />\n";
} else {
echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
}
} else {
echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}
imap_close($mbox);
?>`

### See Also

- imap_renamemailbox() - Rename an old mailbox to new mailbox
- imap_deletemailbox() - Delete a mailbox

# imap_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_delete — Mark a message for deletion from current mailbox

### Description

imap_delete(IMAP\Connection `$imap`, string `$message_nums`, int `$flags` = 0): true

Marks messages listed in `message_nums` for deletion. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter `CL_EXPUNGE`.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_nums`

  A string representing one or more messages in IMAP4-style sequence format (`"n"`, `"n:m"`, or combination of these delimited by commas).

`flags`

  You can set the `FT_UID` which tells the function to treat the `message_nums` argument as a `UID`.

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws a ValueError if `flags` is invalid.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | A ValueError is now thrown on invalid `flags` parameter values. Previously, a warning was emitted and the function returned `false`.

### Examples

Example #1 imap_delete() example

`<?php
$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
or die("Can't connect: " . imap_last_error());
$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";
imap_delete($mbox, 1);
$check = imap_mailboxmsginfo($mbox);
echo "Messages after delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($mbox);
$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
imap_close($mbox);
?>`

### Notes

> Note:

> IMAP mailboxes may not have their message flags saved between connections, so imap_expunge() should be called during the same connection in order to guarantee that messages marked for deletion will actually be purged.

### See Also

- imap_undelete() - Unmark the message which is marked deleted
- imap_expunge() - Delete all messages marked for deletion
- imap_close() - Close an IMAP stream

# imap_deletemailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_deletemailbox — Delete a mailbox

### Description

imap_deletemailbox(IMAP\Connection `$imap`, string `$mailbox`): bool

Deletes the specified `mailbox`.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_createmailbox() - Create a new mailbox
- imap_renamemailbox() - Rename an old mailbox to new mailbox
- imap_open() - Open an IMAP stream to a mailbox for the format of `mbox`

# imap_errors

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_errors — Returns all of the IMAP errors that have occurred

### Description

imap_errors(): array|false

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

### Parameters

This function has no parameters.

### Return Values

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. Returns `false` if no error messages are available.

### See Also

- imap_last_error() - Gets the last IMAP error that occurred during this page request
- imap_alerts() - Returns all IMAP alert messages that have occurred

# imap_expunge

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_expunge — Delete all messages marked for deletion

### Description

imap_expunge(IMAP\Connection `$imap`): true

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

# imap_fetch_overview

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetch_overview — Read an overview of the information in the headers of the given message

### Description

imap_fetch_overview(IMAP\Connection `$imap`, string `$sequence`, int `$flags` = 0): array|false

This function fetches mail headers for the given `sequence` and returns an overview of their contents.

### Parameters

`imap`

  An IMAP\Connection instance.

`sequence`

  A message sequence description. You can enumerate desired messages with the `X,Y` syntax, or retrieve all messages within an interval with the `X:Y` syntax

`flags`

  `sequence` will contain a sequence of message indices or UIDs, if this parameter is set to `FT_UID`.

### Return Values

Returns an array of objects describing one message header each. The object will only define a property if it exists. The possible properties are:

- `subject` - the messages subject
- `from` - who sent it
- `to` - recipient
- `date` - when was it sent
- `message_id` - Message-ID
- `references` - is a reference to this message id
- `in_reply_to` - is a reply to this message id
- `size` - size in bytes
- `uid` - UID the message has in the mailbox
- `msgno` - message sequence number in the mailbox
- `recent` - this message is flagged as recent
- `flagged` - this message is flagged
- `answered` - this message is flagged as answered
- `deleted` - this message is flagged for deletion
- `seen` - this message is flagged as already read
- `draft` - this message is flagged as being a draft
- `udate` - the UNIX timestamp of the arrival date

The function returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_fetch_overview() example

`<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
or die("can't connect: " . imap_last_error());
$MC = imap_check($mbox);
// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
{$overview->subject}\n";
}
imap_close($mbox);
?>`

### See Also

- imap_fetchheader() - Returns header for a message

# imap_fetchbody

(PHP 4, PHP 5, PHP 7, PHP 8)

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

### Description

imap_fetchbody(
IMAP\Connection `$imap`,
int `$message_num`,
string `$section`,
int `$flags` = 0
): string|false

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`section`

  The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

`flags`

  A bitmask with one or more of the following:

  - `FT_UID` - The `message_num` is a UID
  - `FT_PEEK` - Do not set the \Seen flag if not already set
  - `FT_INTERNAL` - The return string is in internal format, will not canonicalize to CRLF.

### Return Values

Returns a particular section of the body of the specified messages as a text string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_savebody() - Save a specific body section to a file
- imap_fetchstructure() - Read the structure of a particular message

# imap_fetchheader

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchheader — Returns header for a message

### Description

imap_fetchheader(IMAP\Connection `$imap`, int `$message_num`, int `$flags` = 0): string|false

This function causes a fetch of the complete, unfiltered » RFC2822 format header of the specified message.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`flags`

  The possible `flags` are:

  - `FT_UID` - The `message_num` argument is a UID
  - `FT_INTERNAL` - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines
  - `FT_PREFETCHTEXT` - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)

### Return Values

Returns the header of the specified message as a text string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_fetch_overview() - Read an overview of the information in the headers of the given message

# imap_fetchmime

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

imap_fetchmime — Fetch MIME headers for a particular section of the message

### Description

imap_fetchmime(
IMAP\Connection `$imap`,
int `$message_num`,
string `$section`,
int `$flags` = 0
): string|false

Fetch the MIME headers of a particular section of the body of the specified messages.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`section`

  The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

`flags`

  A bitmask with one or more of the following:

  - `FT_UID` - The `message_num` is a UID
  - `FT_PEEK` - Do not set the \Seen flag if not already set
  - `FT_INTERNAL` - The return string is in internal format, will not canonicalize to CRLF.

### Return Values

Returns the MIME headers of a particular section of the body of the specified messages as a text string, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_fetchbody() - Fetch a particular section of the body of the message
- imap_fetchstructure() - Read the structure of a particular message
- imap_fetchheader() - Returns header for a message

# imap_fetchstructure

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchstructure — Read the structure of a particular message

### Description

imap_fetchstructure(IMAP\Connection `$imap`, int `$message_num`, int `$flags` = 0): stdClass|false

Fetches all the structured information for a given message.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`flags`

  This optional parameter only has a single option, `FT_UID`, which tells the function to treat the `message_num` argument as a `UID`.

### Return Values

Returns an object with properties listed in the table below, or `false` on failure.

Returned Object for imap_fetchstructure()
type | Primary body type
encoding | Body transfer encoding
ifsubtype | `true` if there is a subtype string
subtype | MIME subtype
ifdescription | `true` if there is a description string
description | Content description string
ifid | `true` if there is an identification string
id | Identification string
lines | Number of lines
bytes | Number of bytes
ifdisposition | `true` if there is a disposition string
disposition | Disposition string
ifdparameters | `true` if the dparameters array exists
dparameters | An array of objects where each object has an `"attribute"` and a `"value"` property corresponding to the parameters on the `Content-disposition` MIME header.
ifparameters | `true` if the parameters array exists
parameters | An array of objects where each object has an `"attribute"` and a `"value"` property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Primary body type (value may vary with used library, use of constants is recommended)
Value | Type | Constant
--- | --- | ---
0 | text | TYPETEXT
1 | multipart | TYPEMULTIPART
2 | message | TYPEMESSAGE
3 | application | TYPEAPPLICATION
4 | audio | TYPEAUDIO
5 | image | TYPEIMAGE
6 | video | TYPEVIDEO
7 | model | TYPEMODEL
8 | other | TYPEOTHER

Transfer encodings (value may vary with used library, use of constants is recommended)
Value | Type | Constant
--- | --- | ---
0 | 7bit | ENC7BIT
1 | 8bit | ENC8BIT
2 | Binary | ENCBINARY
3 | Base64 | ENCBASE64
4 | Quoted-Printable | ENCQUOTEDPRINTABLE
5 | other | ENCOTHER

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_fetchbody() - Fetch a particular section of the body of the message
- imap_bodystruct() - Read the structure of a specified body section of a specific message

# imap_fetchtext

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchtext — Alias of imap_body()

### Description

This function is an alias of: imap_body().

# imap_gc

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_gc — Clears IMAP cache

### Description

imap_gc(IMAP\Connection `$imap`, int `$flags`): true

Purges the cache of entries of a specific type.

### Parameters

`imap`

  An IMAP\Connection instance.

`flags`

  Specifies the cache to purge. It may one or a combination of the following constants: `IMAP_GC_ELT` (message cache elements), `IMAP_GC_ENV` (envelope and bodies), `IMAP_GC_TEXTS` (texts).

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws a ValueError if `flags` is invalid.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | A ValueError is now thrown on invalid `flags` parameter values. Previously, a warning was emitted and the function returned `false`.

### Examples

Example #1 imap_gc() example

`<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");
imap_gc($mbox, IMAP_GC_ELT);
?>`

# imap_get_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

### Description

imap_get_quota(IMAP\Connection `$imap`, string `$quota_root`): array|false

Retrieve the quota level settings, and usage statics per mailbox.

For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

### Parameters

`imap`

  An IMAP\Connection instance.

`quota_root`

  `quota_root` should normally be in the form of `user.name` where name is the mailbox you wish to retrieve information about.

### Return Values

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return `false` in the case of failure.

As of PHP 4.3, the function more properly reflects the functionality as dictated by the » RFC2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it.

For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_get_quota() example

`<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
echo "Usage level is: " . $quota_value['usage'];
echo "Limit level is: " . $quota_value['limit'];
}
imap_close($mbox);
?>`

Example #2 imap_get_quota() 4.3 or greater example

`<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
$storage = $quota_values['STORAGE'];
echo "STORAGE usage level is: " . $storage['usage'];
echo "STORAGE limit level is: " . $storage['limit'];
$message = $quota_values['MESSAGE'];
echo "MESSAGE usage level is: " . $message['usage'];
echo "MESSAGE limit is: " . $message['limit'];
/* ... */
}
imap_close($mbox);
?>`

### Notes

This function is currently only available to users of the c-client2000 or greater library.

The given `imap` must be opened as the mail administrator, otherwise this function will fail.

### See Also

- imap_open() - Open an IMAP stream to a mailbox
- imap_set_quota() - Sets a quota for a given mailbox
- imap_get_quotaroot() - Retrieve the quota settings per user

# imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imap_get_quotaroot — Retrieve the quota settings per user

### Description

imap_get_quotaroot(IMAP\Connection `$imap`, string `$mailbox`): array|false

Retrieve the quota settings per user. The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  `mailbox` should normally be in the form of which mailbox (i.e. INBOX).

### Return Values

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

This function will return `false` in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_get_quotaroot() example

`<?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
$storage = $quota['STORAGE'];
echo "STORAGE usage level is: " . $storage['usage'];
echo "STORAGE limit level is: " . $storage['limit'];
$message = $quota['MESSAGE'];
echo "MESSAGE usage level is: " . $message['usage'];
echo "MESSAGE limit level is: " . $message['limit'];
/* ... */
}
imap_close($mbox);
?>`

### Notes

This function is currently only available to users of the c-client2000 or greater library.

The `imap` should be opened as the user whose mailbox you wish to check.

### See Also

- imap_open() - Open an IMAP stream to a mailbox
- imap_set_quota() - Sets a quota for a given mailbox
- imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

# imap_getacl

(PHP 5, PHP 7, PHP 8)

imap_getacl — Gets the ACL for a given mailbox

### Description

imap_getacl(IMAP\Connection `$imap`, string `$mailbox`): array|false

Gets the ACL for a given mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns an associative array of "folder" => "acl" pairs, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_getacl() example

`<?php
print_r(imap_getacl($imap, 'user.joecool'));
?>`

The above example will output something similar to:

    Array
    (
        [asubfolder] => lrswipcda
        [anothersubfolder] => lrswipcda
    )

### Notes

This function is currently only available to users of the c-client2000 or greater library.

### See Also

- imap_setacl() - Sets the ACL for a given mailbox

# imap_getmailboxes

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

### Description

imap_getmailboxes(IMAP\Connection `$imap`, string `$reference`, string `$pattern`): array|false

Gets information on the mailboxes.

### Parameters

`imap`

  An IMAP\Connection instance.

`reference`

  `reference` should normally be just the server specification as described in imap_open()

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`pattern`

  Specifies where in the mailbox hierarchy to start searching.

  There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

### Return Values

Returns an array of objects containing mailbox information. Each object has the attributes `name`, specifying the full name of the mailbox; `delimiter`, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and `attributes`. `Attributes` is a bitmask that can be tested against:

- `LATT_NOINFERIORS` - This mailbox not contains, and may not contain any "children" (there are no mailboxes below this one). Calling imap_createmailbox() will not work on this mailbox.

- `LATT_NOSELECT` - This is only a container, not a mailbox - you cannot open it.

- `LATT_MARKED` - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers.

- `LATT_UNMARKED` - This mailbox is not marked, does not contain new messages. If either `MARKED` or `UNMARKED` is provided, you can assume the IMAP server supports this feature for this mailbox.

- `LATT_REFERRAL` - This container has a referral to a remote mailbox.

- `LATT_HASCHILDREN` - This mailbox has selectable inferiors.

- `LATT_HASNOCHILDREN` - This mailbox has no selectable inferiors.

The function returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_getmailboxes() example

`<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
foreach ($list as $key => $val) {
echo "($key) ";
echo imap_utf7_decode($val->name) . ",";
echo "'" . $val->delimiter . "',";
echo $val->attributes . "<br />\n";
}
} else {
echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>`

### See Also

- imap_getsubscribed() - List all the subscribed mailboxes

# imap_getsubscribed

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_getsubscribed — List all the subscribed mailboxes

### Description

imap_getsubscribed(IMAP\Connection `$imap`, string `$reference`, string `$pattern`): array|false

Gets information about the subscribed mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

### Parameters

`imap`

  An IMAP\Connection instance.

`reference`

  `reference` should normally be just the server specification as described in imap_open()

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`pattern`

  Specifies where in the mailbox hierarchy to start searching.

  There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

### Return Values

Returns an array of objects containing mailbox information. Each object has the attributes `name`, specifying the full name of the mailbox; `delimiter`, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and `attributes`. `Attributes` is a bitmask that can be tested against:

- `LATT_NOINFERIORS` - This mailbox has no "children" (there are no mailboxes below this one).
- `LATT_NOSELECT` - This is only a container, not a mailbox - you cannot open it.
- `LATT_MARKED` - This mailbox is marked. Only used by UW-IMAPD.
- `LATT_UNMARKED` - This mailbox is not marked. Only used by UW-IMAPD.
- `LATT_REFERRAL` - This container has a referral to a remote mailbox.
- `LATT_HASCHILDREN` - This mailbox has selectable inferiors.
- `LATT_HASNOCHILDREN` - This mailbox has no selectable inferiors.

The function returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

# imap_header

(PHP 4, PHP 5, PHP 7)

imap_header — Alias of imap_headerinfo()

Warning

This alias is REMOVED as of PHP 8.0.0.

### Description

This function is an alias of: imap_headerinfo().

# imap_headerinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_headerinfo — Read the header of the message

### Description

imap_headerinfo(
IMAP\Connection `$imap`,
int `$message_num`,
int `$from_length` = 0,
int `$subject_length` = 0
): stdClass|false

Gets information about the given message number by reading its headers.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number

`from_length`

  Number of characters for the `fetchfrom` property. Must be greater than or equal to zero.

`subject_length`

  Number of characters for the `fetchsubject` property Must be greater than or equal to zero.

### Return Values

Returns `false` on error or, if successful, the information in an object with following properties:

- toaddress - full to: line, up to 1024 characters
- to - an array of objects from the To: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- fromaddress - full from: line, up to 1024 characters
- from - an array of objects from the From: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- ccaddress - full cc: line, up to 1024 characters
- cc - an array of objects from the Cc: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- bccaddress - full bcc: line, up to 1024 characters
- bcc - an array of objects from the Bcc: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- reply_toaddress - full Reply-To: line, up to 1024 characters
- reply_to - an array of objects from the Reply-To: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- senderaddress - full sender: line, up to 1024 characters
- sender - an array of objects from the Sender: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- return_pathaddress - full Return-Path: line, up to 1024 characters
- return_path - an array of objects from the Return-Path: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
- remail -
- date - The message date as found in its headers
- Date - Same as date
- subject - The message subject
- Subject - Same as subject
- in_reply_to -
- message_id -
- newsgroups -
- followup_to -
- references -
- Recent - `R` if recent and seen, `N` if recent and not seen, ' ' if not recent.
- Unseen - `U` if not seen AND not recent, ' ' if seen OR not seen and recent
- Flagged - `F` if flagged, ' ' if not flagged
- Answered - `A` if answered, ' ' if unanswered
- Deleted - `D` if deleted, ' ' if not deleted
- Draft - `X` if draft, ' ' if not draft
- Msgno - The message number
- MailDate -
- Size - The message size
- udate - mail message date in Unix time
- fetchfrom - from line formatted to fit `from_length` characters
- fetchsubject - subject line formatted to fit `subject_length` characters

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | The unused `defaulthost` parameter has been removed.

### See Also

- imap_fetch_overview() - Read an overview of the information in the headers of the given message

# imap_headers

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_headers — Returns headers for all messages in a mailbox

### Description

imap_headers(IMAP\Connection `$imap`): array|false

Returns headers for all messages in a mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Returns an array of string formatted with header info. One element per mail message. Returns `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

# imap_is_open

(PHP 8 >= 8.2.1)

imap_is_open — Check if the IMAP stream is still valid

### Description

imap_is_open(IMAP\Connection `$imap`): bool

Check if the IMAP stream is still valid.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Returns `true` if the stream is still valid, `false` otherwise.

### Examples

Example #1 imap_is_open() example

`<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
imap_is_open($mbox);
// ...
?>`

# imap_last_error

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_last_error — Gets the last IMAP error that occurred during this page request

### Description

imap_last_error(): string|false

Gets the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

### Parameters

This function has no parameters.

### Return Values

Returns the full text of the last IMAP error message that occurred on the current page. Returns `false` if no error messages are available.

### See Also

- imap_errors() - Returns all of the IMAP errors that have occurred

# imap_list

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_list — Read the list of mailboxes

### Description

imap_list(IMAP\Connection `$imap`, string `$reference`, string `$pattern`): array|false

Read the list of mailboxes.

### Parameters

`imap`

  An IMAP\Connection instance.

`reference`

  `reference` should normally be just the server specification as described in imap_open().

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`pattern`

  Specifies where in the mailbox hierarchy to start searching.

  There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

### Return Values

Returns an array containing the names of the mailboxes or `false` in case of failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_list() example

`<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>`

### See Also

- imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one
- imap_lsub() - List all the subscribed mailboxes

# imap_listmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listmailbox — Alias of imap_list()

### Description

This function is an alias of: imap_list().

# imap_listscan

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listscan — Returns the list of mailboxes that matches the given text

### Description

imap_listscan(
IMAP\Connection `$imap`,
string `$reference`,
string `$pattern`,
string `$content`
): array|false

Returns an array containing the names of the mailboxes that have `content` in the text of the mailbox.

This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string `content` inside the mailbox data.

### Parameters

`imap`

  An IMAP\Connection instance.

`reference`

  `reference` should normally be just the server specification as described in imap_open()

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`pattern`

  Specifies where in the mailbox hierarchy to start searching.

  There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

`content`

  The searched string

### Return Values

Returns an array containing the names of the mailboxes that have `content` in the text of the mailbox, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_listmailbox() - Alias of imap_list
- imap_search() - This function returns an array of messages matching the given search criteria

# imap_listsubscribed

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listsubscribed — Alias of imap_lsub()

### Description

This function is an alias of: imap_lsub().

# imap_lsub

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_lsub — List all the subscribed mailboxes

### Description

imap_lsub(IMAP\Connection `$imap`, string `$reference`, string `$pattern`): array|false

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

### Parameters

`imap`

  An IMAP\Connection instance.

`reference`

  `reference` should normally be just the server specification as described in imap_open()

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`pattern`

  Specifies where in the mailbox hierarchy to start searching.

  There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

### Return Values

Returns an array of all the subscribed mailboxes, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_list() - Read the list of mailboxes
- imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one

# imap_mail

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail — Send an email message

### Description

imap_mail(
string `$to`,
string `$subject`,
string `$message`,
?string `$additional_headers` = `null`,
?string `$cc` = `null`,
?string `$bcc` = `null`,
?string `$return_path` = `null`
): bool

This function allows sending of emails with correct handling of Cc and Bcc receivers.

The parameters `to`, `cc` and `bcc` are all strings and are all parsed as » RFC822 address lists.

### Parameters

`to`

  The receiver

`subject`

  The mail subject

`message`

  The mail body, see imap_mail_compose()

`additional_headers`

  As string with additional headers to be set on the mail

`cc`

`bcc`

  The receivers specified in `bcc` will get the mail, but are excluded from the headers.

`return_path`

  Use this parameter to specify return path upon mail delivery failure. This is useful when using PHP as a mail client for multiple users.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.0.0 | `additional_headers`, `cc`, `bcc`, and `return_path` are now nullable.

### See Also

- mail() - Send mail
- imap_mail_compose() - Create a MIME message based on given envelope and body sections

# imap_mail_compose

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_compose — Create a MIME message based on given envelope and body sections

### Description

imap_mail_compose(array `$envelope`, array `$bodies`): string|false

Create a MIME message based on the given `envelope` and `bodies` sections.

### Parameters

`envelope`

  An associative array of header fields. Valid keys are: `"remail"`, `"return_path"`, `"date"`, `"from"`, `"reply_to"`, `"in_reply_to"`, `"subject"`, `"to"`, `"cc"`, `"bcc"` and `"message_id"`, which set the respective message headers to the given string. To set additional headers, the key `"custom_headers"` is supported, which expects an array of those headers, e.g. `["User-Agent: My Mail Client"]`.

`bodies`

  An indexed array of bodies. The first body is the main body of the message; only if it has a type of `TYPEMULTIPART`, further bodies are processed; these bodies constitute the bodies of the parts.

  Body Array Structure
  Key | Type | Description
  --- | --- | ---
  `type` | int | The MIME type. One of `TYPETEXT` (default), `TYPEMULTIPART`, `TYPEMESSAGE`, `TYPEAPPLICATION`, `TYPEAUDIO`, `TYPEIMAGE`, `TYPEMODEL` or `TYPEOTHER`.
  `encoding` | int | The `Content-Transfer-Encoding`. One of `ENC7BIT` (default), `ENC8BIT`, `ENCBINARY`, `ENCBASE64`, `ENCQUOTEDPRINTABLE` or `ENCOTHER`.
  `charset` | string | The charset parameter of the MIME type.
  `type.parameters` | array | An associative array of `Content-Type` parameter names and their values.
  `subtype` | string | The MIME subtype, e.g. `'jpeg'` for `TYPEIMAGE`.
  `id` | string | The `Content-ID`.
  `description` | string | The `Content-Description`.
  `disposition.type` | string | The `Content-Disposition`, e.g. `'attachment'`.
  `disposition` | array | An associative array of `Content-Disposition` parameter names and values.
  `contents.data` | string | The payload.
  `lines` | int | The size of the payload in lines.
  `bytes` | int | The size of the payload in bytes.
  `md5` | string | The MD5 checksum of the payload.

### Return Values

Returns the MIME message as string, or `false` on failure.

### Examples

Example #1 imap_mail_compose() example

`<?php
$envelope["from"]= "joe@example.com";
$envelope["to"] = "foo@example.com";
$envelope["cc"] = "bar@example.com";
$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";
$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);
$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;
$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";
$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;
echo nl2br(imap_mail_compose($envelope, $body));
?>`

# imap_mail_copy

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_copy — Copy specified messages to a mailbox

### Description

imap_mail_copy(
IMAP\Connection `$imap`,
string `$message_nums`,
string `$mailbox`,
int `$flags` = 0
): bool

Copies mail messages specified by `message_nums` to specified mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_nums`

  `message_nums` is a range not just message numbers (as described in » RFC2060).

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`flags`

  `flags` is a bitmask of one or more of

  - `CP_UID` - the sequence numbers contain UIDS
  - `CP_MOVE` - Delete the messages from the current mailbox after copying. If this flag is set, the function behaves identically to imap_mail_move().

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_mail_move() - Move specified messages to a mailbox

# imap_mail_move

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_move — Move specified messages to a mailbox

### Description

imap_mail_move(
IMAP\Connection `$imap`,
string `$message_nums`,
string `$mailbox`,
int `$flags` = 0
): bool

Moves mail messages specified by `message_nums` to the specified `mailbox`. Note that the mail messages are actually copied to the `mailbox`, and the original messages are flagged for deletion. That implies that the messages in `mailbox` are assigned new UIDs.

### Parameters

`imap`

  An IMAP\Connection instance.

`message_nums`

  `message_nums` is a range not just message numbers (as described in » RFC2060).

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`flags`

  `flags` is a bitmask and may contain the single option:

  - `CP_UID` - the sequence numbers contain UIDS

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Notes

> Note:

> imap_mail_move() will flag the original mail with a delete flag, to successfully delete it a call to the imap_expunge() function must be made.

### See Also

- imap_mail_copy() - Copy specified messages to a mailbox

# imap_mailboxmsginfo

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mailboxmsginfo — Get information about the current mailbox

### Description

imap_mailboxmsginfo(IMAP\Connection `$imap`): stdClass

Checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Returns the information in an object with following properties:

Mailbox properties
Date | date of last change (current datetime)
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_mailboxmsginfo() example

`<?php
$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
or die("can't connect: " . imap_last_error());
$check = imap_mailboxmsginfo($mbox);
if ($check) {
echo "Date: " . $check->Date . "<br />\n" ;
echo "Driver: " . $check->Driver . "<br />\n" ;
echo "Mailbox: " . $check->Mailbox . "<br />\n" ;
echo "Messages: " . $check->Nmsgs . "<br />\n" ;
echo "Recent: " . $check->Recent . "<br />\n" ;
echo "Unread: " . $check->Unread . "<br />\n" ;
echo "Deleted: " . $check->Deleted . "<br />\n" ;
echo "Size: " . $check->Size . "<br />\n" ;
} else {
echo "imap_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n";
}
imap_close($mbox);
?>`

# imap_mime_header_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mime_header_decode — Decode MIME header elements

### Description

imap_mime_header_decode(string `$string`): array|false

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

### Parameters

`string`

  The MIME text

### Return Values

The decoded elements are returned in an array of objects, where each object has two properties, `charset` and `text`.

If the element hasn't been encoded, and in other words is in plain US-ASCII, the `charset` property of that element is set to `default`.

The function returns `false` on failure.

### Examples

Example #1 imap_mime_header_decode() example

`<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";
$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
echo "Charset: {$elements[$i]->charset}\n";
echo "Text: {$elements[$i]->text}\n\n";
}
?>`

The above example will output:

    Charset: ISO-8859-1
    Text: Keld Jørn Simonsen

    Charset: default
    Text:  <keld@example.com>

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

### See Also

- imap_utf8() - Converts MIME-encoded text to UTF-8

# imap_msgno

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_msgno — Gets the message sequence number for the given UID

### Description

imap_msgno(IMAP\Connection `$imap`, int `$message_uid`): int

Returns the message sequence number for the given `message_uid`.

This function is the inverse of imap_uid().

### Parameters

`imap`

  An IMAP\Connection instance.

`message_uid`

  The message UID

### Return Values

Returns the message sequence number for the given `message_uid`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_uid() - This function returns the UID for the given message sequence number

# imap_mutf7_to_utf8

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8

### Description

imap_mutf7_to_utf8(string `$string`): string|false

Decode a modified UTF-7 (as specified in RFC 2060, section 5.1.3) string to UTF-8.

> Note:

> This function is only available, if libcclient exports utf8_to_mutf7().

### Parameters

`string`

  A string encoded in modified UTF-7.

### Return Values

Returns `string` converted to UTF-8, or `false` on failure.

### See Also

- imap_utf8_to_mutf7() - Encode a UTF-8 string to modified UTF-7

# imap_num_msg

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_num_msg — Gets the number of messages in the current mailbox

### Description

imap_num_msg(IMAP\Connection `$imap`): int|false

Gets the number of messages in the current mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Return the number of messages in the current mailbox, as an integer, or `false` on error.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_num_recent() - Gets the number of recent messages in current mailbox
- imap_status() - Returns status information on a mailbox

# imap_num_recent

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_num_recent — Gets the number of recent messages in current mailbox

### Description

imap_num_recent(IMAP\Connection `$imap`): int

Gets the number of recent messages in the current mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

Returns the number of recent messages in the current mailbox, as an integer.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_num_msg() - Gets the number of messages in the current mailbox
- imap_status() - Returns status information on a mailbox

# imap_open

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_open — Open an IMAP stream to a mailbox

### Description

imap_open(
string `$mailbox`,
string `$user`,
string `$password`,
int `$flags` = 0,
int `$retries` = 0,
array `$options` = []
): IMAP\Connection|false

Opens an IMAP stream to a `mailbox`.

This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

### Parameters

`mailbox`

  A mailbox name consists of a server and a mailbox path on this server. The special name `INBOX` stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

  The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/').

  The server part is mandatory in all mailbox parameters.

  All names which start with `{` are remote names, and are in the form `"{" remote_system_name [":" port] [flags] "}" [mailbox_name]` where:

  - `remote_system_name` - Internet domain name or bracketed IP address of server.
  - `port` - optional TCP port number, default is the default port for that service
  - `flags` - optional flags, see following table.
  - `mailbox_name` - remote mailbox name, default is INBOX

  Optional flags for names
  Flag | Description
  --- | ---
  `/service=`service | mailbox access service, default is "imap"
  `/user=`user | remote user name for login on the server
  `/authuser=`user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
  `/anonymous` | remote access as anonymous user
  `/debug` | record protocol telemetry in application's debug log
  `/secure` | do not transmit a plaintext password over the network
  `/imap`, `/imap2`, `/imap2bis`, `/imap4`, `/imap4rev1` | equivalent to `/service=imap`
  `/pop3` | equivalent to `/service=pop3`
  `/nntp` | equivalent to `/service=nntp`
  `/norsh` | do not use rsh or ssh to establish a preauthenticated IMAP session
  `/ssl` | use the `Secure Socket Layer` to encrypt the session
  `/validate-cert` | validate certificates from TLS/SSL server (this is the default behavior)
  `/novalidate-cert` | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
  `/tls` | force use of `start-TLS` to encrypt the session, and reject connection to servers that do not support it
  `/notls` | do not do `start-TLS` to encrypt the session, even with servers that support it
  `/readonly` | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

`user`

  The user name

`password`

  The password associated with the `user`

`flags`

  The `flags` are a bit mask with one or more of the following:

  - `OP_READONLY` - Open mailbox read-only
  - `OP_ANONYMOUS` - Don't use or update a .newsrc for news (NNTP only)
  - `OP_HALFOPEN` - For IMAP and NNTP names, open a connection but don't open a mailbox.
  - `CL_EXPUNGE` - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
  - `OP_DEBUG` - Debug protocol negotiations
  - `OP_SHORTCACHE` - Short (`elt`-only) caching
  - `OP_SILENT` - Don't pass up events (internal use)
  - `OP_PROTOTYPE` - Return driver prototype
  - `OP_SECURE` - Don't do non-secure authentication
`retries`

  Number of maximum connect attempts

`options`

  Connection parameters, the following (string) keys maybe used to set one or more connection parameters:

  - `DISABLE_AUTHENTICATOR` - Disable authentication properties

### Return Values

Returns an IMAP\Connection instance on success, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | Returns an IMAP\Connection instance now; previously, a resource was returned.

### Examples

Example #1 Different use of imap_open()

`<?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");
// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");
// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");
// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");
// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?>`

Example #2 imap_open() example

`<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");
if ($folders == false) {
echo "Call failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
?>`

### See Also

- imap_close() - Close an IMAP stream

# imap_ping

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_ping — Check if the IMAP stream is still active

### Description

imap_ping(IMAP\Connection `$imap`): bool

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

### Parameters

`imap`

  An IMAP\Connection instance.

### Return Values

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

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_ping() Example

`<?php
$imap = imap_open("{imap.example.org}", "mailadmin", "password");
// after some sleeping
if (!imap_ping($imap)) {
// do some stuff to reconnect
}
?>`

# imap_qprint

(PHP 4, PHP 5, PHP 7, PHP 8)

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

### Description

imap_qprint(string `$string`): string|false

Convert a quoted-printable string to an 8 bit string according to » RFC2045, section 6.7.

### Parameters

`string`

  A quoted-printable string

### Return Values

Returns an 8 bits string, or `false` on failure.

### See Also

- imap_8bit() - Convert an 8bit string to a quoted-printable string

# imap_rename

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rename — Alias of imap_renamemailbox()

### Description

This function is an alias of: imap_renamemailbox().

# imap_renamemailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_renamemailbox — Rename an old mailbox to new mailbox

### Description

imap_renamemailbox(IMAP\Connection `$imap`, string `$from`, string `$to`): bool

This function renames on old mailbox to new mailbox (see imap_open() for the format of `mbox` names).

### Parameters

`imap`

  An IMAP\Connection instance.

`from`

  The old mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`to`

  The new mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_createmailbox() - Create a new mailbox
- imap_deletemailbox() - Delete a mailbox

# imap_reopen

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_reopen — Reopen IMAP stream to new mailbox

### Description

imap_reopen(
IMAP\Connection `$imap`,
string `$mailbox`,
int `$flags` = 0,
int `$retries` = 0
): bool

Reopens the specified stream to a new `mailbox` on an IMAP or NNTP server.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`flags`

  The `flags` are a bit mask with one or more of the following:

  - `OP_READONLY` - Open mailbox read-only
  - `OP_ANONYMOUS` - Don't use or update a .newsrc for news (NNTP only)
  - `OP_HALFOPEN` - For IMAP and NNTP names, open a connection but don't open a mailbox.
  - `OP_EXPUNGE` - Silently expunge recycle stream
  - `CL_EXPUNGE` - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
`retries`

  Number of maximum connect attempts

### Return Values

Returns `true` if the stream is reopened, `false` otherwise.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_reopen() example

`<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?>`

# imap_rfc822_parse_adrlist

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_parse_adrlist — Parses an address string

### Description

imap_rfc822_parse_adrlist(string `$string`, string `$default_hostname`): array

Parses the address string as defined in » RFC2822 and for each address.

### Parameters

`string`

  A string containing addresses

`default_hostname`

  The default host name

### Return Values

Returns an array of objects. The objects properties are:

- mailbox - the mailbox name (username)
- host - the host name
- personal - the personal name
- adl - at domain source route

### Examples

Example #1 imap_rfc822_parse_adrlist() example

`<?php
$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
die("something is wrong\n");
}
foreach ($address_array as $id => $val) {
echo "# $id\n";
echo " mailbox : " . $val->mailbox . "\n";
echo " host : " . $val->host . "\n";
echo " personal: " . $val->personal . "\n";
echo " adl : " . $val->adl . "\n";
}
?>`

The above example will output:

    # 0
      mailbox : doe
      host    : example.com
      personal: Joe Doe
      adl     :
    # 1
      mailbox : postmaster
      host    : example.com
      personal:
      adl     :
    # 2
      mailbox : root
      host    : example.com
      personal:
      adl     :

### See Also

- imap_rfc822_parse_headers() - Parse mail headers from a string

# imap_rfc822_parse_headers

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_parse_headers — Parse mail headers from a string

### Description

imap_rfc822_parse_headers(string `$headers`, string `$default_hostname` = "UNKNOWN"): stdClass

Gets an object of various header elements, similar to imap_header().

### Parameters

`headers`

  The parsed headers data

`default_hostname`

  The default host name

### Return Values

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

### See Also

- imap_rfc822_parse_adrlist() - Parses an address string

# imap_rfc822_write_address

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info

### Description

imap_rfc822_write_address(string `$mailbox`, string `$hostname`, string `$personal`): string|false

Returns a properly formatted email address as defined in » RFC2822 given the needed information.

### Parameters

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`hostname`

  The email host part

`personal`

  The name of the account owner

### Return Values

Returns a string properly formatted email address as defined in » RFC2822, or `false` on failure.

### Examples

Example #1 imap_rfc822_write_address() example

`<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>`

The above example will output:

    Hartmut Holzgraefe <hartmut@example.com>

# imap_savebody

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

imap_savebody — Save a specific body section to a file

### Description

imap_savebody(
IMAP\Connection `$imap`,
resource|string|int `$file`,
int `$message_num`,
string `$section` = "",
int `$flags` = 0
): bool

Saves a part or the whole body of the specified message.

### Parameters

`imap`

  An IMAP\Connection instance.

`file`

  The path to the saved file as a string, or a valid file descriptor returned by fopen().

`message_num`

  The message number

`section`

  The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

`flags`

  A bitmask with one or more of the following:

  - `FT_UID` - The `message_num` is a UID
  - `FT_PEEK` - Do not set the \Seen flag if not already set
  - `FT_INTERNAL` - The return string is in internal format, will not canonicalize to CRLF.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

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

# imap_scan

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_scan — Alias of imap_listscan()

### Description

This function is an alias of: imap_listscan().

# imap_scanmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_scanmailbox — Alias of imap_listscan()

### Description

This function is an alias of: imap_listscan().

# imap_search

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_search — This function returns an array of messages matching the given search criteria

### Description

imap_search(
IMAP\Connection `$imap`,
string `$criteria`,
int `$flags` = `SE_FREE`,
string `$charset` = ""
): array|false

This function performs a search on the mailbox currently opened in the given IMAP stream.

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also » RFC1176, section "tag SEARCH search_criteria").

### Parameters

`imap`

  An IMAP\Connection instance.

`criteria`

  A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. `FROM "joey smith"`) must be quoted. Results will match all `criteria` entries.

  - ALL - return all messages matching the rest of the criteria
  - ANSWERED - match messages with the \\ANSWERED flag set
  - BCC "string" - match messages with "string" in the Bcc: field
  - BEFORE "date" - match messages with Date: before "date"
  - BODY "string" - match messages with "string" in the body of the message
  - CC "string" - match messages with "string" in the Cc: field
  - DELETED - match deleted messages
  - FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
  - FROM "string" - match messages with "string" in the From: field
  - KEYWORD "string" - match messages with "string" as a keyword
  - NEW - match new messages
  - OLD - match old messages
  - ON "date" - match messages with Date: matching "date"
  - RECENT - match messages with the \\RECENT flag set
  - SEEN - match messages that have been read (the \\SEEN flag is set)
  - SINCE "date" - match messages with Date: after "date"
  - SUBJECT "string" - match messages with "string" in the Subject:
  - TEXT "string" - match messages with text "string"
  - TO "string" - match messages with "string" in the To:
  - UNANSWERED - match messages that have not been answered
  - UNDELETED - match messages that are not deleted
  - UNFLAGGED - match messages that are not flagged
  - UNKEYWORD "string" - match messages that do not have the keyword "string"
  - UNSEEN - match messages which have not been read yet
`flags`

  Valid values for `flags` are `SE_UID`, which causes the returned array to contain UIDs instead of messages sequence numbers.

`charset`

  MIME character set to use when searching strings.

### Return Values

Returns an array of message numbers or UIDs.

Return `false` if it does not understand the search `criteria` or no messages have been found.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_search() example

`<?php
$imap = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);
$some = imap_search($imap, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($imap, 'ALL');
$uids = imap_search($imap, 'ALL', SE_UID);
print_r($some);
print_r($msgnos);
print_r($uids);
?>`

The above example will output something similar to:

    Array
    (
        [0] => 4
        [1] => 6
        [2] => 11
    )
    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 6
    )
    Array
    (
        [0] => 1
        [1] => 4
        [2] => 6
        [3] => 8
        [4] => 11
        [5] => 12
    )

### See Also

- imap_listscan() - Returns the list of mailboxes that matches the given text

# imap_set_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

imap_set_quota — Sets a quota for a given mailbox

### Description

imap_set_quota(IMAP\Connection `$imap`, string `$quota_root`, int `$mailbox_size`): bool

Sets an upper limit quota on a per mailbox basis.

### Parameters

`imap`

  An IMAP\Connection instance.

`quota_root`

  The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: `user.name`.

`mailbox_size`

  The maximum size (in KB) for the `quota_root`

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_set_quota() example

`<?php
$mbox = imap_open("{imap.example.org:143}", "mailadmin", "password");
if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
echo "Error in setting quota\n";
return;
}
imap_close($mbox);
?>`

### Notes

This function is currently only available to users of the c-client2000 or greater library.

The given `imap` must be opened as the mail administrator, other wise this function will fail.

### See Also

- imap_open() - Open an IMAP stream to a mailbox
- imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

# imap_setacl

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imap_setacl — Sets the ACL for a given mailbox

### Description

imap_setacl(
IMAP\Connection `$imap`,
string `$mailbox`,
string `$user_id`,
string `$rights`
): bool

Sets the ACL for a giving mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`user_id`

  The user to give the rights to.

`rights`

  The rights to give to the user. Passing an empty string will delete acl.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Notes

This function is currently only available to users of the c-client2000 or greater library.

### See Also

- imap_getacl() - Gets the ACL for a given mailbox

# imap_setflag_full

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_setflag_full — Sets flags on messages

### Description

imap_setflag_full(
IMAP\Connection `$imap`,
string `$sequence`,
string `$flag`,
int `$options` = 0
): true

Causes a store to add the specified `flag` to the flags set for the messages in the specified `sequence`.

### Parameters

`imap`

  An IMAP\Connection instance.

`sequence`

  A sequence of message numbers. You can enumerate desired messages with the `X,Y` syntax, or retrieve all messages within an interval with the `X:Y` syntax

`flag`

  The flags which you can set are `\Seen`, `\Answered`, `\Flagged`, `\Deleted`, and `\Draft` as defined by » RFC2060.

`options`

  A bit mask that may contain the single option:

  - `ST_UID` - The sequence argument contains UIDs instead of sequence numbers

### Return Values

Always returns `true`.

### Errors/Exceptions

Throws a ValueError if `options` is invalid.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | A ValueError is now thrown on invalid `options` parameter values. Previously, a warning was emitted and the function returned `false`.

### Examples

Example #1 imap_setflag_full() example

`<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
or die("can't connect: " . imap_last_error());
$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");
echo gettype($status) . "\n";
echo $status . "\n";
imap_close($mbox);
?>`

### See Also

- imap_clearflag_full() - Clears flags on messages

# imap_sort

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_sort — Gets and sort messages

### Description

imap_sort(
IMAP\Connection `$imap`,
int `$criteria`,
bool `$reverse`,
int `$flags` = 0,
?string `$search_criteria` = `null`,
?string `$charset` = `null`
): array|false

Gets and sorts message numbers by the given parameters.

### Parameters

`imap`

  An IMAP\Connection instance.

`criteria`

  Criteria can be one (and only one) of the following:

  - `SORTDATE` - message Date
  - `SORTARRIVAL` - arrival date
  - `SORTFROM` - mailbox in first From address
  - `SORTSUBJECT` - message subject
  - `SORTTO` - mailbox in first To address
  - `SORTCC` - mailbox in first cc address
  - `SORTSIZE` - size of message in octets
`reverse`

  Whether to sort in reverse order.

`flags`

  The `flags` are a bitmask of one or more of the following:

  - `SE_UID` - Return UIDs instead of sequence numbers
  - `SE_NOPREFETCH` - Don't prefetch searched messages
`search_criteria`

  IMAP2-format search criteria string. For details see imap_search().

`charset`

  MIME character set to use when sorting strings.

### Return Values

Returns an array of message numbers sorted by the given parameters, or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.
8.0.0 | `reverse` is now bool instead of int.
8.0.0 | `search_criteria` and `charset` are now nullable.

# imap_status

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_status — Returns status information on a mailbox

### Description

imap_status(IMAP\Connection `$imap`, string `$mailbox`, int `$flags`): stdClass|false

Gets status information about the given `mailbox`.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

`flags`

  Valid flags are:

  - `SA_MESSAGES` - set $status->messages to the number of messages in the mailbox
  - `SA_RECENT` - set $status->recent to the number of recent messages in the mailbox
  - `SA_UNSEEN` - set $status->unseen to the number of unseen (new) messages in the mailbox
  - `SA_UIDNEXT` - set $status->uidnext to the next uid to be used in the mailbox
  - `SA_UIDVALIDITY` - set $status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid
  - `SA_ALL` - set all of the above

### Return Values

This function returns an object containing status information, or `false` on failure. The object has the following properties: `messages`, `recent`, `unseen`, `uidnext`, and `uidvalidity`.

`flags` is also set, which contains a bitmask which can be checked against any of the above constants.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_status() example

`<?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
} else {
echo "imap_status failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>`

# imap_subscribe

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_subscribe — Subscribe to a mailbox

### Description

imap_subscribe(IMAP\Connection `$imap`, string `$mailbox`): bool

Subscribe to a new mailbox.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_unsubscribe() - Unsubscribe from a mailbox

# imap_thread

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imap_thread — Returns a tree of threaded message

### Description

imap_thread(IMAP\Connection `$imap`, int `$flags` = `SE_FREE`): array|false

Gets a tree of a threaded message.

### Parameters

`imap`

  An IMAP\Connection instance.

`flags`

### Return Values

imap_thread() returns an associative array containing a tree of messages threaded by `REFERENCES`, or `false` on error.

Every message in the current mailbox will be represented by three entries in the resulting array:

- $thread["XX.num"] - current message number

- $thread["XX.next"]

- $thread["XX.branch"]

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Examples

Example #1 imap_thread() Example

`<?php
// Here we're outputting the threads of a newsgroup, in HTML
$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);
foreach ($threads as $key => $val) {
$tree = explode('.', $key);
if ($tree[1] == 'num') {
$header = imap_headerinfo($nntp, $val);
echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
} elseif ($tree[1] == 'branch') {
echo "\t</li>\n</ul>\n";
}
}
imap_close($nntp);
?>`

# imap_timeout

(PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8)

imap_timeout — Set or fetch imap timeout

### Description

imap_timeout(int `$timeout_type`, int `$timeout` = -1): int|bool

Sets or fetches the imap timeout.

### Parameters

`timeout_type`

  One of the following: `IMAP_OPENTIMEOUT`, `IMAP_READTIMEOUT`, `IMAP_WRITETIMEOUT`, or `IMAP_CLOSETIMEOUT`.

`timeout`

  The timeout, in seconds.

### Return Values

If the `timeout` parameter is set, this function returns `true` on success and `false` on failure.

If `timeout` is not provided or evaluates to -1, the current timeout value of `timeout_type` is returned as an integer.

### Examples

Example #1 imap_timeout() example

`<?php
echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";
?>`

# imap_uid

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_uid — This function returns the UID for the given message sequence number

### Description

imap_uid(IMAP\Connection `$imap`, int `$message_num`): int|false

This function returns the UID for the given message sequence number. An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes.

This function is the inverse of imap_msgno().

### Parameters

`imap`

  An IMAP\Connection instance.

`message_num`

  The message number.

### Return Values

The UID of the given message.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### Notes

> Note:

> This function is not supported by POP3 mailboxes.

### See Also

- imap_msgno() - Gets the message sequence number for the given UID

# imap_undelete

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_undelete — Unmark the message which is marked deleted

### Description

imap_undelete(IMAP\Connection `$imap`, string `$message_nums`, int `$flags` = 0): true

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

### Parameters

`imap`

  An IMAP\Connection instance.

`message_nums`

  A string representing one or more messages in IMAP4-style sequence format (`"n"`, `"n:m"`, or combination of these delimited by commas).

`flags`

### Return Values

Always returns `true`.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_delete() - Mark a message for deletion from current mailbox
- imap_mail_move() - Move specified messages to a mailbox

# imap_unsubscribe

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_unsubscribe — Unsubscribe from a mailbox

### Description

imap_unsubscribe(IMAP\Connection `$imap`, string `$mailbox`): bool

Unsubscribe from the specified `mailbox`.

### Parameters

`imap`

  An IMAP\Connection instance.

`mailbox`

  The mailbox name, see imap_open() for more information

  Warning

  Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

### Return Values

Returns `true` on success or `false` on failure.

### Changelog

Version | Description
--- | ---
8.1.0 | The `imap` parameter expects an IMAP\Connection instance now; previously, a valid `imap` resource was expected.

### See Also

- imap_subscribe() - Subscribe to a mailbox

# imap_utf7_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

### Description

imap_utf7_decode(string `$string`): string|false

Decodes modified UTF-7 `string` into ISO-8859-1 string.

This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.

### Parameters

`string`

  A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3.

### Return Values

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in `string`, or `false` if `string` contains invalid modified UTF-7 sequence or `string` contains a character that is not part of ISO-8859-1 character set.

### See Also

- imap_utf7_encode() - Converts ISO-8859-1 string to modified UTF-7 text

# imap_utf7_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

### Description

imap_utf7_encode(string `$string`): string

Converts `string` to modified UTF-7 text.

This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.

### Parameters

`string`

  An ISO-8859-1 string.

### Return Values

Returns `string` encoded with the modified UTF-7 encoding as defined in » RFC 2060, section 5.1.3.

### See Also

- imap_utf7_decode() - Decodes a modified UTF-7 encoded string

# imap_utf8

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf8 — Converts MIME-encoded text to UTF-8

### Description

imap_utf8(string `$mime_encoded_text`): string

Converts the given `mime_encoded_text` to UTF-8, if the declared charset is known to libc-client. Otherwise the given text is decoded, but not converted to UTF-8.

### Parameters

`mime_encoded_text`

  A MIME encoded string. MIME encoding method and the UTF-8 specification are described in » RFC2047 and » RFC2044 respectively.

### Return Values

Returns the decoded string, if possible converted to UTF-8.

### Examples

Example #1 Basic imap_utf8() Usage

`<?php
echo imap_utf8("Johannes =?ISO-8859-1?Q?Schl=FCter?=");
?>`

The above example will output something similar to:

    Johannes Schlüter

### See Also

- imap_mime_header_decode() - Decode MIME header elements

# imap_utf8_to_mutf7

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7

### Description

imap_utf8_to_mutf7(string `$string`): string|false

Encode a UTF-8 string to modified UTF-7 (as specified in RFC 2060, section 5.1.3).

> Note:

> This function is only available, if libcclient exports utf8_to_mutf7().

### Parameters

`string`

  A UTF-8 encoded string.

### Return Values

Returns `string` converted to modified UTF-7, or `false` on failure.

### See Also

- imap_mutf7_to_utf8() - Decode a modified UTF-7 string to UTF-8

## Table of Contents

- imap_8bit — Convert an 8bit string to a quoted-printable string
- imap_alerts — Returns all IMAP alert messages that have occurred
- imap_append — Append a string message to a specified mailbox
- imap_base64 — Decode BASE64 encoded text
- imap_binary — Convert an 8bit string to a base64 string
- imap_body — Read the message body
- imap_bodystruct — Read the structure of a specified body section of a specific message
- imap_check — Check current mailbox
- imap_clearflag_full — Clears flags on messages
- imap_close — Close an IMAP stream
- imap_create — Alias of imap_createmailbox
- imap_createmailbox — Create a new mailbox
- imap_delete — Mark a message for deletion from current mailbox
- imap_deletemailbox — Delete a mailbox
- imap_errors — Returns all of the IMAP errors that have occurred
- imap_expunge — Delete all messages marked for deletion
- imap_fetch_overview — Read an overview of the information in the headers of the given message
- imap_fetchbody — Fetch a particular section of the body of the message
- imap_fetchheader — Returns header for a message
- imap_fetchmime — Fetch MIME headers for a particular section of the message
- imap_fetchstructure — Read the structure of a particular message
- imap_fetchtext — Alias of imap_body
- imap_gc — Clears IMAP cache
- imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
- imap_get_quotaroot — Retrieve the quota settings per user
- imap_getacl — Gets the ACL for a given mailbox
- imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
- imap_getsubscribed — List all the subscribed mailboxes
- imap_header — Alias of imap_headerinfo
- imap_headerinfo — Read the header of the message
- imap_headers — Returns headers for all messages in a mailbox
- imap_is_open — Check if the IMAP stream is still valid
- imap_last_error — Gets the last IMAP error that occurred during this page request
- imap_list — Read the list of mailboxes
- imap_listmailbox — Alias of imap_list
- imap_listscan — Returns the list of mailboxes that matches the given text
- imap_listsubscribed — Alias of imap_lsub
- imap_lsub — List all the subscribed mailboxes
- imap_mail — Send an email message
- imap_mail_compose — Create a MIME message based on given envelope and body sections
- imap_mail_copy — Copy specified messages to a mailbox
- imap_mail_move — Move specified messages to a mailbox
- imap_mailboxmsginfo — Get information about the current mailbox
- imap_mime_header_decode — Decode MIME header elements
- imap_msgno — Gets the message sequence number for the given UID
- imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8
- imap_num_msg — Gets the number of messages in the current mailbox
- imap_num_recent — Gets the number of recent messages in current mailbox
- imap_open — Open an IMAP stream to a mailbox
- imap_ping — Check if the IMAP stream is still active
- imap_qprint — Convert a quoted-printable string to an 8 bit string
- imap_rename — Alias of imap_renamemailbox
- imap_renamemailbox — Rename an old mailbox to new mailbox
- imap_reopen — Reopen IMAP stream to new mailbox
- imap_rfc822_parse_adrlist — Parses an address string
- imap_rfc822_parse_headers — Parse mail headers from a string
- imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
- imap_savebody — Save a specific body section to a file
- imap_scan — Alias of imap_listscan
- imap_scanmailbox — Alias of imap_listscan
- imap_search — This function returns an array of messages matching the given search criteria
- imap_set_quota — Sets a quota for a given mailbox
- imap_setacl — Sets the ACL for a given mailbox
- imap_setflag_full — Sets flags on messages
- imap_sort — Gets and sort messages
- imap_status — Returns status information on a mailbox
- imap_subscribe — Subscribe to a mailbox
- imap_thread — Returns a tree of threaded message
- imap_timeout — Set or fetch imap timeout
- imap_uid — This function returns the UID for the given message sequence number
- imap_undelete — Unmark the message which is marked deleted
- imap_unsubscribe — Unsubscribe from a mailbox
- imap_utf7_decode — Decodes a modified UTF-7 encoded string
- imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
- imap_utf8 — Converts MIME-encoded text to UTF-8
- imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7

# The IMAP\Connection class

(PHP 8 >= 8.1.0)

## Introduction

A fully opaque class which replaces a `imap` resource as of PHP 8.1.0.

## Class synopsis

final class IMAP\Connection {
}

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- IMAP Functions
  - imap_8bit — Convert an 8bit string to a quoted-printable string
  - imap_alerts — Returns all IMAP alert messages that have occurred
  - imap_append — Append a string message to a specified mailbox
  - imap_base64 — Decode BASE64 encoded text
  - imap_binary — Convert an 8bit string to a base64 string
  - imap_body — Read the message body
  - imap_bodystruct — Read the structure of a specified body section of a specific message
  - imap_check — Check current mailbox
  - imap_clearflag_full — Clears flags on messages
  - imap_close — Close an IMAP stream
  - imap_create — Alias of imap_createmailbox
  - imap_createmailbox — Create a new mailbox
  - imap_delete — Mark a message for deletion from current mailbox
  - imap_deletemailbox — Delete a mailbox
  - imap_errors — Returns all of the IMAP errors that have occurred
  - imap_expunge — Delete all messages marked for deletion
  - imap_fetch_overview — Read an overview of the information in the headers of the given message
  - imap_fetchbody — Fetch a particular section of the body of the message
  - imap_fetchheader — Returns header for a message
  - imap_fetchmime — Fetch MIME headers for a particular section of the message
  - imap_fetchstructure — Read the structure of a particular message
  - imap_fetchtext — Alias of imap_body
  - imap_gc — Clears IMAP cache
  - imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
  - imap_get_quotaroot — Retrieve the quota settings per user
  - imap_getacl — Gets the ACL for a given mailbox
  - imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
  - imap_getsubscribed — List all the subscribed mailboxes
  - imap_header — Alias of imap_headerinfo
  - imap_headerinfo — Read the header of the message
  - imap_headers — Returns headers for all messages in a mailbox
  - imap_is_open — Check if the IMAP stream is still valid
  - imap_last_error — Gets the last IMAP error that occurred during this page request
  - imap_list — Read the list of mailboxes
  - imap_listmailbox — Alias of imap_list
  - imap_listscan — Returns the list of mailboxes that matches the given text
  - imap_listsubscribed — Alias of imap_lsub
  - imap_lsub — List all the subscribed mailboxes
  - imap_mail — Send an email message
  - imap_mail_compose — Create a MIME message based on given envelope and body sections
  - imap_mail_copy — Copy specified messages to a mailbox
  - imap_mail_move — Move specified messages to a mailbox
  - imap_mailboxmsginfo — Get information about the current mailbox
  - imap_mime_header_decode — Decode MIME header elements
  - imap_msgno — Gets the message sequence number for the given UID
  - imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8
  - imap_num_msg — Gets the number of messages in the current mailbox
  - imap_num_recent — Gets the number of recent messages in current mailbox
  - imap_open — Open an IMAP stream to a mailbox
  - imap_ping — Check if the IMAP stream is still active
  - imap_qprint — Convert a quoted-printable string to an 8 bit string
  - imap_rename — Alias of imap_renamemailbox
  - imap_renamemailbox — Rename an old mailbox to new mailbox
  - imap_reopen — Reopen IMAP stream to new mailbox
  - imap_rfc822_parse_adrlist — Parses an address string
  - imap_rfc822_parse_headers — Parse mail headers from a string
  - imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
  - imap_savebody — Save a specific body section to a file
  - imap_scan — Alias of imap_listscan
  - imap_scanmailbox — Alias of imap_listscan
  - imap_search — This function returns an array of messages matching the given search criteria
  - imap_set_quota — Sets a quota for a given mailbox
  - imap_setacl — Sets the ACL for a given mailbox
  - imap_setflag_full — Sets flags on messages
  - imap_sort — Gets and sort messages
  - imap_status — Returns status information on a mailbox
  - imap_subscribe — Subscribe to a mailbox
  - imap_thread — Returns a tree of threaded message
  - imap_timeout — Set or fetch imap timeout
  - imap_uid — This function returns the UID for the given message sequence number
  - imap_undelete — Unmark the message which is marked deleted
  - imap_unsubscribe — Unsubscribe from a mailbox
  - imap_utf7_decode — Decodes a modified UTF-7 encoded string
  - imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
  - imap_utf8 — Converts MIME-encoded text to UTF-8
  - imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7
- IMAP\Connection — The IMAP\Connection class

# Mail

# Introduction

The mail() function allows you to send mail.

# Installing/Configuring

## Table of Contents

- Requirements
- Runtime Configuration

## Requirements

For the Mail functions to be available, PHP must have access to the `sendmail` binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: `/usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib`. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mail configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mail.add_x_header | "0" | `INI_PERDIR` |
mail.mixed_lf_and_crlf | "0" | `INI_SYSTEM`|`INI_PERDIR` | Added in PHP 8.2.4
mail.log | NULL | `INI_SYSTEM`|`INI_PERDIR` |
mail.force_extra_parameters | NULL | `INI_SYSTEM` |
SMTP | "localhost" | `INI_ALL` |
smtp_port | "25" | `INI_ALL` |
sendmail_from | NULL | `INI_ALL` |
sendmail_path | "/usr/sbin/sendmail -t -i" | `INI_SYSTEM` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mail.add_x_header` bool

  Add `X-PHP-Originating-Script` that will include UID of the script followed by the filename.

`mail.log` string

  The path to a log file that will log all mail() calls. Log entries include the full path of the script, line number, `To` address and headers.

`mail.mixed_lf_and_crlf` bool

  Allows reverting the line separator for email headers and message bodies to LF (Line Feed), mimicking the non-compliant behavior of PHP 7. It is provided as a compatibility measure for certain non-compliant Mail Transfer Agents (MTAs) that fail to correctly process CRLF (Carriage Return + Line Feed) as a line separator in email headers and message content.

`mail.force_extra_parameters` string

  Force the addition of the specified parameters to be passed as extra parameters to the sendmail binary. These parameters will always replace the value of the 5th parameter to mail().

  In addition to the default behavior for `INI_SYSTEM`, this value can also be set with `php_value` in httpd.conf (but this is not recommended).
`SMTP` string

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

`smtp_port` int

  Used under Windows only: Number of the port to connect to the server specified with the `SMTP` setting when sending mail with mail(); defaults to 25.

`sendmail_from` string

  Which `"From:"` mail address should be used in mail sent directly via SMTP (Windows only). This directive also sets the `"Return-Path:"` header.

`sendmail_path` string

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

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

  qmail-inject does not require any option to process mail correctly.

  This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

# Mail Functions

# ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ezmlm_hash — Calculate the hash value needed by EZMLM

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

ezmlm_hash(string `$addr`): int

ezmlm_hash() calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database.

### Parameters

`addr`

  The email address that's being hashed.

### Return Values

The hash value of `addr`.

### Changelog

Version | Description
--- | ---
8.0.0 | Removed this function.
7.2.0 | Deprecated this function.

### Examples

Example #1 Calculating the hash and subscribing a user

`<?php
$user = "joecool@example.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface
?>`

# mail

(PHP 4, PHP 5, PHP 7, PHP 8)

mail — Send mail

### Description

mail(
string `$to`,
string `$subject`,
string `$message`,
array|string `$additional_headers` = [],
string `$additional_params` = ""
): bool

Sends an email.

### Parameters

`to`

  Receiver, or receivers of the mail.

  The formatting of this string must comply with » RFC 2822. Some examples are:

  - user@example.com
  - user@example.com, anotheruser@example.com
  - User
  - User , Another User
`subject`

  Subject of the email to be sent.

  Caution

  Subject must satisfy » RFC 2047.

`message`

  Message to be sent.

  Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters.

  Caution

  (Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

  `<?php
  $text = str_replace("\n.", "\n..", $text);
  ?>`
`additional_headers` (optional)

  String or array to be inserted at the end of the email header.

  This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

  If an array is passed, its keys are the header names and its values are the respective header values.

  > Note:

  > When sending mail, the mail must contain a `From` header. This can be set with the `additional_headers` parameter, or a default can be set in php.ini.

  > Failing to do this will result in an error message similar to `Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing`. The `From` header sets also `Return-Path` when sending directly via SMTP (Windows only).

  > Note:

  > If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

`additional_params` (optional)

  The `additional_params` parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the `sendmail_path` configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the `-f` sendmail option.

  This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add additional parameters. For security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted parameters to the shell command.

  Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs where the use of such characters is required, alternative means of sending emails (such as using a framework or a library) is recommended.

  The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

### Return Values

Returns `true` if the mail was successfully accepted for delivery, `false` otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

### Changelog

Version | Description
--- | ---
7.2.0 | The `additional_headers` parameter now also accepts an array.

### Examples

Example #1 Sending mail.

Using mail() to send a simple email:

`<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>`

Example #2 Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

`<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>`

Example #3 Sending mail with extra headers as array

This example sends the same mail as the example immediately above, but passes the additional headers as array (available as of PHP 7.2.0).

`<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
'From' => 'webmaster@example.com',
'Reply-To' => 'webmaster@example.com',
'X-Mailer' => 'PHP/' . phpversion()
);
mail($to, $subject, $message, $headers);
?>`

Example #4 Sending mail with an additional command line parameter.

The `additional_params` parameter can be used to pass an additional parameter to the program configured to use when sending mail using the `sendmail_path`.

`<?php
mail('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>`

Example #5 Sending HTML email

It is also possible to send HTML email with mail().

`<?php
// Multiple recipients
$to = 'johny@example.com, sally@example.com'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>`

> Note:

> If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR package » PEAR::Mail_Mime.

### Notes

> Note:

> The SMTP implementation (Windows only) of mail() differs in many ways from the sendmail implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a `MTA` is needed listening on a network socket (which can either on the localhost or a remote machine).

> Second, the custom headers like `From:`, `Cc:`, `Bcc:` and `Date:` are not interpreted by the `MTA` in the first place, but are parsed by PHP.

> As such, the `to` parameter should not be an address in the form of "Something <someone@example.com>". The mail command may not parse this properly while talking with the MTA.

> Note:

> It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

> For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

> Note:

> The following RFCs may be useful: » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049, and » RFC 2822.

### See Also

- mb_send_mail() - Send encoded mail
- imap_mail() - Send an email message
- » PEAR::Mail
- » PEAR::Mail_Mime

## Table of Contents

- ezmlm_hash — Calculate the hash value needed by EZMLM
- mail — Send mail

- Installing/Configuring
  - Requirements
  - Runtime Configuration
- Mail Functions
  - ezmlm_hash — Calculate the hash value needed by EZMLM
  - mail — Send mail

# Mailparse

# Introduction

Mailparse is an extension for parsing and working with email messages. It can deal with » RFC 822 and » RFC 2045 (`MIME`) compliant messages.

Mailparse is stream based, which means that it does not keep in-memory copies of the files it processes - so it is very resource efficient when dealing with large messages.

> Note: Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration
- Resource Types

## Installation

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: » https://pecl.php.net/package/mailparse.

In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.

Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. Windows binaries (DLL files) for this PECL extension are available from the PECL website.

It is necessary that the mbstring extension is loaded before mailparse.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mailparse Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
mailparse.def_charset | "us-ascii" | `INI_SYSTEM` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`mailparse.def_charset` string
  The default character set.

## Resource Types

Mailparse defines the resource type `mailparse_mail_structure`, which is returned by mailparse_msg_create() and mailparse_msg_parse_file().

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

`MAILPARSE_EXTRACT_OUTPUT` (int)
`MAILPARSE_EXTRACT_STREAM` (int)
`MAILPARSE_EXTRACT_RETURN` (int)

# Mailparse Functions

# mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

### Description

mailparse_determine_best_xfer_encoding(resource `$fp`): string

Figures out the best way of encoding the content read from the given file pointer.

### Parameters

`fp`
  A valid file pointer, which must be seek-able.

### Return Values

Returns one of the character encodings supported by the mbstring module.

### Examples

Example #1 mailparse_determine_best_xfer_encoding() example

`<?php
$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);
?>`

The above example will output something similar to:

    Best encoding: 7bit

# mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

### Description

mailparse_msg_create(): resource

Create a `MIME` mail resource.

### Parameters

This function has no parameters.

### Return Values

Returns a handle that can be used to parse a message.

### Notes

> Note: It is recommended to call mailparse_msg_free() on the result of this function, when it is no longer needed, to avoid memory leaks.

### See Also

- mailparse_msg_free() - Frees a MIME resource
- mailparse_msg_parse_file() - Parses a file

# mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

### Description

mailparse_msg_extract_part(resource `$mimemail`, string `$msgbody`, callable `$callbackfunc` = ?): void
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`mimemail`
  A valid `MIME` resource.
`msgbody`
`callbackfunc`

### Return Values

No value is returned.

### See Also

- mailparse_msg_extract_part_file() - Extracts/decodes a message section
- mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

# mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

### Description

mailparse_msg_extract_part_file(resource `$mimemail`, mixed `$filename`, callable `$callbackfunc` = ?): string

Extracts/decodes a message section from the supplied filename.

The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported.

### Parameters

`mimemail`
  A valid `MIME` resource, created with mailparse_msg_create().
`filename`
  Can be a file name or a valid stream resource.
`callbackfunc`
  If set, this must be either a valid callback that will be passed the extracted section, or `null` to make this function return the extracted section. If not specified, the contents will be sent to "stdout".

### Return Values

If `callbackfunc` is not `null` returns `true` on success.

If `callbackfunc` is set to `null`, returns the extracted section as a string.

Returns `false` on error.

### See Also

- mailparse_msg_extract_part() - Extracts/decodes a message section
- mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

# mailparse_msg_extract_whole_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding

### Description

mailparse_msg_extract_whole_part_file(resource `$mimemail`, string `$filename`, callable `$callbackfunc` = ?): string
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`mimemail`
  A valid `MIME` resource.
`filename`
`callbackfunc`

### Return Values

### See Also

- mailparse_msg_extract_part() - Extracts/decodes a message section
- mailparse_msg_extract_part_file() - Extracts/decodes a message section

# mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

### Description

mailparse_msg_free(resource `$mimemail`): bool

Frees a `MIME` resource.

### Parameters

`mimemail`
  A valid `MIME` resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- mailparse_msg_create() - Create a mime mail resource
- mailparse_msg_parse_file() - Parses a file

# mailparse_msg_get_part

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part — Returns a handle on a given section in a mimemessage

### Description

mailparse_msg_get_part(resource `$mimemail`, string `$mimesection`): resource
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`mimemail`
  A valid `MIME` resource.
`mimesection`

# mailparse_msg_get_part_data

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part_data — Returns an associative array of info about the message

### Description

mailparse_msg_get_part_data(resource `$mimemail`): array
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`mimemail`
  A valid `MIME` resource.

# mailparse_msg_get_structure

(PECL mailparse >= 0.9.0)

mailparse_msg_get_structure — Returns an array of mime section names in the supplied message

### Description

mailparse_msg_get_structure(resource `$mimemail`): array
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`mimemail`
  A valid `MIME` resource.

# mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

### Description

mailparse_msg_parse(resource `$mimemail`, string `$data`): bool

Incrementally parse data into the supplied mime mail resource.

This function allow you to stream portions of a file at a time, rather than read and parse the whole thing.

### Parameters

`mimemail`
  A valid `MIME` resource.
`data`

  > Note: The final chunk of `data` is supposed to end with a newline (`CRLF`); otherwise the last line of the message will not be parsed.

### Return Values

Returns `true` on success or `false` on failure.

# mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

### Description

mailparse_msg_parse_file(string `$filename`): resource

Parses a file. This is the optimal way of parsing a mail file that you have on disk.

### Parameters

`filename`
  Path to the file holding the message. The file is opened and streamed through the parser.

  > Note: The message contained in `filename` is supposed to end with a newline (`CRLF`); otherwise the last line of the message will not be parsed.

### Return Values

Returns a `MIME` resource representing the structure, or `false` on error.

### Notes

> Note: It is recommended to call mailparse_msg_free() on the result of this function, when it is no longer needed, to avoid memory leaks.

### See Also

- mailparse_msg_free() - Frees a MIME resource
- mailparse_msg_create() - Create a mime mail resource

# mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

### Description

mailparse_rfc822_parse_addresses(string `$addresses`): array

Parses a » RFC 822 compliant recipient list, such as that found in the `To:` header.

### Parameters

`addresses`
  A string containing addresses, like in: `Wez Furlong <wez@example.com>, doe@example.com`

  > Note: This string must not include the header name.

### Return Values

Returns an array of associative arrays with the following keys for each recipient:

`display` | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as `address`.
`address` | The email address
`is_group` | `true` if the recipient is a newsgroup, `false` otherwise.

### Examples

Example #1 mailparse_rfc822_parse_addresses() example

`<?php
$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));
?>`

The above example will output:

    array(2) {
      [0]=>
      array(3) {
        ["display"]=>
        string(11) "Wez Furlong"
        ["address"]=>
        string(15) "wez@example.com"
        ["is_group"]=>
        bool(false)
      }
      [1]=>
      array(3) {
        ["display"]=>
        string(15) "doe@example.com"
        ["address"]=>
        string(15) "doe@example.com"
        ["is_group"]=>
        bool(false)
      }
    }

# mailparse_stream_encode

(PECL mailparse >= 0.9.0)

mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp

### Description

mailparse_stream_encode(resource `$sourcefp`, resource `$destfp`, string `$encoding`): bool

Streams data from the source file pointer, apply `encoding` and write to the destination file pointer.

### Parameters

`sourcefp`
  A valid file handle. The file is streamed through the parser.
`destfp`
  The destination file handle in which the encoded data will be written.
`encoding`
  One of the character encodings supported by the mbstring module.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 mailparse_stream_encode() example

`<?php
// email.eml contents: hello, this is some text=hello.
$fp = fopen('email.eml', 'r');
$dest = tmpfile();
mailparse_stream_encode($fp, $dest, "quoted-printable");
rewind($dest);
// Display new file contents
fpassthru($dest);
?>`

The above example will output:

    hello, this is some text=3Dhello.

# mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

### Description

mailparse_uudecode_all(resource `$fp`): array

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

### Parameters

`fp`
  A valid file pointer.

### Return Values

Returns an array of associative arrays listing filename information.

`filename` | Path to the temporary file name created
`origfilename` | The original filename, for uuencoded parts only

The first filename entry is the message body. The next entries are the decoded uuencoded files.

### Examples

Example #1 mailparse_uudecode_all() example

`<?php
$text = <<<EOD
To: fred@example.com
hello, this is some text hello.
blah blah blah.
begin 644 test.txt
/=&AI<R!I<R!A('1E<W0*
`
end
EOD;
$fp = tmpfile();
fwrite($fp, $text);
$data = mailparse_uudecode_all($fp);
echo "BODY\n";
readfile($data[0]["filename"]);
echo "UUE ({$data[1]['origfilename']})\n";
readfile($data[1]["filename"]);
// Clean up
unlink($data[0]["filename"]);
unlink($data[1]["filename"]);
?>`

The above example will output:

    BODY
    To: fred@example.com

    hello, this is some text hello.
    blah blah blah.

    UUE (test.txt)
    this is a test

## Table of Contents

- mailparse_determine_best_xfer_encoding — Gets the best way of encoding
- mailparse_msg_create — Create a mime mail resource
- mailparse_msg_extract_part — Extracts/decodes a message section
- mailparse_msg_extract_part_file — Extracts/decodes a message section
- mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
- mailparse_msg_free — Frees a MIME resource
- mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
- mailparse_msg_get_part_data — Returns an associative array of info about the message
- mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
- mailparse_msg_parse — Incrementally parse data into buffer
- mailparse_msg_parse_file — Parses a file
- mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
- mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
- mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

- Installing/Configuring
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Mailparse Functions
  - mailparse_determine_best_xfer_encoding — Gets the best way of encoding
  - mailparse_msg_create — Create a mime mail resource
  - mailparse_msg_extract_part — Extracts/decodes a message section
  - mailparse_msg_extract_part_file — Extracts/decodes a message section
  - mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
  - mailparse_msg_free — Frees a MIME resource
  - mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
  - mailparse_msg_get_part_data — Returns an associative array of info about the message
  - mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
  - mailparse_msg_parse — Incrementally parse data into buffer
  - mailparse_msg_parse_file — Parses a file
  - mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
  - mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
  - mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

- IMAP — IMAP, POP3 and NNTP
  - Installing/Configuring
  - Predefined Constants
  - IMAP Functions
  - IMAP\Connection — The IMAP\Connection class
- Mail
  - Installing/Configuring
  - Mail Functions
- Mailparse
  - Installing/Configuring
  - Predefined Constants
  - Mailparse Functions

# Mathematical Extensions

# BCMath Arbitrary Precision Mathematics

# Introduction

For arbitrary precision mathematics PHP offers BCMath which supports numbers of any size and precision up to `2147483647` (or `0x7FFFFFFF`) decimal digits, if there is sufficient memory, represented as strings.

Valid (aka. well-formed) BCMath numbers are strings which match the regular expression `/^[+-]?[0-9]*(\.[0-9]*)?$/`.

Caution

Passing values of type float to a BCMath function which expects a string as operand may not have the desired effect due to the way PHP converts float values to string, namely that the string may be in exponential notation (which is not supported by BCMath), and that, prior to PHP 8.0.0, the decimal separator is locale dependent (while BCMath always expects a decimal point).

`<?php
$num1 = 0; // (string) 0 => '0'
$num2 = -0.000005; // (string) -0.000005 => '-5.05E-6'
echo bcadd($num1, $num2, 6); // => '0.000000'
setlocale(LC_NUMERIC, 'de_DE'); // uses a decimal comma
$num2 = 1.2; // (string) 1.2 => '1,2'
echo bcsub($num1, $num2, 1); // => '0.0'
?>`

# Installing/Configuring

## Table of Contents

- Installation
- Runtime Configuration

## Installation

These functions are only available if PHP was configured with --enable-bcmath.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

BC math configuration options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
bcmath.scale | "0" | `INI_ALL` |

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`bcmath.scale` int

  Number of decimal digits for all bcmath functions. See also bcscale().

  > Note: BcMath\Number is not affected by this setting.

# BC Math Functions

# bcadd

(PHP 4, PHP 5, PHP 7, PHP 8)

bcadd — Add two arbitrary precision numbers

### Description

bcadd(string `$num1`, string `$num2`, ?int `$scale` = `null`): string

Sums `num1` and `num2`.

### Parameters

`num1`

  The left operand, as a string.

`num2`

  The right operand, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

The sum of the two operands, as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.

### Examples

Example #1 bcadd() example

`<?php
$a = '1.234';
$b = '5';
echo bcadd($a, $b); // 6
echo bcadd($a, $b, 4); // 6.2340
?>`

### See Also

- bcsub() - Subtract one arbitrary precision number from another
- BcMath\Number::add() - Adds an arbitrary precision number

# bcceil

(PHP 8 >= 8.4.0)

bcceil — Round up arbitrary precision number

### Description

bcceil(string `$num`): string

Returns the next highest integer value by rounding up `num` if necessary.

### Parameters

`num`
  The value to round.

### Return Values

Returns a numeric string representing `num` rounded up to the nearest integer.

### Errors/Exceptions

This function throws a ValueError if `num` is not a well-formed BCMath numeric string.

### Examples

Example #1 bcceil() example

`<?php
var_dump(bcceil('4.3'));
var_dump(bcceil('9.999'));
var_dump(bcceil('-3.14'));
?>`

The above example will output:

    string(1) "5"
    string(2) "10"
    string(2) "-3"

### See Also

- bcfloor() - Round down arbitrary precision number
- bcround() - Round arbitrary precision number
- BcMath\Number::ceil() - Rounds up an arbitrary precision number

# bccomp

(PHP 4, PHP 5, PHP 7, PHP 8)

bccomp — Compare two arbitrary precision numbers

### Description

bccomp(string `$num1`, string `$num2`, ?int `$scale` = `null`): int

Compares `num1` to `num2` and returns the result of the comparison as an integer.

### Parameters

`num1`

  The left operand, as a string.

`num2`

  The right operand, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns `0` if both operands are equal, `1` if `num1` is greater than `num2`, `-1` otherwise.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.

### Examples

Example #1 bccomp() example

`<?php
echo bccomp('1', '2') . "\n"; // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1
?>`

### See Also

- BcMath\Number::compare() - Compares two arbitrary precision numbers

# bcdiv

(PHP 4, PHP 5, PHP 7, PHP 8)

bcdiv — Divide two arbitrary precision numbers

### Description

bcdiv(string `$num1`, string `$num2`, ?int `$scale` = `null`): string

Divides `num1` by `num2`.

### Parameters

`num1`

  The dividend, as a string.

`num2`

  The divisor, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the result of the division as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

This function throws a DivisionByZeroError exception if `num2` is `0`.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.
8.0.0 | Dividing by `0` now throws a DivisionByZeroError exception instead of returning `null`.

### Examples

Example #1 bcdiv() example

`<?php
echo bcdiv('105', '6.55957', 3); // 16.007
?>`

### See Also

- bcdivmod() - Get the quotient and modulus of an arbitrary precision number
- bcmod() - Get modulus of an arbitrary precision number
- bcmul() - Multiply two arbitrary precision numbers
- BcMath\Number::div() - Divides by an arbitrary precision number

# bcdivmod

(PHP 8 >= 8.4.0)

bcdivmod — Get the quotient and modulus of an arbitrary precision number

### Description

bcdivmod(string `$num1`, string `$num2`, ?int `$scale` = `null`): array

Get the quotient and remainder of dividing `num1` by `num2`.

### Parameters

`num1`

  The dividend, as a string.

`num2`

  The divisor, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns an indexed array where the first element is the quotient as a string and the second element is the remainder as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

This function throws a DivisionByZeroError exception if `num2` is `0`.

### Examples

Example #1 bcdivmod() example

`<?php
bcscale(0);
[$quot, $rem] = bcdivmod('5', '3');
echo $quot; // 1
echo $rem; // 2
[$quot, $rem] = bcdivmod('5', '-3');
echo $quot; // -1
echo $rem; // 2
[$quot, $rem] = bcdivmod('-5', '3');
echo $quot; // -1
echo $rem; // -2
[$quot, $rem] = bcdivmod('-5', '-3');
echo $quot; // 1
echo $rem; // -2
?>`

Example #2 bcdivmod() with decimals

`<?php
[$quot, $rem] = bcdivmod('5.7', '1.3', 1);
echo $quot; // 4
echo $rem; // 0.5
?>`

### See Also

- bcdiv() - Divide two arbitrary precision numbers
- bcmod() - Get modulus of an arbitrary precision number
- BcMath\Number::divmod() - Gets the quotient and modulus of an arbitrary precision number

# bcfloor

(PHP 8 >= 8.4.0)

bcfloor — Round down arbitrary precision number

### Description

bcfloor(string `$num`): string

Returns the next lowest integer value by rounding down `num` if necessary.

### Parameters

`num`
  The value to round.

### Return Values

Returns a numeric string representing `num` rounded down to the nearest integer.

### Errors/Exceptions

This function throws a ValueError if `num` is not a well-formed BCMath numeric string.

### Examples

Example #1 bcfloor() example

`<?php
var_dump(bcfloor('4.3'));
var_dump(bcfloor('9.999'));
var_dump(bcfloor('-3.14'));
?>`

The above example will output:

    string(1) "4"
    string(1) "9"
    string(2) "-4"

### See Also

- bcceil() - Round up arbitrary precision number
- bcround() - Round arbitrary precision number
- BcMath\Number::floor() - Rounds down an arbitrary precision number

# bcmod

(PHP 4, PHP 5, PHP 7, PHP 8)

bcmod — Get modulus of an arbitrary precision number

### Description

bcmod(string `$num1`, string `$num2`, ?int `$scale` = `null`): string

Get the remainder of dividing `num1` by `num2`. The result has the same sign as `num1`.

### Parameters

`num1`

  The left operand, as a string.

`num2`

  The right operand, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the modulus as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

This function throws a DivisionByZeroError exception if `num2` is `0`.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.
8.0.0 | Dividing by `0` now throws a DivisionByZeroError exception instead of returning null.
7.2.0 | `num1` and `num2` are no longer truncated to integer, so now the behavior of bcmod() follows fmod() rather than the `%` operator.
7.2.0 | The `scale` parameter was added.

### Examples

Example #1 bcmod() example

`<?php
bcscale(0);
echo bcmod( '5', '3'); // 2
echo bcmod( '5', '-3'); // 2
echo bcmod('-5', '3'); // -2
echo bcmod('-5', '-3'); // -2
?>`

Example #2 bcmod() with decimals

`<?php
bcscale(1);
echo bcmod('5.7', '1.3'); // 0.5 as of PHP 7.2.0; 0 previously
?>`

### See Also

- bcdiv() - Divide two arbitrary precision numbers
- bcdivmod() - Get the quotient and modulus of an arbitrary precision number
- BcMath\Number::mod() - Gets the modulus of an arbitrary precision number

# bcmul

(PHP 4, PHP 5, PHP 7, PHP 8)

bcmul — Multiply two arbitrary precision numbers

### Description

bcmul(string `$num1`, string `$num2`, ?int `$scale` = `null`): string

Multiply `num1` by `num2`.

### Parameters

`num1`

  The left operand, as a string.

`num2`

  The right operand, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the result as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.
7.3.0 | bcmul() now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

### Examples

Example #1 bcmul() example

`<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>`

### Notes

> Note:

> Prior to PHP 7.3.0, bcmul() may return a result with fewer digits after the decimal point than the `scale` parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the `scale`. For example:

> Example #2 bcmul() scale example

> `<?php
> echo bcmul('5', '2', 2); // prints "10", not "10.00"
> ?>`

### See Also

- bcdiv() - Divide two arbitrary precision numbers
- BcMath\Number::mul() - Multiplies an arbitrary precision number

# bcpow

(PHP 4, PHP 5, PHP 7, PHP 8)

bcpow — Raise an arbitrary precision number to another

### Description

bcpow(string `$num`, string `$exponent`, ?int `$scale` = `null`): string

Raise `num` to the power `exponent`.

### Parameters

`num`

  The base, as a string.

`exponent`

  The exponent, as a string. Must be a value with no fractional part. The valid range of the exponent is platform specific, but is at least `-2147483648` to `2147483647`.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the result as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num` or `exponent` is not a well-formed BCMath numeric string
- `exponent` has a fractional part
- `exponent` or `scale` is outside the valid range

This function throws a DivisionByZeroError exception if `num` is `0` and `exponent` is a negative value.

### Changelog

Version | Description
--- | ---
8.4.0 | Negative powers of `0` previously returned `0`, but now throw a DivisionByZeroError exception.
8.0.0 | When `exponent` has a fractional part, it now throws a ValueError instead of truncating.
7.3.0 | bcpow() now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

### Examples

Example #1 bcpow() example

`<?php
echo bcpow('4.2', '3', 2); // 74.08
?>`

### Notes

> Note:

> Before PHP 7.3.0 bcpow() may return a result with fewer digits after the decimal point than the `scale` parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the `scale`. For example:

> Example #2 bcpow() scale example

> `<?php
> echo bcpow('5', '2', 2); // prints "25", not "25.00"
> ?>`

### See Also

- bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
- bcsqrt() - Get the square root of an arbitrary precision number
- BcMath\Number::pow() - Raises an arbitrary precision number

# bcpowmod

(PHP 5, PHP 7, PHP 8)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

### Description

bcpowmod(
string `$num`,
string `$exponent`,
string `$modulus`,
?int `$scale` = `null`
): string

Use the fast-exponentiation method to raise `num` to the power `exponent` with respect to the modulus `modulus`.

### Parameters

`num`

  The base, as an integral string (i.e. the scale has to be zero).

`exponent`

  The exponent, as an non-negative, integral string (i.e. the scale has to be zero).

`modulus`

  The modulus, as an integral string (i.e. the scale has to be zero).

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the result as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num`, `exponent` or `modulus` is not a well-formed BCMath numeric string
- `num`, `exponent` or `modulus` has a fractional part
- `exponent` is a negative value
- `scale` is outside the valid range

This function throws a DivisionByZeroError exception if `modulus` is `0`.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.
8.0.0 | Now throws a ValueError instead of returning `false` if `exponent` is a negative value.
8.0.0 | Dividing by `0` now throws a DivisionByZeroError exception instead of returning `false`.

### Examples

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

`<?php
$a = bcpowmod($x, $y, $mod);
$b = bcmod(bcpow($x, $y), $mod);
// $a and $b are equal to each other.
?>`

### Notes

> Note:

> Because this method uses the modulus operation, numbers which are not positive integers may give unexpected results.

### See Also

- bcpow() - Raise an arbitrary precision number to another
- bcmod() - Get modulus of an arbitrary precision number
- BcMath\Number::powmod() - Raises an arbitrary precision number, reduced by a specified modulus

# bcround

(PHP 8 >= 8.4.0)

bcround — Round arbitrary precision number

### Description

bcround(string `$num`, int `$precision` = 0, RoundingMode `$mode` = `RoundingMode::HalfAwayFromZero`): string

Returns the rounded value of `num` to specified `precision` (number of digits after the decimal point). `precision` can also be negative or zero (default).

### Parameters

`num`

  The value to round.

`precision`

  The optional number of decimal digits to round to.

  If the `precision` is positive, `num` is rounded to `precision` significant digits after the decimal point.

  If the `precision` is negative, `num` is rounded to `precision` significant digits before the decimal point, i.e. to the nearest multiple of `pow(10, -$precision)`, e.g. for a `precision` of -1 `num` is rounded to tens, for a `precision` of -2 to hundreds, etc.

`mode`
  Specifies the rounding mode. For more information about modes, see RoundingMode.

### Return Values

Returns a numeric string representing `num` rounded to the given precision.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num` is not a well-formed BCMath numeric string.
- An invalid `mode` is specified.

### Examples

Example #1 bcround() examples

`<?php
var_dump(bcround('3.4'));
var_dump(bcround('3.5'));
var_dump(bcround('3.6'));
var_dump(bcround('3.6', 0));
var_dump(bcround('5.045', 2));
var_dump(bcround('5.055', 2));
var_dump(bcround('345', -2));
var_dump(bcround('345', -3));
var_dump(bcround('678', -2));
var_dump(bcround('678', -3));
?>`

The above example will output:

    string(1) "3"
    string(1) "4"
    string(1) "4"
    string(1) "4"
    string(4) "5.05"
    string(4) "5.06"
    string(3) "300"
    string(1) "0"
    string(3) "700"
    string(4) "1000"

Example #2 Example of using bcround() with different `precision` values

`<?php
$number = '123.45';
var_dump(bcround($number, 3));
var_dump(bcround($number, 2));
var_dump(bcround($number, 1));
var_dump(bcround($number, 0));
var_dump(bcround($number, -1));
var_dump(bcround($number, -2));
var_dump(bcround($number, -3));
?>`

The above example will output:

    string(7) "123.450"
    string(6) "123.45"
    string(5) "123.5"
    string(3) "123"
    string(3) "120"
    string(3) "100"
    string(1) "0"

Example #3 Example of using bcround() with different `mode` values

`<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
var_dump(bcround('9.5', 0, RoundingMode::HalfAwayFromZero));
var_dump(bcround('9.5', 0, RoundingMode::HalfTowardsZero));
var_dump(bcround('9.5', 0, RoundingMode::HalfEven));
var_dump(bcround('9.5', 0, RoundingMode::HalfOdd));
var_dump(bcround('9.5', 0, RoundingMode::TowardsZero));
var_dump(bcround('9.5', 0, RoundingMode::AwayFromZero));
var_dump(bcround('9.5', 0, RoundingMode::NegativeInfinity));
var_dump(bcround('9.5', 0, RoundingMode::PositiveInfinity));
echo PHP_EOL;
echo 'Rounding modes with 8.5' . PHP_EOL;
var_dump(bcround('8.5', 0, RoundingMode::HalfAwayFromZero));
var_dump(bcround('8.5', 0, RoundingMode::HalfTowardsZero));
var_dump(bcround('8.5', 0, RoundingMode::HalfEven));
var_dump(bcround('8.5', 0, RoundingMode::HalfOdd));
var_dump(bcround('8.5', 0, RoundingMode::TowardsZero));
var_dump(bcround('8.5', 0, RoundingMode::AwayFromZero));
var_dump(bcround('8.5', 0, RoundingMode::NegativeInfinity));
var_dump(bcround('8.5', 0, RoundingMode::PositiveInfinity));
?>`

The above example will output:

    Rounding modes with 9.5
    string(2) "10"
    string(1) "9"
    string(2) "10"
    string(1) "9"
    string(1) "9"
    string(2) "10"
    string(1) "9"
    string(2) "10"

    Rounding modes with 8.5
    string(1) "9"
    string(1) "8"
    string(1) "8"
    string(1) "9"
    string(1) "8"
    string(1) "9"
    string(1) "8"
    string(1) "9"

Example #4 Example of using bcround() with different `mode` values when specifying `precision`

`<?php
echo 'Using RoundingMode::HalfAwayFromZero with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::HalfAwayFromZero));
var_dump(bcround(-1.55, 1, RoundingMode::HalfAwayFromZero));
echo PHP_EOL;
echo 'Using RoundingMode::HalfTowardsZero with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::HalfTowardsZero));
var_dump(bcround(-1.55, 1, RoundingMode::HalfTowardsZero));
echo PHP_EOL;
echo 'Using RoundingMode::HalfEven with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::HalfEven));
var_dump(bcround(-1.55, 1, RoundingMode::HalfEven));
echo PHP_EOL;
echo 'Using RoundingMode::HalfOdd with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::HalfOdd));
var_dump(bcround(-1.55, 1, RoundingMode::HalfOdd));
echo PHP_EOL;
echo 'Using RoundingMode::TowardsZero with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::TowardsZero));
var_dump(bcround(-1.55, 1, RoundingMode::TowardsZero));
echo PHP_EOL;
echo 'Using RoundingMode::AwayFromZero with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::AwayFromZero));
var_dump(bcround(-1.55, 1, RoundingMode::AwayFromZero));
echo PHP_EOL;
echo 'Using RoundingMode::NegativeInfinity with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::NegativeInfinity));
var_dump(bcround(-1.55, 1, RoundingMode::NegativeInfinity));
echo PHP_EOL;
echo 'Using RoundingMode::PositiveInfinity with 1 decimal digit precision' . PHP_EOL;
var_dump(bcround( 1.55, 1, RoundingMode::PositiveInfinity));
var_dump(bcround(-1.55, 1, RoundingMode::PositiveInfinity));
?>`

The above example will output:

    Using RoundingMode::HalfAwayFromZero with 1 decimal digit precision
    string(3) "1.6"
    string(4) "-1.6"

    Using RoundingMode::HalfTowardsZero with 1 decimal digit precision
    string(3) "1.5"
    string(4) "-1.5"

    Using RoundingMode::HalfEven with 1 decimal digit precision
    string(3) "1.6"
    string(4) "-1.6"

    Using RoundingMode::HalfOdd with 1 decimal digit precision
    string(3) "1.5"
    string(4) "-1.5"

    Using RoundingMode::TowardsZero with 1 decimal digit precision
    string(3) "1.5"
    string(4) "-1.5"

    Using RoundingMode::AwayFromZero with 1 decimal digit precision
    string(3) "1.6"
    string(4) "-1.6"

    Using RoundingMode::NegativeInfinity with 1 decimal digit precision
    string(3) "1.5"
    string(4) "-1.6"

    Using RoundingMode::PositiveInfinity with 1 decimal digit precision
    string(3) "1.6"
    string(4) "-1.5"

### See Also

- bcceil() - Round up arbitrary precision number
- bcfloor() - Round down arbitrary precision number
- BcMath\Number::round() - Rounds an arbitrary precision number

# bcscale

(PHP 4, PHP 5, PHP 7, PHP 8)

bcscale — Set or get default scale parameter for all bc math functions

### Description

bcscale(int `$scale`): int

Sets the default scale parameter for all subsequent calls to bc math functions that do not explicitly specify a scale parameter.

bcscale(null `$scale` = `null`): int

Gets the current scale factor.

### Parameters

`scale`

  The scale factor.

### Return Values

Returns the old scale when used as setter. Otherwise the current scale is returned.

### Errors/Exceptions

This function throws a ValueError if `scale` is outside the valid range.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.
7.3.0 | bcscale() can now be used to get the current scale factor; when used as setter, it now returns the old scale value. Formerly, `scale` was mandatory, and bcscale() always returned `true`.

### Examples

Example #1 bcscale() example

`<?php
// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007
// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007
?>`

# bcsqrt

(PHP 4, PHP 5, PHP 7, PHP 8)

bcsqrt — Get the square root of an arbitrary precision number

### Description

bcsqrt(string `$num`, ?int `$scale` = `null`): string

Return the square root of `num`.

### Parameters

`num`

  The operand, as a well-formed BCMath numeric string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

Returns the square root as a well-formed BCMath numeric string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num` is not a well-formed BCMath numeric string
- `num` is less than `0`
- `scale` is outside the valid range

### Changelog

Version | Description
--- | ---
8.0.0 | If `num` is not a well-formed BCMath numeric string, or less than `0`, a ValueError is thrown. Previously, `E_WARNING` was raised instead.
8.0.0 | `scale` now needs to be between `0` and `2147483647`; previously, negative scales have been silently treated as `0`.
8.0.0 | `scale` is now nullable.

### Examples

Example #1 bcsqrt() example

`<?php
echo bcsqrt('2', 3); // 1.414
?>`

### See Also

- bcpow() - Raise an arbitrary precision number to another
- BcMath\Number::sqrt() - Gets the square root of an arbitrary precision number

# bcsub

(PHP 4, PHP 5, PHP 7, PHP 8)

bcsub — Subtract one arbitrary precision number from another

### Description

bcsub(string `$num1`, string `$num2`, ?int `$scale` = `null`): string

Subtracts `num2` from `num1`.

### Parameters

`num1`

  The left operand, as a string.

`num2`

  The right operand, as a string.

`scale`
  This parameter is used to set the number of digits after the decimal place in the result. If `null`, it will default to the default scale set with bcscale(), or fallback to the value of the `bcmath.scale` INI directive.

### Return Values

The result of the subtraction, as a string.

### Errors/Exceptions

This function throws a ValueError in the following cases:

- `num1` or `num2` is not a well-formed BCMath numeric string.
- `scale` is outside the valid range.

### Changelog

Version | Description
--- | ---
8.0.0 | `scale` is now nullable.

### Examples

Example #1 bcsub() example

`<?php
$a = '1.234';
$b = '5';
echo bcsub($a, $b); // -3
echo bcsub($a, $b, 4); // -3.7660
?>`

### See Also

- bcadd() - Add two arbitrary precision numbers
- BcMath\Number::sub() - Subtracts an arbitrary precision number

## Table of Contents

- bcadd — Add two arbitrary precision numbers
- bcceil — Round up arbitrary precision number
- bccomp — Compare two arbitrary precision numbers
- bcdiv — Divide two arbitrary precision numbers
- bcdivmod — Get the quotient and modulus of an arbitrary precision number
- bcfloor — Round down arbitrary precision number
- bcmod — Get modulus of an arbitrary precision number
- bcmul — Multiply two arbitrary precision numbers
- bcpow — Raise an arbitrary precision number to another
- bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
- bcround — Round arbitrary precision number
- bcscale — Set or get default scale parameter for all bc math functions
- bcsqrt — Get the square root of an arbitrary precision number
- bcsub — Subtract one arbitrary precision number from another

# The BcMath\Number class

(PHP 8 >= 8.4.0)

## Introduction

A class for an arbitrary precision number. These objects support overloaded arithmetic and comparison operators.

> Note: This class is not affected by the bcmath.scale INI directive set in php.ini.

> Note: The behavior of an overloaded operator is the same as specifying `null` for the `scale` parameter on the corresponding method.

## Class synopsis

namespace BcMath;
final readonly class Number implements Stringable {
/* Properties */
public string $value;
public int $scale;
/* Methods */
public BcMath\Number::__construct(string|int `$num`)
public BcMath\Number::add(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::ceil(): BcMath\Number
public BcMath\Number::compare(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): int
public BcMath\Number::div(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::divmod(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): array
public BcMath\Number::floor(): BcMath\Number
public BcMath\Number::mod(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::mul(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::pow(BcMath\Number|string|int `$exponent`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::powmod(BcMath\Number|string|int `$exponent`, BcMath\Number|string|int `$modulus`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::round(int `$precision` = 0, RoundingMode `$mode` = `RoundingMode::HalfAwayFromZero`): BcMath\Number
public BcMath\Number::__serialize(): array
public BcMath\Number::sqrt(?int `$scale` = `null`): BcMath\Number
public BcMath\Number::sub(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number
public BcMath\Number::__toString(): string
public BcMath\Number::__unserialize(array `$data`): void
}

## Properties

value
  A string representation of an arbitrary precision number.
scale
  The scale value currently set on the object. For objects resulting from calculations, this value is automatically computed and set, unless the `scale` parameter was set in the calculation method.

# BcMath\Number::add

(PHP 8 >= 8.4.0)

BcMath\Number::add — Adds an arbitrary precision number

### Description

public BcMath\Number::add(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number

Adds $this and `num`.

### Parameters

`num`
  The value to add.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result of addition as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the greater BcMath\Number::scale of the two numbers used for addition is used.

That is, if the BcMath\Number::scales of two values are `2` and `5` respectively, the BcMath\Number::scale of the result will be `5`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range

### Examples

Example #1 BcMath\Number::add() example when `scale` is not specified

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->add(new BcMath\Number('2.34567'));
$ret2 = $number->add('-3.456');
$ret3 = $number->add(7);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(7) "3.57967"
      ["scale"]=>
      int(5)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(6) "-2.222"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(5) "8.234"
      ["scale"]=>
      int(3)
    }

Example #2 BcMath\Number::add() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->add(new BcMath\Number('2.34567'), 1);
$ret2 = $number->add('-3.456', 10);
$ret3 = $number->add(7, 0);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(3) "3.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(13) "-2.2220000000"
      ["scale"]=>
      int(10)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }

### See Also

- bcadd() - Add two arbitrary precision numbers
- BcMath\Number::sub() - Subtracts an arbitrary precision number

# BcMath\Number::ceil

(PHP 8 >= 8.4.0)

BcMath\Number::ceil — Rounds up an arbitrary precision number

### Description

public BcMath\Number::ceil(): BcMath\Number

Returns the next highest integer value by rounding up $this if necessary.

### Parameters

This function has no parameters.

### Return Values

Returns the result as a new BcMath\Number object. The BcMath\Number::scale of the result is always `0`.

### Examples

Example #1 BcMath\Number::ceil() example

`<?php
$num1 = new BcMath\Number('4.3')->ceil();
$num2 = new BcMath\Number('9.999')->ceil();
$num3 = new BcMath\Number('-3.14')->ceil();
var_dump($num1, $num2, $num3);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "5"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(2) "10"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(2) "-3"
      ["scale"]=>
      int(0)
    }

### See Also

- bcceil() - Round up arbitrary precision number
- BcMath\Number::floor() - Rounds down an arbitrary precision number
- BcMath\Number::round() - Rounds an arbitrary precision number

# BcMath\Number::compare

(PHP 8 >= 8.4.0)

BcMath\Number::compare — Compares two arbitrary precision numbers

### Description

public BcMath\Number::compare(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): int

Compare two arbitrary precision numbers. This method behaves similar to the spaceship operator.

### Parameters

`num`
  The value to be compared to.
`scale`
  Specify the `scale` to use for comparison. If `null`, all digits are used in the comparison.

### Return Values

Returns `0` if the two numbers are equal, `1` if $this is greater than `num`, `-1` otherwise.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range

### Examples

Example #1 BcMath\Number::compare() example when `scale` is not specified

`<?php
$number = new BcMath\Number('1.234');
var_dump(
$number->compare(new BcMath\Number('1.234')),
$number->compare('1.23400'),
$number->compare('1.23401'),
$number->compare(1),
);
?>`

The above example will output:

    int(0)
    int(0)
    int(-1)
    int(1)

Example #2 BcMath\Number::compare() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('1.234');
var_dump(
$number->compare(new BcMath\Number('1.299'), 1),
$number->compare('1.24', 2),
$number->compare('1.22', 2),
$number->compare(1, 0),
);
?>`

The above example will output:

    int(0)
    int(-1)
    int(1)
    int(0)

### See Also

- bccomp() - Compare two arbitrary precision numbers

# BcMath\Number::__construct

(PHP 8 >= 8.4.0)

BcMath\Number::__construct — Creates a BcMath\Number object

### Description

public BcMath\Number::__construct(string|int `$num`)

Creates a BcMath\Number object from an int or string value.

### Parameters

`num`
  An int or string value. If `num` is a int, the BcMath\Number::scale is always set to `0`. If `num` is a string, it must be a valid number, and the BcMath\Number::scale is automatically set by parsing the string.

### Errors/Exceptions

This method throws a ValueError if `num` is string and not a well-formed BCMath numeric string.

### Examples

Example #1 BcMath\Number::__construct() example

`<?php
$num1 = new BcMath\Number(100);
$num2 = new BcMath\Number('-200');
$num3 = new BcMath\Number('300.00');
var_dump($num1, $num2, $num3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(3) "100"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(4) "-200"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(6) "300.00"
      ["scale"]=>
      int(2)
    }

### See Also

- BcMath\Number::__serialize() - Serializes a BcMath\Number object
- BcMath\Number::__unserialize() - Deserializes a data parameter into a BcMath\Number object

# BcMath\Number::div

(PHP 8 >= 8.4.0)

BcMath\Number::div — Divides by an arbitrary precision number

### Description

public BcMath\Number::div(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number

Divides $this by `num`.

### Parameters

`num`
  The divisor.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result of division as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the BcMath\Number::scale of the dividend is used. However, in cases such as indivisible division, the BcMath\Number::scale of the result is expanded. Expansion is done only as needed, up to a maximum of `+10`.

That is, if the BcMath\Number::scale of the dividend is `5`, the BcMath\Number::scale of the result is between `5` and `15`.

Even in indivisible calculations, the BcMath\Number::scale will not always be `+10`. A `0` at the end of the result is considered not to need expansion, so the BcMath\Number::scale is reduced by that amount. The BcMath\Number::scale will never be less than the BcMath\Number::scale before expansion. See also the code example.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range
- BcMath\Number::scale of the result object is outside the valid range

This method throws a DivisionByZeroError exception if `num` is `0`.

### Examples

Example #1 BcMath\Number::div() example when `scale` is not specified

`<?php
$number = new BcMath\Number('0.002');
$ret1 = $number->div(new BcMath\Number('2.000'));
$ret2 = $number->div('-3');
$ret3 = $number->div(32);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "0.002"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(5) "0.001"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(16) "-0.0006666666666"
      ["scale"]=>
      int(13)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(9) "0.0000625"
      ["scale"]=>
      int(7)
    }

Example #2 BcMath\Number::div() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('0.002');
$ret1 = $number->div(new BcMath\Number('2.000'), 15);
$ret2 = $number->div('-3', 5);
$ret3 = $number->div(32, 2);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "0.002"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(17) "0.001000000000000"
      ["scale"]=>
      int(15)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(8) "-0.00066"
      ["scale"]=>
      int(5)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(4) "0.00"
      ["scale"]=>
      int(2)
    }

Example #3 BcMath\Number::div() example of expansioning BcMath\Number::scale of result object

`<?php
var_dump(
new BcMath\Number('0.001')->div('10001'),
new BcMath\Number('0.001')->div('10001', 13),
new BcMath\Number('0.001')->div('100000000000001'),
);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(13) "0.00000009999"
      ["scale"]=>
      int(11)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(15) "0.0000000999900"
      ["scale"]=>
      int(13)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(5) "0.000"
      ["scale"]=>
      int(3)
    }

### See Also

- bcdiv() - Divide two arbitrary precision numbers
- BcMath\Number::divmod() - Gets the quotient and modulus of an arbitrary precision number
- BcMath\Number::mod() - Gets the modulus of an arbitrary precision number
- BcMath\Number::sqrt() - Gets the square root of an arbitrary precision number
- BcMath\Number::pow() - Raises an arbitrary precision number
- BcMath\Number::mul() - Multiplies an arbitrary precision number

# BcMath\Number::divmod

(PHP 8 >= 8.4.0)

BcMath\Number::divmod — Gets the quotient and modulus of an arbitrary precision number

### Description

public BcMath\Number::divmod(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): array

Gets the quotient and remainder of dividing $this by `num`.

### Parameters

`num`
  The divisor.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns an indexed array where the first element is the quotient as a new BcMath\Number object and the second element is the remainder as a new BcMath\Number object.

The quotient is always an integer value, so BcMath\Number::scale of the quotient will always be `0`, regardless of whether explicitly specify `scale`.

If `scale` is explicitly specified, BcMath\Number::scale of the remainder will be the specified value. When the BcMath\Number::scale of the result's remainder object is automatically set, the greater BcMath\Number::scale of the two numbers used for modulus operation is used.

That is, if the BcMath\Number::scales of two values are `2` and `5` respectively, the BcMath\Number::scale of the remainder will be `5`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range

This method throws a DivisionByZeroError exception if `num` is `0`.

### Examples

Example #1 BcMath\Number::divmod() example when `scale` is not specified

`<?php
echo '8.3 / 2.22' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('8')->divmod(new BcMath\Number('2.22'));
var_dump($quot, $rem);
echo PHP_EOL . '8.3 / 8.3' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('8.3')->divmod('8.3');
var_dump($quot, $rem);
echo PHP_EOL . '10 / -3' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('10')->divmod(-3);
var_dump($quot, $rem);
?>`

The above example will output:

    8.3 / 2.22
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "3"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(4) "1.34"
      ["scale"]=>
      int(2)
    }

    8.3 / 8.3
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "1"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(3) "0.0"
      ["scale"]=>
      int(1)
    }

    10 / -3
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(2) "-3"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(1) "1"
      ["scale"]=>
      int(0)
    }

Example #2 BcMath\Number::divmod() example of explicitly specifying `scale`

`<?php
echo '8.3 / 2.22' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('8')->divmod(new BcMath\Number('2.22'), 1);
var_dump($quot, $rem);
echo PHP_EOL . '8.3 / 8.3' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('8.3')->divmod('8.3', 4);
var_dump($quot, $rem);
echo PHP_EOL . '10 / -3' . PHP_EOL;
[$quot, $rem] = new BcMath\Number('10')->divmod(-3, 5);
var_dump($quot, $rem);
?>`

The above example will output:

    8.3 / 2.22
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "3"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.3"
      ["scale"]=>
      int(1)
    }

    8.3 / 8.3
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "1"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(6) "0.0000"
      ["scale"]=>
      int(4)
    }

    10 / -3
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(2) "-3"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(7) "1.00000"
      ["scale"]=>
      int(5)
    }

### See Also

- bcdivmod() - Get the quotient and modulus of an arbitrary precision number
- BcMath\Number::div() - Divides by an arbitrary precision number
- BcMath\Number::mod() - Gets the modulus of an arbitrary precision number

# BcMath\Number::floor

(PHP 8 >= 8.4.0)

BcMath\Number::floor — Rounds down an arbitrary precision number

### Description

public BcMath\Number::floor(): BcMath\Number

Returns the next highest integer value by rounding down $this if necessary.

### Parameters

This function has no parameters.

### Return Values

Returns the result as a new BcMath\Number object. The BcMath\Number::scale of the result is always `0`.

### Examples

Example #1 BcMath\Number::floor() example

`<?php
$num1 = new BcMath\Number('4.3')->floor();
$num2 = new BcMath\Number('9.999')->floor();
$num3 = new BcMath\Number('-3.14')->floor();
var_dump($num1, $num2, $num3);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "4"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(2) "-4"
      ["scale"]=>
      int(0)
    }

### See Also

- bcfloor() - Round down arbitrary precision number
- BcMath\Number::ceil() - Rounds up an arbitrary precision number
- BcMath\Number::round() - Rounds an arbitrary precision number

# BcMath\Number::mod

(PHP 8 >= 8.4.0)

BcMath\Number::mod — Gets the modulus of an arbitrary precision number

### Description

public BcMath\Number::mod(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number

Gets the remainder of dividing $this by `num`. Unless `num` is `0`, the result has the same sign as $this.

### Parameters

`num`
  The divisor.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the modulus as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the greater BcMath\Number::scale of the two numbers used for modulus operation is used.

That is, if the BcMath\Number::scales of two values are `2` and `5` respectively, the BcMath\Number::scale of the result will be `5`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range

This method throws a DivisionByZeroError exception if `num` is `0`.

### Examples

Example #1 BcMath\Number::mod() example when `scale` is not specified

`<?php
$number = new BcMath\Number('8.3');
$ret1 = $number->mod(new BcMath\Number('2.22'));
$ret2 = $number->mod('8.3');
$ret3 = $number->mod(-5);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(3) "8.3"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(4) "1.64"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(3) "0.0"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "3.3"
      ["scale"]=>
      int(1)
    }

Example #2 BcMath\Number::mod() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('8.3');
$ret1 = $number->mod(new BcMath\Number('2.22'), 1);
$ret2 = $number->mod('8.3', 3);
$ret3 = $number->mod(-5, 0);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(3) "8.3"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(3) "1.6"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(5) "0.000"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "3"
      ["scale"]=>
      int(0)
    }

### See Also

- bcmod() - Get modulus of an arbitrary precision number
- BcMath\Number::div() - Divides by an arbitrary precision number
- BcMath\Number::divmod() - Gets the quotient and modulus of an arbitrary precision number
- BcMath\Number::powmod() - Raises an arbitrary precision number, reduced by a specified modulus

# BcMath\Number::mul

(PHP 8 >= 8.4.0)

BcMath\Number::mul — Multiplies an arbitrary precision number

### Description

public BcMath\Number::mul(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number

Multiplies $this by `num`.

### Parameters

`num`
  The multiplier.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result of multiplication as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the sum of the BcMath\Number::scales of the two values used for multiplication is used.

That is, if the BcMath\Number::scales of two values are `2` and `5` respectively, the BcMath\Number::scale of the result will be `7`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range
- BcMath\Number::scale of the result object is outside the valid range

### Examples

Example #1 BcMath\Number::mul() example when `scale` is not specified

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->mul(new BcMath\Number('2.3456'));
$ret2 = $number->mul('-3.4');
$ret3 = $number->mul(7);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(9) "2.8944704"
      ["scale"]=>
      int(7)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(7) "-4.1956"
      ["scale"]=>
      int(4)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(5) "8.638"
      ["scale"]=>
      int(3)
    }

Example #2 BcMath\Number::mul() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->mul(new BcMath\Number('2.3456'), 1);
$ret2 = $number->mul('-3.4', 10);
$ret3 = $number->mul(7, 0);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(3) "2.8"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(13) "-4.1956000000"
      ["scale"]=>
      int(10)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }

### See Also

- bcmul() - Multiply two arbitrary precision numbers
- BcMath\Number::div() - Divides by an arbitrary precision number
- BcMath\Number::pow() - Raises an arbitrary precision number
- BcMath\Number::powmod() - Raises an arbitrary precision number, reduced by a specified modulus

# BcMath\Number::pow

(PHP 8 >= 8.4.0)

BcMath\Number::pow — Raises an arbitrary precision number

### Description

public BcMath\Number::pow(BcMath\Number|string|int `$exponent`, ?int `$scale` = `null`): BcMath\Number

Raises $this to the `exponent` power.

### Parameters

`exponent`
  The exponent. Must be a value with no fractional part. The valid range of the `exponent` is platform specific, but it is at least `-2147483648` to `2147483647`.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result of power as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, depending on the value of `exponent`, the BcMath\Number::scale of result will be as follows:

`exponent` | BcMath\Number::scale of result
--- | ---
positive | (BcMath\Number::scale of power base) * (`exponent`'s value)
`0` | `0`
negative | Between (BcMath\Number::scale of power base) and (BcMath\Number::scale of power base + `10`)

If an indivisible division occurs due to a negative `exponent`, the BcMath\Number::scale of the result is expanded. Expansion is done only as needed, up to a maximum of `+10`. This behavior is the same as BcMath\Number::div(), so please see that for details.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `exponent` is string and not a well-formed BCMath numeric string
- `exponent` has a fractional part
- `exponent` or `scale` is outside the valid range
- BcMath\Number::scale of the result object is outside the valid range

This method throws a DivisionByZeroError exception if $this's value is `0` and `exponent` is a negative value.

### Examples

Example #1 BcMath\Number::pow() example when `scale` is not specified

`<?php
$number = new BcMath\Number('3.0');
$ret1 = $number->pow(new BcMath\Number('5'));
$ret2 = $number->pow('-1');
$ret3 = $number->pow(0);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(3) "3.0"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(9) "243.00000"
      ["scale"]=>
      int(5)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(13) "0.33333333333"
      ["scale"]=>
      int(11)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "1"
      ["scale"]=>
      int(0)
    }

Example #2 BcMath\Number::pow() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('3.0');
$ret1 = $number->pow(new BcMath\Number('5'), 0);
$ret2 = $number->pow('-1', 2);
$ret3 = $number->pow(0, 10);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(3) "3.0"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(3) "243"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(4) "0.33"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(12) "1.0000000000"
      ["scale"]=>
      int(10)
    }

### See Also

- bcpow() - Raise an arbitrary precision number to another
- BcMath\Number::powmod() - Raises an arbitrary precision number, reduced by a specified modulus
- BcMath\Number::mul() - Multiplies an arbitrary precision number
- BcMath\Number::sqrt() - Gets the square root of an arbitrary precision number
- BcMath\Number::div() - Divides by an arbitrary precision number

# BcMath\Number::powmod

(PHP 8 >= 8.4.0)

BcMath\Number::powmod — Raises an arbitrary precision number, reduced by a specified modulus

### Description

public BcMath\Number::powmod(BcMath\Number|string|int `$exponent`, BcMath\Number|string|int `$modulus`, ?int `$scale` = `null`): BcMath\Number

Use the fast-exponentiation method to raise $this to the power `exponent` with respect to the modulus `modulus`.

### Parameters

`exponent`
  The exponent, as an non-negative and integral (i.e. the scale has to be zero).
`modulus`
  The modulus, as an integral (i.e. the scale has to be zero).
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the BcMath\Number::scale of the result object will always be `0`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `exponent` or `modulus` is string and not a well-formed BCMath numeric string
- $this, `exponent` or `modulus` has a fractional part
- `exponent` is a negative value
- `scale` is outside the valid range

This method throws a DivisionByZeroError exception if `modulus` is `0`.

### Examples

Example #1 BcMath\Number::powmod() example when `scale` is not specified

`<?php
var_dump(
new BcMath\Number('8')->powmod(new BcMath\Number('3'), 5),
new BcMath\Number('-8')->powmod(new BcMath\Number('3'), 5),
new BcMath\Number('8')->powmod('2', -3),
new BcMath\Number('-8')->powmod(5, 7),
);
?>`

The above example will output:

    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "2"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(2) "-2"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "1"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(2) "-1"
      ["scale"]=>
      int(0)
    }

Example #2 BcMath\Number::powmod() example of explicitly specifying `scale`

`<?php
var_dump(
new BcMath\Number('8')->powmod(new BcMath\Number('3'), 5, 1),
new BcMath\Number('-8')->powmod(new BcMath\Number('3'), 5, 2),
new BcMath\Number('8')->powmod('2', -3, 3),
new BcMath\Number('-8')->powmod(5, 7, 4),
);
?>`

The above example will output:

    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(3) "2.0"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(5) "-2.00"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(5) "1.000"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(7) "-1.0000"
      ["scale"]=>
      int(4)
    }

### See Also

- bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
- BcMath\Number::pow() - Raises an arbitrary precision number
- BcMath\Number::mod() - Gets the modulus of an arbitrary precision number

# BcMath\Number::round

(PHP 8 >= 8.4.0)

BcMath\Number::round — Rounds an arbitrary precision number

### Description

public BcMath\Number::round(int `$precision` = 0, RoundingMode `$mode` = `RoundingMode::HalfAwayFromZero`): BcMath\Number

Returns the rounded value of $this to specified `precision` (number of digits after the decimal point). `precision` can also be negative or zero (default).

### Parameters

`precision`

  The optional number of decimal digits to round to.

  If the `precision` is positive, `num` is rounded to `precision` significant digits after the decimal point.

  If the `precision` is negative, `num` is rounded to `precision` significant digits before the decimal point, i.e. to the nearest multiple of `pow(10, -$precision)`, e.g. for a `precision` of -1 `num` is rounded to tens, for a `precision` of -2 to hundreds, etc.

`mode`
  Specifies the rounding mode. For more information about modes, see RoundingMode.

### Return Values

Returns the result as a new BcMath\Number object.

### Errors/Exceptions

This method throws a ValueError if an invalid `mode` is specified.

### Examples

Example #1 BcMath\Number::round() example

`<?php
var_dump(
new BcMath\Number('3.4')->round(),
new BcMath\Number('3.5')->round(),
new BcMath\Number('3.6')->round(),
new BcMath\Number('3.6')->round(0),
new BcMath\Number('5.045')->round(2),
new BcMath\Number('5.055')->round(2),
new BcMath\Number('345')->round(-2),
new BcMath\Number('345')->round(-3),
new BcMath\Number('678')->round(-2),
new BcMath\Number('678')->round(-3),
);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(1) "3"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "4"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "4"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(1) "4"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#6 (2) {
      ["value"]=>
      string(4) "5.05"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#7 (2) {
      ["value"]=>
      string(4) "5.06"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#8 (2) {
      ["value"]=>
      string(3) "300"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#9 (2) {
      ["value"]=>
      string(1) "0"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#10 (2) {
      ["value"]=>
      string(3) "700"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#11 (2) {
      ["value"]=>
      string(4) "1000"
      ["scale"]=>
      int(0)
    }

Example #2 Example of using BcMath\Number::round() with different `precision` values

`<?php
$number = new BcMath\Number('123.45');
var_dump(
$number->round(3),
$number->round(2),
$number->round(1),
$number->round(0),
$number->round(-1),
$number->round(-2),
$number->round(-3),
);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(7) "123.450"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(6) "123.45"
      ["scale"]=>
      int(2)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(5) "123.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(3) "123"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#6 (2) {
      ["value"]=>
      string(3) "120"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#7 (2) {
      ["value"]=>
      string(3) "100"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#8 (2) {
      ["value"]=>
      string(1) "0"
      ["scale"]=>
      int(0)
    }

Example #3 Example of using BcMath\Number::round() with different `mode` values

`<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
$number = new BcMath\Number('9.5');
var_dump(
$number->round(0, RoundingMode::HalfAwayFromZero),
$number->round(0, RoundingMode::HalfTowardsZero),
$number->round(0, RoundingMode::HalfEven),
$number->round(0, RoundingMode::HalfOdd),
$number->round(0, RoundingMode::TowardsZero),
$number->round(0, RoundingMode::AwayFromZero),
$number->round(0, RoundingMode::NegativeInfinity),
$number->round(0, RoundingMode::PositiveInfinity),
);
echo PHP_EOL;
echo 'Rounding modes with 8.5' . PHP_EOL;
$number = new BcMath\Number('8.5');
var_dump(
$number->round(0, RoundingMode::HalfAwayFromZero),
$number->round(0, RoundingMode::HalfTowardsZero),
$number->round(0, RoundingMode::HalfEven),
$number->round(0, RoundingMode::HalfOdd),
$number->round(0, RoundingMode::TowardsZero),
$number->round(0, RoundingMode::AwayFromZero),
$number->round(0, RoundingMode::NegativeInfinity),
$number->round(0, RoundingMode::PositiveInfinity),
);
?>`

The above example will output:

    Rounding modes with 9.5
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(2) "10"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#7 (2) {
      ["value"]=>
      string(2) "10"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#9 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#11 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#13 (2) {
      ["value"]=>
      string(2) "10"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#15 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#17 (2) {
      ["value"]=>
      string(2) "10"
      ["scale"]=>
      int(0)
    }

    Rounding modes with 8.5
    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#15 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#13 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#11 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#9 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#7 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(1) "8"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(1) "9"
      ["scale"]=>
      int(0)
    }

Example #4 Example of using BcMath\Number::round() with different `mode` values when specifying `precision`

`<?php
$positive = new BcMath\Number('1.55');
$negative = new BcMath\Number('-1.55');
echo 'Using RoundingMode::HalfAwayFromZero with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::HalfAwayFromZero),
$negative->round(1, RoundingMode::HalfAwayFromZero),
);
echo PHP_EOL;
echo 'Using RoundingMode::HalfTowardsZero with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::HalfTowardsZero),
$negative->round(1, RoundingMode::HalfTowardsZero),
);
echo PHP_EOL;
echo 'Using RoundingMode::HalfEven with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::HalfEven),
$negative->round(1, RoundingMode::HalfEven),
);
echo PHP_EOL;
echo 'Using RoundingMode::HalfOdd with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::HalfOdd),
$negative->round(1, RoundingMode::HalfOdd),
);
echo PHP_EOL;
echo 'Using RoundingMode::TowardsZero with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::TowardsZero),
$negative->round(1, RoundingMode::TowardsZero),
);
echo PHP_EOL;
echo 'Using RoundingMode::AwayFromZero with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::AwayFromZero),
$negative->round(1, RoundingMode::AwayFromZero),
);
echo PHP_EOL;
echo 'Using RoundingMode::NegativeInfinity with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::NegativeInfinity),
$negative->round(1, RoundingMode::NegativeInfinity),
);
echo PHP_EOL;
echo 'Using RoundingMode::PositiveInfinity with 1 decimal digit precision' . PHP_EOL;
var_dump(
$positive->round(1, RoundingMode::PositiveInfinity),
$negative->round(1, RoundingMode::PositiveInfinity),
);
?>`

The above example will output:

    Using RoundingMode::HalfAwayFromZero with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.6"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(4) "-1.6"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::HalfTowardsZero with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#6 (2) {
      ["value"]=>
      string(4) "-1.5"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::HalfEven with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.6"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#7 (2) {
      ["value"]=>
      string(4) "-1.6"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::HalfOdd with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#8 (2) {
      ["value"]=>
      string(4) "-1.5"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::TowardsZero with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#9 (2) {
      ["value"]=>
      string(4) "-1.5"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::AwayFromZero with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.6"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#10 (2) {
      ["value"]=>
      string(4) "-1.6"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::NegativeInfinity with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.5"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#11 (2) {
      ["value"]=>
      string(4) "-1.6"
      ["scale"]=>
      int(1)
    }

    Using RoundingMode::PositiveInfinity with 1 decimal digit precision
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(3) "1.6"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#12 (2) {
      ["value"]=>
      string(4) "-1.5"
      ["scale"]=>
      int(1)
    }

### See Also

- bcround() - Round arbitrary precision number
- BcMath\Number::ceil() - Rounds up an arbitrary precision number
- BcMath\Number::floor() - Rounds down an arbitrary precision number

# BcMath\Number::__serialize

(PHP 8 >= 8.4.0)

BcMath\Number::__serialize — Serializes a BcMath\Number object

### Description

public BcMath\Number::__serialize(): array

Serializes $this.

### Parameters

This function has no parameters.

### See Also

- BcMath\Number::__construct() - Creates a BcMath\Number object
- BcMath\Number::__unserialize() - Deserializes a data parameter into a BcMath\Number object

# BcMath\Number::sqrt

(PHP 8 >= 8.4.0)

BcMath\Number::sqrt — Gets the square root of an arbitrary precision number

### Description

public BcMath\Number::sqrt(?int `$scale` = `null`): BcMath\Number

Return the square root of $this.

### Parameters

`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the square root as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the BcMath\Number::scale of $this is used. However, in cases such as indivisible division, the BcMath\Number::scale of the result is expanded. Expansion is done only as needed, up to a maximum of `+10`. This behavior is the same as BcMath\Number::div(), so please see that for details.

That is, if the BcMath\Number::scale of $this is `5`, the BcMath\Number::scale of the result is between `5` and `15`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- $this is a negative value
- `scale` is outside the valid range
- BcMath\Number::scale of the result object is outside the valid range

### Examples

Example #1 BcMath\Number::sqrt() example

`<?php
var_dump(
new BcMath\Number('2')->sqrt(),
new BcMath\Number('2')->sqrt(3),
new BcMath\Number('4')->sqrt(),
new BcMath\Number('4')->sqrt(3),
);
?>`

The above example will output:

    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(12) "1.4142135623"
      ["scale"]=>
      int(10)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(5) "1.414"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(1) "2"
      ["scale"]=>
      int(0)
    }
    object(BcMath\Number)#5 (2) {
      ["value"]=>
      string(5) "2.000"
      ["scale"]=>
      int(3)
    }

### See Also

- bcsqrt() - Get the square root of an arbitrary precision number
- BcMath\Number::div() - Divides by an arbitrary precision number
- BcMath\Number::pow() - Raises an arbitrary precision number

# BcMath\Number::sub

(PHP 8 >= 8.4.0)

BcMath\Number::sub — Subtracts an arbitrary precision number

### Description

public BcMath\Number::sub(BcMath\Number|string|int `$num`, ?int `$scale` = `null`): BcMath\Number

Subtracts `num` from $this.

### Parameters

`num`
  The value to subtract.
`scale`
  BcMath\Number::scale explicitly specified for calculation results. If `null`, the BcMath\Number::scale of the calculation result will be set automatically.

### Return Values

Returns the result of subtraction as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the greater BcMath\Number::scale of the two numbers used for subtraction is used.

That is, if the BcMath\Number::scales of two values are `2` and `5` respectively, the BcMath\Number::scale of the result will be `5`.

### Errors/Exceptions

This method throws a ValueError in the following cases:

- `num` is string and not a well-formed BCMath numeric string
- `scale` is outside the valid range

### Examples

Example #1 BcMath\Number::sub() example when `scale` is not specified

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->sub(new BcMath\Number('2.34567'));
$ret2 = $number->sub('-3.456');
$ret3 = $number->sub(7);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(8) "-1.11167"
      ["scale"]=>
      int(5)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(5) "4.690"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(6) "-5.766"
      ["scale"]=>
      int(3)
    }

Example #2 BcMath\Number::sub() example of explicitly specifying `scale`

`<?php
$number = new BcMath\Number('1.234');
$ret1 = $number->sub(new BcMath\Number('2.34567'), 1);
$ret2 = $number->sub('-3.456', 10);
$ret3 = $number->sub(7, 0);
var_dump($number, $ret1, $ret2, $ret3);
?>`

The above example will output:

    object(BcMath\Number)#1 (2) {
      ["value"]=>
      string(5) "1.234"
      ["scale"]=>
      int(3)
    }
    object(BcMath\Number)#3 (2) {
      ["value"]=>
      string(4) "-1.1"
      ["scale"]=>
      int(1)
    }
    object(BcMath\Number)#2 (2) {
      ["value"]=>
      string(12) "4.6900000000"
      ["scale"]=>
      int(10)
    }
    object(BcMath\Number)#4 (2) {
      ["value"]=>
      string(2) "-5"
      ["scale"]=>
      int(0)
    }

### See Also

- bcsub() - Subtract one arbitrary precision number from another
- BcMath\Number::add() - Adds an arbitrary precision number

# BcMath\Number::__toString

(PHP 8 >= 8.4.0)

BcMath\Number::__toString — Converts BcMath\Number to string

### Description

public BcMath\Number::__toString(): string

Converts BcMath\Number to string.

### Parameters

This function has no parameters.

### Return Values

Returns BcMath\Number::value as a string.

# BcMath\Number::__unserialize

(PHP 8 >= 8.4.0)

BcMath\Number::__unserialize — Deserializes a data parameter into a BcMath\Number object

### Description

public BcMath\Number::__unserialize(array `$data`): void

Deserializes a data parameter into a BcMath\Number object.

### Parameters

`data`
  The serialized data parameter as an associative array

### Errors/Exceptions

This method throws a ValueError if invalid serialized data is passed.

### See Also

- BcMath\Number::__construct() - Creates a BcMath\Number object
- BcMath\Number::serialize()

## Table of Contents

- BcMath\Number::add — Adds an arbitrary precision number
- BcMath\Number::ceil — Rounds up an arbitrary precision number
- BcMath\Number::compare — Compares two arbitrary precision numbers
- BcMath\Number::__construct — Creates a BcMath\Number object
- BcMath\Number::div — Divides by an arbitrary precision number
- BcMath\Number::divmod — Gets the quotient and modulus of an arbitrary precision number
- BcMath\Number::floor — Rounds down an arbitrary precision number
- BcMath\Number::mod — Gets the modulus of an arbitrary precision number
- BcMath\Number::mul — Multiplies an arbitrary precision number
- BcMath\Number::pow — Raises an arbitrary precision number
- BcMath\Number::powmod — Raises an arbitrary precision number, reduced by a specified modulus
- BcMath\Number::round — Rounds an arbitrary precision number
- BcMath\Number::__serialize — Serializes a BcMath\Number object
- BcMath\Number::sqrt — Gets the square root of an arbitrary precision number
- BcMath\Number::sub — Subtracts an arbitrary precision number
- BcMath\Number::__toString — Converts BcMath\Number to string
- BcMath\Number::__unserialize — Deserializes a data parameter into a BcMath\Number object

- Installing/Configuring
  - Installation
  - Runtime Configuration
- BC Math Functions
  - bcadd — Add two arbitrary precision numbers
  - bcceil — Round up arbitrary precision number
  - bccomp — Compare two arbitrary precision numbers
  - bcdiv — Divide two arbitrary precision numbers
  - bcdivmod — Get the quotient and modulus of an arbitrary precision number
  - bcfloor — Round down arbitrary precision number
  - bcmod — Get modulus of an arbitrary precision number
  - bcmul — Multiply two arbitrary precision numbers
  - bcpow — Raise an arbitrary precision number to another
  - bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  - bcround — Round arbitrary precision number
  - bcscale — Set or get default scale parameter for all bc math functions
  - bcsqrt — Get the square root of an arbitrary precision number
  - bcsub — Subtract one arbitrary precision number from another
- BcMath\Number — The BcMath\Number class
  - BcMath\Number::add — Adds an arbitrary precision number
  - BcMath\Number::ceil — Rounds up an arbitrary precision number
  - BcMath\Number::compare — Compares two arbitrary precision numbers
  - BcMath\Number::__construct — Creates a BcMath\Number object
  - BcMath\Number::div — Divides by an arbitrary precision number
  - BcMath\Number::divmod — Gets the quotient and modulus of an arbitrary precision number
  - BcMath\Number::floor — Rounds down an arbitrary precision number
  - BcMath\Number::mod — Gets the modulus of an arbitrary precision number
  - BcMath\Number::mul — Multiplies an arbitrary precision number
  - BcMath\Number::pow — Raises an arbitrary precision number
  - BcMath\Number::powmod — Raises an arbitrary precision number, reduced by a specified modulus
  - BcMath\Number::round — Rounds an arbitrary precision number
  - BcMath\Number::__serialize — Serializes a BcMath\Number object
  - BcMath\Number::sqrt — Gets the square root of an arbitrary precision number
  - BcMath\Number::sub — Subtracts an arbitrary precision number
  - BcMath\Number::__toString — Converts BcMath\Number to string
  - BcMath\Number::__unserialize — Deserializes a data parameter into a BcMath\Number object

# GNU Multiple Precision

# Introduction

These functions allow for arbitrary-length integers to be worked with using the GNU MP library.

> Note:

> Most GMP functions accept GMP number arguments. These are shown in this documentation as GMP objects. Most of these functions will also accept numeric and string arguments, so long as it is possible to convert the latter to a number. Also, if there is a more performant function that can operate on the arguments (integers only), then it will be used instead (this is done transparently). See also the gmp_init() function.

> Note:

> The arithmetic, bitwise, and comparison operators may be used with the GMP objects returned from gmp_init() and other GMP functions.

Warning

Large integers must be specified as strings - otherwise, PHP will coerce them to floats, resulting in a loss of precision.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

The GMP library can be downloaded from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

At least GMP version 4.2 is required, with some functions requiring a more recent version of the GMP library.

On Windows, MPIR is required instead of GMP.

## Installation

In order to have these functions available, PHP must be compiled with GMP support by using the --with-gmp option.

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

`GMP_ROUND_ZERO` (int)
`GMP_ROUND_PLUSINF` (int)
`GMP_ROUND_MINUSINF` (int)
`GMP_MSW_FIRST` (int)
`GMP_LSW_FIRST` (int)
`GMP_LITTLE_ENDIAN` (int)
`GMP_BIG_ENDIAN` (int)
`GMP_NATIVE_ENDIAN` (int)
`GMP_VERSION` (string)
  The GMP library version
`GMP_MPIR_VERSION` (string)
  The MPIR library version.

# Examples

Example #1 Factorial function using GMP

`<?php
function fact($x)
{
$return = 1;
for ($i=2; $i <= $x; $i++) {
$return = gmp_mul($return, $i);
}
return $return;
}
echo gmp_strval(fact(1000)) . "\n";
?>`

This will calculate factorial of 1000 (pretty big number) very fast.

# GMP Functions

## See Also

More mathematical functions can be found in the Mathematical Extensions section

# gmp_abs

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_abs — Absolute value

### Description

gmp_abs(GMP|int|string `$num`): GMP

Get the absolute value of a number.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns the absolute value of `num`, as a GMP number.

### Examples

Example #1 gmp_abs() example

`<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");
echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>`

The above example will output:

    274982683358
    274982683358

# gmp_add

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_add — Add numbers

### Description

gmp_add(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Add two numbers.

### Parameters

`num1`

  The first summand (augent).

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The second summand (addend).

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP number representing the sum of the arguments.

### Examples

Example #1 gmp_add() example

`<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>`

The above example will output:

    200000000000000

# gmp_and

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_and — Bitwise AND

### Description

gmp_and(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Calculates bitwise AND of two GMP numbers.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP number representing the bitwise `AND` comparison.

### Examples

Example #1 gmp_and() example

`<?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?>`

The above example will output:

    4
    0

# gmp_binomial

(PHP 7 >= 7.3.0, PHP 8)

gmp_binomial — Calculates binomial coefficient

### Description

gmp_binomial(GMP|int|string `$n`, int `$k`): GMP

Calculates the binomial coefficient C(n, k).

### Parameters

`n`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`k`

### Return Values

Returns the binomial coefficient C(n, k).

### Errors/Exceptions

Throws ValueError if `k` is negative. Prior to PHP 8.0.0, `E_WARNING` was issued instead.

### Changelog

Version | Description
--- | ---
8.0.0 | This function no longer returns `false` on failure.

# gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_clrbit — Clear bit

### Description

gmp_clrbit(GMP `$num`, int `$index`): void

Clears (sets to 0) bit `index` in `num`. The index starts at 0.

### Parameters

`num`

  A GMP object.

`index`

  The index of the bit to clear. Index 0 represents the least significant bit.

### Return Values

No value is returned.

### Examples

Example #1 gmp_clrbit() example

`<?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?>`

The above example will output:

    254

### Notes

> Note:

> Unlike most of the other GMP functions, gmp_clrbit() must be called with a GMP object that already exists (using gmp_init() for example). One will not be automatically created.

### See Also

- gmp_setbit() - Set bit
- gmp_testbit() - Tests if a bit is set

# gmp_cmp

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_cmp — Compare numbers

### Description

gmp_cmp(GMP|int|string `$num1`, GMP|int|string `$num2`): int

Compares two numbers.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns a positive value if `a > b`, zero if `a = b` and a negative value if `a < b`.

### Examples

Example #1 gmp_cmp() example

`<?php
$cmp1 = gmp_cmp("1234", "1000"); // greater than
$cmp2 = gmp_cmp("1000", "1234"); // less than
$cmp3 = gmp_cmp("1234", "1234"); // equal to
echo "$cmp1 $cmp2 $cmp3\n";
?>`

The above example will output:

    1 -1 0

# gmp_com

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_com — Calculates one's complement

### Description

gmp_com(GMP|int|string `$num`): GMP

Returns the one's complement of `num`.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns the one's complement of `num`, as a GMP number.

### Examples

Example #1 gmp_com() example

`<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>`

The above example will output:

    -1235

# gmp_div

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div — Alias of gmp_div_q()

### Description

This function is an alias of: gmp_div_q().

# gmp_div_q

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_q — Divide numbers

### Description

gmp_div_q(GMP|int|string `$num1`, GMP|int|string `$num2`, int `$rounding_mode` = `GMP_ROUND_ZERO`): GMP

Divides `num1` by `num2` and returns the integer result.

### Parameters

`num1`

  The number being divided.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The number that `num1` is being divided by.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`rounding_mode`

  The result rounding is defined by the `rounding_mode`, which can have the following values:

  - `GMP_ROUND_ZERO`: The result is truncated towards 0.
  - `GMP_ROUND_PLUSINF`: The result is rounded towards `+infinity`.
  - `GMP_ROUND_MINUSINF`: The result is rounded towards `-infinity`.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_div_q() example

`<?php
$div1 = gmp_div_q("100", "5");
echo gmp_strval($div1) . "\n";
$div2 = gmp_div_q("1", "3");
echo gmp_strval($div2) . "\n";
$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";
$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";
$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
?>`

The above example will output:

    20
    0
    1
    0
    -1

### Notes

> Note:

> This function can also be called as gmp_div().

### See Also

- gmp_div_r() - Remainder of the division of numbers
- gmp_div_qr() - Divide numbers and get quotient and remainder

# gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_qr — Divide numbers and get quotient and remainder

### Description

gmp_div_qr(GMP|int|string `$num1`, GMP|int|string `$num2`, int `$rounding_mode` = `GMP_ROUND_ZERO`): array

The function divides `num1` by `num2`.

### Parameters

`num1`

  The number being divided.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The number that `num1` is being divided by.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`rounding_mode`

  See the gmp_div_q() function for description of the `rounding_mode` argument.

### Return Values

Returns an array, with the first element being `[n/d]` (the integer result of the division) and the second being `(n - [n/d] * d)` (the remainder of the division).

### Examples

Example #1 Division of GMP numbers

`<?php
$a = gmp_init("0x41682179fbf5");
$res = gmp_div_qr($a, "0xDEFE75");
printf("Result is: q - %s, r - %s",
gmp_strval($res[0]), gmp_strval($res[1]));
?>`

### See Also

- gmp_div_q() - Divide numbers
- gmp_div_r() - Remainder of the division of numbers

# gmp_div_r

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_r — Remainder of the division of numbers

### Description

gmp_div_r(GMP|int|string `$num1`, GMP|int|string `$num2`, int `$rounding_mode` = `GMP_ROUND_ZERO`): GMP

Calculates remainder of the integer division of `num1` by `num2`. The remainder has the sign of the `num1` argument, if not zero.

### Parameters

`num1`

  The number being divided.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The number that `num1` is being divided by.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`rounding_mode`

  See the gmp_div_q() function for description of the `rounding_mode` argument.

### Return Values

The remainder, as a GMP number.

### Examples

Example #1 gmp_div_r() example

`<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>`

The above example will output:

    5

### See Also

- gmp_div_q() - Divide numbers
- gmp_div_qr() - Divide numbers and get quotient and remainder

# gmp_divexact

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_divexact — Exact division of numbers

### Description

gmp_divexact(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Divides `num1` by `num2`, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that `num2` divides `num1`.

### Parameters

`num1`

  The number being divided.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The number that `num1` is being divided by.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_divexact() example

`<?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";
$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?>`

The above example will output:

    5
    2863311534

# gmp_export

(PHP 5 >= 5.6.1, PHP 7, PHP 8)

gmp_export — Export to a binary string

### Description

gmp_export(GMP|int|string `$num`, int `$word_size` = 1, int `$flags` = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN): string

Export a GMP number to a binary string

### Parameters

`num`

  The GMP number being exported

`word_size`

  Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

`flags`

  Default value is `GMP_MSW_FIRST` | `GMP_NATIVE_ENDIAN`.

### Return Values

Returns a string.

### Changelog

Version | Description
--- | ---
8.0.0 | This function no longer returns `false` on failure.

### Examples

Example #1 gmp_export() example

`<?php
$number = gmp_init(16705);
echo gmp_export($number) . "\n";
?>`

The above example will output:

    AA

### See Also

- gmp_import() - Import from a binary string

# gmp_fact

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_fact — Factorial

### Description

gmp_fact(GMP|int|string `$num`): GMP

Calculates factorial (`num!`) of `num`.

### Parameters

`num`

  The factorial number.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_fact() example

`<?php
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";
$fact2 = gmp_fact(50); // 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
?>`

The above example will output:

    120
    30414093201713378043612608166064768844377641568960512000000000000

# gmp_gcd

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_gcd — Calculate GCD

### Description

gmp_gcd(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Calculate greatest common divisor of `num1` and `num2`. The result is always positive even if either of, or both, input operands are negative.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A positive GMP number that divides into both `num1` and `num2`.

### Examples

Example #1 gmp_gcd() example

`<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>`

The above example will output:

    3

### See Also

- gmp_lcm() - Calculate LCM

# gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_gcdext — Calculate GCD and multipliers

### Description

gmp_gcdext(GMP|int|string `$num1`, GMP|int|string `$num2`): array

Calculates g, s, and t, such that `a*s + b*t = g = gcd(a,b)`, where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: `a*x + b*y = c`. For more information, go to the » "Diophantine Equation" page at MathWorld

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

An array of GMP numbers.

### Examples

Example #1 Solving a linear Diophantine equation

`<?php
// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a = gmp_init(12);
$b = gmp_init(21);
$g = gmp_gcd($a, $b);
$r = gmp_gcdext($a, $b);
$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res = gmp_add(gmp_mul($a, $r['s']), gmp_mul($b, $r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));
if ($check_gcd && $check_res) {
$fmt = "Solution: %d*%d + %d*%d = %d\n";
printf($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
gmp_strval($r['t']), gmp_strval($r['g']));
} else {
echo "Error while solving the equation\n";
}
// output: Solution: 12*2 + 21*-1 = 3
?>`

# gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_hamdist — Hamming distance

### Description

gmp_hamdist(GMP|int|string `$num1`, GMP|int|string `$num2`): int

Returns the hamming distance between `num1` and `num2`. Both operands should be non-negative.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

  It should be positive.

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

  It should be positive.

### Return Values

The hamming distance between `num1` and `num2`, as an int.

### Examples

Example #1 gmp_hamdist() example

`<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";
/* hamdist is equivalent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>`

The above example will output:

    6
    6

### See Also

- gmp_popcount() - Population count
- gmp_xor() - Bitwise XOR

# gmp_import

(PHP 5 >= 5.6.1, PHP 7, PHP 8)

gmp_import — Import from a binary string

### Description

gmp_import(string `$data`, int `$word_size` = 1, int `$flags` = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN): GMP

Import a GMP number from a binary string

### Parameters

`data`

  The binary string being imported

`word_size`

  Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

`flags`

  Default value is `GMP_MSW_FIRST` | `GMP_NATIVE_ENDIAN`.

### Return Values

Returns a GMP number.

### Changelog

Version | Description
--- | ---
8.0.0 | This function no longer returns `false` on failure.

### Examples

Example #1 gmp_import() example

`<?php
$number = gmp_import("\0");
echo gmp_strval($number) . "\n";
$number = gmp_import("\0\1\2");
echo gmp_strval($number) . "\n";
?>`

The above example will output:

    0
    258

### See Also

- gmp_export() - Export to a binary string

# gmp_init

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_init — Create GMP number

### Description

gmp_init(int|string `$num`, int `$base` = 0): GMP

Creates a GMP number from an integer or string.

### Parameters

`num`
  An integer or a string. The string representation can be decimal, hexadecimal, octal, or binary.
`base`
  The base to use for converting a string representation. An explicit base can be between `2` and `62`. For bases up to `36`, case is ignored; upper-case and lower-case letters have the same value. For bases `37` to `62`, upper-case letter represent the values `10` to `35` and lower-case letter represent the values `36` to `61`. If `base` is `0` then the actual base is determined from the leading characters of `num`. If the first two characters are `0x` or `0X`, the string is interpreted as a hexadecimal integer. If the first two characters are `0b` or `0B`, the string is interpreted as a binary integer. If the first two characters are `0o` or `0o`, the string is interpreted as an octal integer. Moreover, if the first character is `0` the string is also interpreted as an octal integer. In all other cases, the string is interpreted as a decimal integer.

### Return Values

A GMP object.

### Changelog

Version | Description
--- | ---
8.1.0 | Support for explicit octal prefixes `0o` and `0o` has been added for `num` strings. Interpretation of such prefixes when `base` is `0` has also been added.

### Examples

Example #1 Creating GMP number

`<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>`

### Notes

> Note:

> It is not necessary to call this function in order to use integers or strings in place of GMP numbers in GMP functions (such as with gmp_add()). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

### See Also

- GMP::__construct() - Create GMP number

# gmp_intval

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_intval — Convert GMP number to integer

### Description

gmp_intval(GMP|int|string `$num`): int

This function converts GMP number into native PHP ints.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

The int value of `num`.

### Examples

Example #1 gmp_intval() example

`<?php
// displays correct result
echo gmp_intval("2147483647") . "\n";
// displays wrong result, above PHP integer limit
echo gmp_intval("2147483648") . "\n";
// displays correct result
echo gmp_strval("2147483648") . "\n";
?>`

The above example will output:

    2147483647
    2147483647
    2147483648

### Notes

Warning

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). To simply print the GMP number, use gmp_strval().

# gmp_invert

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_invert — Inverse by modulo

### Description

gmp_invert(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP|false

Computes the inverse of `num1` modulo `num2`.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP number on success or `false` if an inverse does not exist.

### Examples

Example #1 gmp_invert() example

`<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?>`

The above example will output:

    9

# gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_jacobi — Jacobi symbol

### Description

gmp_jacobi(GMP|int|string `$num1`, GMP|int|string `$num2`): int

Computes » Jacobi symbol of `num1` and `num2`. `num2` should be odd and must be positive.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

  Should be odd and must be positive.

### Return Values

A GMP object.

### Examples

Example #1 gmp_jacobi() example

`<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>`

The above example will output:

    1
    0

### See Also

- gmp_kronecker() - Kronecker symbol
- gmp_legendre() - Legendre symbol

# gmp_kronecker

(PHP 7 >= 7.3.0, PHP 8)

gmp_kronecker — Kronecker symbol

### Description

gmp_kronecker(GMP|int|string `$num1`, GMP|int|string `$num2`): int

This function computes the Kronecker symbol of `num1` and `num2`.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns the Kronecker symbol of `num1` and `num2`

### See Also

- gmp_jacobi() - Jacobi symbol
- gmp_legendre() - Legendre symbol

# gmp_lcm

(PHP 7 >= 7.3.0, PHP 8)

gmp_lcm — Calculate LCM

### Description

gmp_lcm(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

This function computes the least common multiple (lcm) of `num1` and `num2`.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### See Also

- gmp_gcd() - Calculate GCD

# gmp_legendre

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_legendre — Legendre symbol

### Description

gmp_legendre(GMP|int|string `$num1`, GMP|int|string `$num2`): int

Compute the » Legendre symbol of `num1` and `num2`. `num2` should be odd and must be positive.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

  Should be odd and must be positive.

### Return Values

A GMP object.

### Examples

Example #1 gmp_legendre() example

`<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>`

The above example will output:

    1
    0

### See Also

- gmp_jacobi() - Jacobi symbol
- gmp_kronecker() - Kronecker symbol

# gmp_mod

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_mod — Modulo operation

### Description

gmp_mod(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Calculates `num1` modulo `num2`. The result is always non-negative, the sign of `num2` is ignored.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The modulo that is being evaluated.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_mod() example

`<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>`

The above example will output:

    2

# gmp_mul

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_mul — Multiply numbers

### Description

gmp_mul(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Multiplies `num1` by `num2` and returns the result.

### Parameters

`num1`

  A number that will be multiplied by `num2`.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A number that will be multiplied by `num1`.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_mul() example

`<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>`

The above example will output:

    24691356000

# gmp_neg

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_neg — Negate number

### Description

gmp_neg(GMP|int|string `$num`): GMP

Returns the negative value of a number.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns -`num`, as a GMP number.

### Examples

Example #1 gmp_neg() example

`<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>`

The above example will output:

    -1
    1

# gmp_nextprime

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

gmp_nextprime — Find next prime number

### Description

gmp_nextprime(GMP|int|string `$num`): GMP

Find next prime number

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Return the next prime number greater than `num`, as a GMP number.

### Examples

Example #1 gmp_nextprime() example

`<?php
$prime1 = gmp_nextprime(10); // next prime number greater than 10
$prime2 = gmp_nextprime(-1000); // next prime number greater than -1000
echo gmp_strval($prime1) . "\n";
echo gmp_strval($prime2) . "\n";
?>`

The above example will output:

    11
    2

### Notes

> Note:

> This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

# gmp_or

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_or — Bitwise OR

### Description

gmp_or(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Calculates bitwise inclusive OR of two GMP numbers.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_or() example

`<?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?>`

The above example will output:

    fffffff6
    fffffff2

# gmp_perfect_power

(PHP 7 >= 7.3.0, PHP 8)

gmp_perfect_power — Perfect power check

### Description

gmp_perfect_power(GMP|int|string `$num`): bool

Checks whether `num` is a perfect power.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns `true` if `num` is a perfect power, `false` otherwise.

### See Also

- gmp_perfect_square() - Perfect square check

# gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_perfect_square — Perfect square check

### Description

gmp_perfect_square(GMP|int|string `$num`): bool

Check if a number is a perfect square.

### Parameters

`num`

  The number being checked as a perfect square.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns `true` if `num` is a perfect square, `false` otherwise.

### Examples

Example #1 gmp_perfect_square() example

`<?php
// 3 * 3, perfect square
var_dump(gmp_perfect_square("9"));
// not a perfect square
var_dump(gmp_perfect_square("7"));
// 1234567890 * 1234567890, perfect square
var_dump(gmp_perfect_square("1524157875019052100"));
?>`

The above example will output:

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

### See Also

- gmp_perfect_power() - Perfect power check
- gmp_sqrt() - Calculate square root
- gmp_sqrtrem() - Square root with remainder

# gmp_popcount

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_popcount — Population count

### Description

gmp_popcount(GMP|int|string `$num`): int

Get the population count.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

The population count of `num`, as an int.

### Examples

Example #1 gmp_popcount() example

`<?php
$pop1 = gmp_init("10000101", 2); // 3 1's
echo gmp_popcount($pop1) . "\n";
$pop2 = gmp_init("11111110", 2); // 7 1's
echo gmp_popcount($pop2) . "\n";
?>`

The above example will output:

    3
    7

# gmp_pow

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_pow — Raise number into power

### Description

gmp_pow(GMP|int|string `$num`, int `$exponent`): GMP

Raise `num` into power `exponent`.

### Parameters

`num`

  The base number.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`exponent`

  The positive power to raise the `num`.

### Return Values

The new (raised) number, as a GMP number. The case of `0^0` yields 1.

### Examples

Example #1 gmp_pow() example

`<?php
$pow1 = gmp_pow("2", 31);
echo gmp_strval($pow1) . "\n";
$pow2 = gmp_pow("0", 0);
echo gmp_strval($pow2) . "\n";
$pow3 = gmp_pow("2", -1); // Negative exp, generates warning
echo gmp_strval($pow3) . "\n";
?>`

The above example will output:

    2147483648
    1

# gmp_powm

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_powm — Raise number into power with modulo

### Description

gmp_powm(GMP|int|string `$num`, GMP|int|string `$exponent`, GMP|int|string `$modulus`): GMP

Calculate (`num` raised into power `exponent`) modulo `modulus`. If `exponent` is negative, result is undefined.

### Parameters

`num`

  The base number.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`exponent`

  The positive power to raise the `num`.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`modulus`

  The modulo.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

The new (raised) number, as a GMP number.

### Examples

Example #1 gmp_powm() example

`<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>`

The above example will output:

    2147483648

# gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_prob_prime — Check if number is "probably prime"

### Description

gmp_prob_prime(GMP|int|string `$num`, int `$repetitions` = 10): int

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

### Parameters

`num`

  The number being checked as a prime.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`repetitions`

  Reasonable values of `repetitions` vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

If this function returns 0, `num` is definitely not prime. If it returns 1, then `num` is "probably" prime. If it returns 2, then `num` is surely prime.

### Examples

Example #1 gmp_prob_prime() example

`<?php
// definitely not a prime
echo gmp_prob_prime("6") . "\n";
// probably a prime
echo gmp_prob_prime("1111111111111111111") . "\n";
// definitely a prime
echo gmp_prob_prime("11") . "\n";
?>`

The above example will output:

    0
    1
    2

# gmp_random

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_random — Random number

Warning

This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

### Description

gmp_random(int `$limiter` = 20): GMP

Generate a random number. The number will be between 0 and (2 ** n) - 1, where n is the number of bits per limb multiplied by `limiter`. If `limiter` is negative, negative numbers are generated.

A limb is an internal GMP mechanism. The number of bits in a limb is not static, and can vary from system to system. Generally, the number of bits in a limb is either 32 or 64, but this is not guaranteed.

Caution

This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.

If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG.

### Parameters

`limiter`

  The limiter.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A random GMP number.

### Examples

Example #1 gmp_random() example

`<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb
echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>`

The above example will output:

    1915834968
    8642564075890328087

# gmp_random_bits

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

gmp_random_bits — Random number

### Description

gmp_random_bits(int `$bits`): GMP

Generate a random number. The number will be between `0` and `2$bits - 1`.

`bits` must greater than 0, and the maximum value is restricted by available memory.

Caution

This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.

If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG.

### Parameters

`bits`

  The number of bits to generate.

### Return Values

A random GMP number.

### Errors/Exceptions

If `bits` is less than `1`, a ValueError will be thrown.

### Examples

Example #1 gmp_random_bits() example

`<?php
$rand1 = gmp_random_bits(3); // random number from 0 to 7
$rand2 = gmp_random_bits(5); // random number from 0 to 31
echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>`

The above example will output:

    3
    15

# gmp_random_range

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

gmp_random_range — Get a uniformly selected integer

### Description

gmp_random_range(GMP|int|string `$min`, GMP|int|string `$max`): GMP

Generate a random number. The number will be between `min` and `max`.

`min` and `max` can both be negative, but `min` must always be less than `max`.

Caution

This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.

If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG.

### Parameters

`min`

  A GMP number representing the lower bound for the random number

`max`

  A GMP number representing the upper bound for the random number

### Return Values

Returns a GMP object which contains a uniformly selected integer from the closed interval [`min`, `max`]. Both `min` and `max` are possible return values.

### Errors/Exceptions

If `max` is less than `min`, a ValueError will be thrown.

### Examples

Example #1 gmp_random_range() example

`<?php
$rand1 = gmp_random_range(0, 100); // random number between 0 and 100
$rand2 = gmp_random_range(-100, -10); // random number between -100 and -10
echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>`

The above example will output:

    42
    -67

# gmp_random_seed

(PHP 7, PHP 8)

gmp_random_seed — Sets the RNG seed

### Description

gmp_random_seed(GMP|int|string `$seed`): void

### Parameters

`seed`

  The seed to be set for the gmp_random(), gmp_random_bits(), and gmp_random_range() functions.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

No value is returned.

### Errors/Exceptions

Throws a ValueError if `seed` is invalid.

### Changelog

Version | Description
--- | ---
8.0.0 | If `seed` is invalid, gmp_random_seed() now throws a ValueError. Previously it emitted an `E_WARNING` and returned `false`.

### Examples

Example #1 gmp_random_seed() example

`<?php
// set the seed
gmp_random_seed(100);
var_dump(gmp_strval(gmp_random(1)));
// set the seed to something else
gmp_random_seed(gmp_init(-100));
var_dump(gmp_strval(gmp_random_bits(10)));
// set the seed to something invalid
var_dump(gmp_random_seed('not a number'));`

The above example will output:

    string(20) "15370156633245019617"
    string(3) "683"

    Warning: gmp_random_seed(): Unable to convert variable to GMP - string is not an integer in %s on line %d
    bool(false)

### See Also

- gmp_init() - Create GMP number
- gmp_random() - Random number
- gmp_random_bits() - Random number
- gmp_random_range() - Get a uniformly selected integer

# gmp_root

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

gmp_root — Take the integer part of nth root

### Description

gmp_root(GMP|int|string `$num`, int `$nth`): GMP

Takes the `nth` root of `num` and returns the integer component of the result.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`nth`

  The positive root to take of `num`.

### Return Values

The integer component of the resultant root, as a GMP number.

# gmp_rootrem

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

gmp_rootrem — Take the integer part and remainder of nth root

### Description

gmp_rootrem(GMP|int|string `$num`, int `$nth`): array

Takes the `nth` root of `num` and returns the integer component and remainder of the result.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`nth`

  The positive root to take of `num`.

### Return Values

A two element array, where the first element is the integer component of the root, and the second element is the remainder, both represented as GMP numbers.

# gmp_scan0

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_scan0 — Scan for 0

### Description

gmp_scan0(GMP|int|string `$num1`, int `$start`): int

Scans `num1`, starting with bit `start`, towards more significant bits, until the first clear bit is found.

### Parameters

`num1`

  The number to scan.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`start`

  The starting bit.

### Return Values

Returns the index of the found bit, as an int. The index starts from 0.

### Examples

Example #1 gmp_scan0() example

`<?php
// "0" bit is found at position 3. index starts at 0
$s1 = gmp_init("10111", 2);
echo gmp_scan0($s1, 0) . "\n";
// "0" bit is found at position 7. index starts at 5
$s2 = gmp_init("101110000", 2);
echo gmp_scan0($s2, 5) . "\n";
?>`

The above example will output:

    3
    7

# gmp_scan1

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_scan1 — Scan for 1

### Description

gmp_scan1(GMP|int|string `$num1`, int `$start`): int

Scans `num1`, starting with bit `start`, towards more significant bits, until the first set bit is found.

### Parameters

`num1`

  The number to scan.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`start`

  The starting bit.

### Return Values

Returns the index of the found bit, as an int. If no set bit is found, -1 is returned.

### Examples

Example #1 gmp_scan1() example

`<?php
// "1" bit is found at position 3. index starts at 0
$s1 = gmp_init("01000", 2);
echo gmp_scan1($s1, 0) . "\n";
// "1" bit is found at position 9. index starts at 5
$s2 = gmp_init("01000001111", 2);
echo gmp_scan1($s2, 5) . "\n";
?>`

The above example will output:

    3
    9

# gmp_setbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_setbit — Set bit

### Description

gmp_setbit(GMP `$num`, int `$index`, bool `$value` = `true`): void

Sets bit `index` in `num`.

### Parameters

`num`

  A GMP object.

`index`

  The index of the bit to set. Index 0 represents the least significant bit.

`value`

  True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off).

### Return Values

No value is returned.

### Examples

Example #1 gmp_setbit() example - 0 index

`<?php
$a = gmp_init("2"); //
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0); // 0b10 now becomes 0b11
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>`

The above example will output:

    2 -> 0b10
    3 -> 0b11

Example #2 gmp_setbit() example - 1 index

`<?php
$a = gmp_init("0xfd");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>`

The above example will output:

    253 -> 0b11111101
    255 -> 0b11111111

Example #3 gmp_setbit() example - clearing a bit

`<?php
$a = gmp_init("0xff");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0, false); // clear bit at index 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>`

The above example will output:

    255 -> 0b11111111
    254 -> 0b11111110

### Notes

> Note:

> Unlike most of the other GMP functions, gmp_setbit() must be called with a GMP object that already exists (using gmp_init() for example). One will not be automatically created.

### See Also

- gmp_clrbit() - Clear bit
- gmp_testbit() - Tests if a bit is set

# gmp_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sign — Sign of number

### Description

gmp_sign(GMP|int|string `$num`): int

Checks the sign of a number.

### Parameters

`num`

  Either a GMP object, or a numeric string provided that it is possible to convert the latter to an int.

### Return Values

Returns 1 if `num` is positive, -1 if `num` is negative, and 0 if `num` is zero.

### Examples

Example #1 gmp_sign() example

`<?php
// positive
echo gmp_sign("500") . "\n";
// negative
echo gmp_sign("-500") . "\n";
// zero
echo gmp_sign("0") . "\n";
?>`

The above example will output:

    1
    -1
    0

### See Also

- gmp_abs() - Absolute value
- abs() - Absolute value

# gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sqrt — Calculate square root

### Description

gmp_sqrt(GMP|int|string `$num`): GMP

Calculates square root of `num`.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

The integer portion of the square root, as a GMP number.

### Examples

Example #1 gmp_sqrt() example

`<?php
$sqrt1 = gmp_sqrt("9");
$sqrt2 = gmp_sqrt("7");
$sqrt3 = gmp_sqrt("1524157875019052100");
echo gmp_strval($sqrt1) . "\n";
echo gmp_strval($sqrt2) . "\n";
echo gmp_strval($sqrt3) . "\n";
?>`

The above example will output:

    3
    2
    1234567890

# gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sqrtrem — Square root with remainder

### Description

gmp_sqrtrem(GMP|int|string `$num`): array

Calculate the square root of a number, with remainder.

### Parameters

`num`

  The number being square rooted.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

Returns array where first element is the integer square root of `num` and the second is the remainder (i.e., the difference between `num` and the first element squared).

### Examples

Example #1 gmp_sqrtrem() example

`<?php
list($sqrt1, $sqrt1rem) = gmp_sqrtrem("9");
list($sqrt2, $sqrt2rem) = gmp_sqrtrem("7");
list($sqrt3, $sqrt3rem) = gmp_sqrtrem("1048576");
echo gmp_strval($sqrt1) . ", " . gmp_strval($sqrt1rem) . "\n";
echo gmp_strval($sqrt2) . ", " . gmp_strval($sqrt2rem) . "\n";
echo gmp_strval($sqrt3) . ", " . gmp_strval($sqrt3rem) . "\n";
?>`

The above example will output:

    3, 0
    2, 3
    1024, 0

# gmp_strval

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_strval — Convert GMP number to string

### Description

gmp_strval(GMP|int|string `$num`, int `$base` = 10): string

Convert GMP number to string representation in base `base`. The default base is 10.

### Parameters

`num`

  The GMP number that will be converted to a string.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`base`

  The base of the returned number. The default base is 10. Allowed values for the base are from 2 to 62 and -2 to -36.

### Return Values

The number, as a string.

### Examples

Example #1 Converting a GMP number to a string

`<?php
$a = gmp_init("0x41682179fbf5");
printf("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>`

# gmp_sub

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sub — Subtract numbers

### Description

gmp_sub(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Subtracts `num2` from `num1` and returns the result.

### Parameters

`num1`

  The number being subtracted from.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  The number subtracted from `num1`.

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_sub() example

`<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>`

The above example will output:

    281470681743360

# gmp_testbit

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gmp_testbit — Tests if a bit is set

### Description

gmp_testbit(GMP|int|string `$num`, int `$index`): bool

Tests if the specified bit is set.

### Parameters

`num`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`index`

  The bit to test

### Return Values

Returns `true` if the bit is set in `num`, otherwise `false`.

### Errors/Exceptions

An `E_WARNING` level error is issued when `index` is less than zero, and `false` is returned.

### Examples

Example #1 gmp_testbit() example

`<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>`

The above example will output:

    bool(false)
    bool(true)

### See Also

- gmp_setbit() - Set bit
- gmp_clrbit() - Clear bit

# gmp_xor

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_xor — Bitwise XOR

### Description

gmp_xor(GMP|int|string `$num1`, GMP|int|string `$num2`): GMP

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

### Parameters

`num1`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

`num2`

  A GMP object, an int, or a string that can be interpreted as a number following the same logic as if the string was used in gmp_init() with automatic base detection (i.e. when `base` is equal to 0).

### Return Values

A GMP object.

### Examples

Example #1 gmp_xor() example

`<?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);
$xor3 = gmp_xor($xor1, $xor2);
echo gmp_strval($xor3, 2) . "\n";
?>`

The above example will output:

    1011110111000100

## Table of Contents

- gmp_abs — Absolute value
- gmp_add — Add numbers
- gmp_and — Bitwise AND
- gmp_binomial — Calculates binomial coefficient
- gmp_clrbit — Clear bit
- gmp_cmp — Compare numbers
- gmp_com — Calculates one's complement
- gmp_div — Alias of gmp_div_q
- gmp_div_q — Divide numbers
- gmp_div_qr — Divide numbers and get quotient and remainder
- gmp_div_r — Remainder of the division of numbers
- gmp_divexact — Exact division of numbers
- gmp_export — Export to a binary string
- gmp_fact — Factorial
- gmp_gcd — Calculate GCD
- gmp_gcdext — Calculate GCD and multipliers
- gmp_hamdist — Hamming distance
- gmp_import — Import from a binary string
- gmp_init — Create GMP number
- gmp_intval — Convert GMP number to integer
- gmp_invert — Inverse by modulo
- gmp_jacobi — Jacobi symbol
- gmp_kronecker — Kronecker symbol
- gmp_lcm — Calculate LCM
- gmp_legendre — Legendre symbol
- gmp_mod — Modulo operation
- gmp_mul — Multiply numbers
- gmp_neg — Negate number
- gmp_nextprime — Find next prime number
- gmp_or — Bitwise OR
- gmp_perfect_power — Perfect power check
- gmp_perfect_square — Perfect square check
- gmp_popcount — Population count
- gmp_pow — Raise number into power
- gmp_powm — Raise number into power with modulo
- gmp_prob_prime — Check if number is "probably prime"
- gmp_random — Random number
- gmp_random_bits — Random number
- gmp_random_range — Get a uniformly selected integer
- gmp_random_seed — Sets the RNG seed
- gmp_root — Take the integer part of nth root
- gmp_rootrem — Take the integer part and remainder of nth root
- gmp_scan0 — Scan for 0
- gmp_scan1 — Scan for 1
- gmp_setbit — Set bit
- gmp_sign — Sign of number
- gmp_sqrt — Calculate square root
- gmp_sqrtrem — Square root with remainder
- gmp_strval — Convert GMP number to string
- gmp_sub — Subtract numbers
- gmp_testbit — Tests if a bit is set
- gmp_xor — Bitwise XOR

# The GMP class

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

## Introduction

A GMP number. These objects support overloaded arithmetic, bitwise and comparison operators.

> Note:

> No object-oriented interface is provided to manipulate GMP objects. Please use the procedural GMP API.

## Class synopsis

final class GMP {
/* Methods */
public __construct(int|string `$num` = 0, int `$base` = 0)
public __serialize(): array
public __unserialize(array `$data`): void
}

## Changelog

Version | Description
--- | ---
8.4.0 | GMP is now marked final

# GMP::__construct

(PHP 8 >= 8.2.4)

GMP::__construct — Create GMP number

### Description

public GMP::__construct(int|string `$num` = 0, int `$base` = 0)

Creates a GMP number from an integer or string.

### Parameters

`num`
  An integer or a string. The string representation can be decimal, hexadecimal, octal, or binary.
`base`
  The base to use for converting a string representation. An explicit base can be between `2` and `62`. For bases up to `36`, case is ignored; upper-case and lower-case letters have the same value. For bases `37` to `62`, upper-case letter represent the values `10` to `35` and lower-case letter represent the values `36` to `61`. If `base` is `0` then the actual base is determined from the leading characters of `num`. If the first two characters are `0x` or `0X`, the string is interpreted as a hexadecimal integer. If the first two characters are `0b` or `0B`, the string is interpreted as a binary integer. If the first two characters are `0o` or `0o`, the string is interpreted as an octal integer. Moreover, if the first character is `0` the string is also interpreted as an octal integer. In all other cases, the string is interpreted as a decimal integer.

### See Also

- gmp_init() - Create GMP number

# GMP::__serialize

(PHP 8 >= 8.1.0)

GMP::__serialize — Serializes the GMP object

### Description

public GMP::__serialize(): array

Warning

This function is currently not documented; only its argument list is available.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# GMP::__unserialize

(PHP 8 >= 8.1.0)

GMP::__unserialize — Deserializes the `data` parameter into a GMP object

### Description

public GMP::__unserialize(array `$data`): void

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`data`

  The value being deserialized.

### Return Values

No value is returned.

## Table of Contents

- GMP::__construct — Create GMP number
- GMP::__serialize — Serializes the GMP object
- GMP::__unserialize — Deserializes the data parameter into a GMP object

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Examples
- GMP Functions
  - gmp_abs — Absolute value
  - gmp_add — Add numbers
  - gmp_and — Bitwise AND
  - gmp_binomial — Calculates binomial coefficient
  - gmp_clrbit — Clear bit
  - gmp_cmp — Compare numbers
  - gmp_com — Calculates one's complement
  - gmp_div — Alias of gmp_div_q
  - gmp_div_q — Divide numbers
  - gmp_div_qr — Divide numbers and get quotient and remainder
  - gmp_div_r — Remainder of the division of numbers
  - gmp_divexact — Exact division of numbers
  - gmp_export — Export to a binary string
  - gmp_fact — Factorial
  - gmp_gcd — Calculate GCD
  - gmp_gcdext — Calculate GCD and multipliers
  - gmp_hamdist — Hamming distance
  - gmp_import — Import from a binary string
  - gmp_init — Create GMP number
  - gmp_intval — Convert GMP number to integer
  - gmp_invert — Inverse by modulo
  - gmp_jacobi — Jacobi symbol
  - gmp_kronecker — Kronecker symbol
  - gmp_lcm — Calculate LCM
  - gmp_legendre — Legendre symbol
  - gmp_mod — Modulo operation
  - gmp_mul — Multiply numbers
  - gmp_neg — Negate number
  - gmp_nextprime — Find next prime number
  - gmp_or — Bitwise OR
  - gmp_perfect_power — Perfect power check
  - gmp_perfect_square — Perfect square check
  - gmp_popcount — Population count
  - gmp_pow — Raise number into power
  - gmp_powm — Raise number into power with modulo
  - gmp_prob_prime — Check if number is "probably prime"
  - gmp_random — Random number
  - gmp_random_bits — Random number
  - gmp_random_range — Get a uniformly selected integer
  - gmp_random_seed — Sets the RNG seed
  - gmp_root — Take the integer part of nth root
  - gmp_rootrem — Take the integer part and remainder of nth root
  - gmp_scan0 — Scan for 0
  - gmp_scan1 — Scan for 1
  - gmp_setbit — Set bit
  - gmp_sign — Sign of number
  - gmp_sqrt — Calculate square root
  - gmp_sqrtrem — Square root with remainder
  - gmp_strval — Convert GMP number to string
  - gmp_sub — Subtract numbers
  - gmp_testbit — Tests if a bit is set
  - gmp_xor — Bitwise XOR
- GMP — The GMP class
  - GMP::__construct — Create GMP number
  - GMP::__serialize — Serializes the GMP object
  - GMP::__unserialize — Deserializes the data parameter into a GMP object

# Mathematical Functions

# Introduction

These math functions will only handle values within the range of the int and float types. To handle larger numbers, take a look at the arbitrary precision math or GNU Multiple Precision functions functions.

## See Also

- arithmetic operators
- Arbitrary precision math functions
- GNU Multiple Precision functions

# Predefined Constants

The constants below are always available as part of the PHP core.

Mathematical Constants
`M_PI` (float)
  Approximation of the number π (pi). (`3.14159265358979323846`).
`M_E` (float)
  Approximation of Euler's number `e` (`2.7182818284590452354`).
`M_LOG2E` (float)
  Approximation of `log2(e)` (`1.4426950408889634074`).
`M_LOG10E` (float)
  Approximation of `log10(e)` (`0.43429448190325182765`).
`M_LN2` (float)
  Approximation of `ln(2)` (`0.69314718055994530942`).
`M_LN10` (float)
  Approximation of `ln(10)` (`2.30258509299404568402`).
`M_PI_2` (float)
  Approximation of `π/2` (`1.57079632679489661923`).
`M_PI_4` (float)
  Approximation of `π/4` (`0.78539816339744830962`).
`M_1_PI` (float)
  Approximation of `1/π` (`0.31830988618379067154`).
`M_2_PI` (float)
  Approximation of `2/π` (`0.63661977236758134308`).
`M_SQRTPI` (float)
  Approximation of `sqrt(π)` (`1.77245385090551602729`).
`M_2_SQRTPI` (float)
  Approximation of `2/sqrt(π)` (`1.12837916709551257390`).
`M_SQRT2` (float)
  Approximation of `sqrt(2)` (`1.41421356237309504880`).
`M_SQRT3` (float)
  Approximation of `sqrt(3)` (`1.73205080756887729352`).
`M_SQRT1_2` (float)
  Approximation of `1/sqrt(2)` (`0.70710678118654752440`).
`M_LNPI` (float)
  Approximation of `ln(π)` (`1.14472988584940017414`).
`M_EULER` (float)
  Approximation of Euler's constant γ (`0.57721566490153286061`).

IEEE 754 floating point constants
`NAN` (float)
  Not A Number
`INF` (float)
  Infinity

Rounding constants

> Note: As of PHP 8.4.0, it is recommended to use the RoundingMode enum instead.

`PHP_ROUND_HALF_UP` (int)
  Rounding half away from zero.
`PHP_ROUND_HALF_DOWN` (int)
  Rounding half toward zero.
`PHP_ROUND_HALF_EVEN` (int)
  Round halves to even numbers
`PHP_ROUND_HALF_ODD` (int)
  Round halves to odd numbers

# The RoundingMode Enum

(PHP 8 >= 8.4.0)

## Introduction

The RoundingMode enum is used to specify how rounding should be performed for round(), bcround(), and BcMath\Number::round().

## Enum synopsis

enum RoundingMode
{
case HalfAwayFromZero ; // Round to the nearest integer. If the decimal part is `5`, round to the integer with the larger absolute value.
case HalfTowardsZero ; // Round to the nearest integer. If the decimal part is `5`, round to the integer with the smaller absolute value.
case HalfEven ; // Round to the nearest integer. If the decimal part is `5`, round to the even integer.
case HalfOdd ; // Round to the nearest integer. If the decimal part is `5`, round to the odd integer.
case TowardsZero ; // Round to the nearest integer with a smaller or equal absolute value.
case AwayFromZero ; // Round to the nearest integer with a greater or equal absolute value.
case NegativeInfinity ; // Round to the largest integer that is smaller or equal.
case PositiveInfinity ; // Round to the smallest integer that is greater or equal.
}

# Math Functions

# abs

(PHP 4, PHP 5, PHP 7, PHP 8)

abs — Absolute value

### Description

abs(int|float `$num`): int|float

Returns the absolute value of `num`.

### Parameters

`num`

  The numeric value to process

### Return Values

The absolute value of `num`. If the argument `num` is of type float, the return type is also float, otherwise it is int (as float usually has a bigger value range than int).

### Changelog

Version | Description
--- | ---
8.0.0 | `num` no longer accepts internal objects which support numeric conversion.

### Examples

Example #1 abs() example

`<?php
var_dump(abs(-4.2));
var_dump(abs(5));
var_dump(abs(-5));
?>`

The above example will output:

    float(4.2)
    int(5)
    int(5)

### See Also

- gmp_abs() - Absolute value
- gmp_sign() - Sign of number

# acos

(PHP 4, PHP 5, PHP 7, PHP 8)

acos — Arc cosine

### Description

acos(float `$num`): float

Returns the arc cosine of `num` in radians. acos() is the inverse function of cos(), which means that `$num == cos(acos($num))` for every value of `num` that is in the domain of acos().

### Parameters

`num`

  The argument to process

### Return Values

The arc cosine of `num` in radians.

### See Also

- cos() - Cosine
- acosh() - Inverse hyperbolic cosine
- asin() - Arc sine
- atan() - Arc tangent

# acosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

acosh — Inverse hyperbolic cosine

### Description

acosh(float `$num`): float

Returns the inverse hyperbolic cosine of `num`, i.e. the value whose hyperbolic cosine is `num`.

### Parameters

`num`

  The value to process

### Return Values

The inverse hyperbolic cosine of `num`

### See Also

- cosh() - Hyperbolic cosine
- acos() - Arc cosine
- asinh() - Inverse hyperbolic sine
- atanh() - Inverse hyperbolic tangent

# asin

(PHP 4, PHP 5, PHP 7, PHP 8)

asin — Arc sine

### Description

asin(float `$num`): float

Returns the arc sine of `num` in radians. asin() is the inverse function of sin(), which means that `$num == sin(asin($num))` for every value of `num` that is in the domain of asin().

### Parameters

`num`

  The argument to process

### Return Values

The arc sine of `num` in radians

### See Also

- sin() - Sine
- asinh() - Inverse hyperbolic sine
- acos() - Arc cosine
- atan() - Arc tangent

# asinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

asinh — Inverse hyperbolic sine

### Description

asinh(float `$num`): float

Returns the inverse hyperbolic sine of `num`, i.e. the value whose hyperbolic sine is `num`.

### Parameters

`num`

  The argument to process

### Return Values

The inverse hyperbolic sine of `num`

### See Also

- sinh() - Hyperbolic sine
- asin() - Arc sine
- acosh() - Inverse hyperbolic cosine
- atanh() - Inverse hyperbolic tangent

# atan

(PHP 4, PHP 5, PHP 7, PHP 8)

atan — Arc tangent

### Description

atan(float `$num`): float

Returns the arc tangent of `num` in radians. atan() is the inverse function of tan(), which means that `$num == tan(atan($num))` for every value of `num` that is in the domain of atan().

### Parameters

`num`

  The argument to process

### Return Values

The arc tangent of `num` in radians.

### See Also

- tan() - Tangent
- atanh() - Inverse hyperbolic tangent
- asin() - Arc sine
- acos() - Arc cosine

# atan2

(PHP 4, PHP 5, PHP 7, PHP 8)

atan2 — Arc tangent of two variables

### Description

atan2(float `$y`, float `$x`): float

This function calculates the arc tangent of the two variables `x` and `y`. It is similar to calculating the arc tangent of `y` / `x`, except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

### Parameters

`y`

  Dividend parameter

`x`

  Divisor parameter

### Return Values

The arc tangent of `y`/`x` in radians.

### See Also

- atan() - Arc tangent

# atanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

atanh — Inverse hyperbolic tangent

### Description

atanh(float `$num`): float

Returns the inverse hyperbolic tangent of `num`, i.e. the value whose hyperbolic tangent is `num`.

### Parameters

`num`

  The argument to process

### Return Values

Inverse hyperbolic tangent of `num`

### See Also

- tanh() - Hyperbolic tangent
- atan() - Arc tangent
- asinh() - Inverse hyperbolic sine
- acosh() - Inverse hyperbolic cosine

# base_convert

(PHP 4, PHP 5, PHP 7, PHP 8)

base_convert — Convert a number between arbitrary bases

### Description

base_convert(string `$num`, int `$from_base`, int `$to_base`): string

Returns a string containing `num` represented in base `to_base`. The base in which `num` is given is specified in `from_base`. Both `from_base` and `to_base` have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. The case of the letters doesn't matter, i.e. `num` is interpreted case-insensitively.

Warning

base_convert() may lose precision on large numbers due to properties related to the internal float type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

### Parameters

`num`

  The number to convert. Any invalid characters in `num` are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.

`from_base`

  The base `num` is in

`to_base`

  The base to convert `num` to

### Return Values

`num` converted to base `to_base`

### Changelog

Version | Description
--- | ---
7.4.0 | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.

### Examples

Example #1 base_convert() example

`<?php
$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);
?>`

The above example will output:

    101000110111001100110100

### See Also

- intval() - Get the integer value of a variable

# bindec

(PHP 4, PHP 5, PHP 7, PHP 8)

bindec — Binary to decimal

### Description

bindec(string `$binary_string`): int|float

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

bindec() converts a binary number to an int or, if needed for size reasons, float.

bindec() interprets all `binary_string` values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

### Parameters

`binary_string`

  The binary string to convert. Any invalid characters in `binary_string` are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.

Warning

The parameter must be a string. Using other data types will produce unexpected results.

### Return Values

The decimal value of `binary_string`

### Changelog

Version | Description
--- | ---
7.4.0 | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.

### Examples

Example #1 bindec() example

`<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";
echo bindec('111');
?>`

The above example will output:

    51
    51
    7

Example #2 bindec() interprets input as unsigned integers

`<?php
/*
* The lesson from this example is in the output
* rather than the PHP code itself.
*/
$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover? Watch it next time around...');
p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');
if (PHP_INT_SIZE == 4) {
$note = 'interpreted to be the largest unsigned integer';
} else {
$note = 'interpreted to be the largest unsigned integer
(18446744073709551615) but skewed by float precision';
}
p(-1, $note);
function p($input, $note = '') {
echo "input: $input\n";
$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo "binary: $bin\n";
ini_set('precision', 20); // For readability on 64 bit boxes.
$dec = bindec($bin);
echo 'bindec(): ' . $dec . "\n";
if ($note) {
echo "NOTE: $note\n";
}
echo "\n";
}
?>`

Output of the above example on 32 bit machines:

    input:        1073741823
    binary:       00111111111111111111111111111111
    bindec():     1073741823

    input:        1073741824
    binary:       01000000000000000000000000000000
    bindec():     1073741824
    NOTE:         See the rollover?  Watch it next time around...

    input:        2147483647
    binary:       01111111111111111111111111111111
    bindec():     2147483647
    NOTE:         PHP_INT_MAX

    input:        -2147483648
    binary:       10000000000000000000000000000000
    bindec():     2147483648
    NOTE:         interpreted to be one more than PHP_INT_MAX

    input:        -1
    binary:       11111111111111111111111111111111
    bindec():     4294967295
    NOTE:         interpreted to be the largest unsigned integer

Output of the above example on 64 bit machines:

    input:        4611686018427387903
    binary:       0011111111111111111111111111111111111111111111111111111111111111
    bindec():     4611686018427387903

    input:        4611686018427387904
    binary:       0100000000000000000000000000000000000000000000000000000000000000
    bindec():     4611686018427387904
    NOTE:         See the rollover?  Watch it next time around...

    input:        9223372036854775807
    binary:       0111111111111111111111111111111111111111111111111111111111111111
    bindec():     9223372036854775807
    NOTE:         PHP_INT_MAX

    input:        -9223372036854775808
    binary:       1000000000000000000000000000000000000000000000000000000000000000
    bindec():     9223372036854775808
    NOTE:         interpreted to be one more than PHP_INT_MAX

    input:        -1
    binary:       1111111111111111111111111111111111111111111111111111111111111111
    bindec():     18446744073709551616
    NOTE:         interpreted to be the largest unsigned integer
                  (18446744073709551615) but skewed by float precision

### Notes

> Note:

> The function can convert numbers that are too large to fit into the platforms int type, larger values are returned as float in that case.

### See Also

- decbin() - Decimal to binary
- octdec() - Octal to decimal
- hexdec() - Hexadecimal to decimal
- base_convert() - Convert a number between arbitrary bases

# ceil

(PHP 4, PHP 5, PHP 7, PHP 8)

ceil — Round fractions up

### Description

ceil(int|float `$num`): float

Returns the next highest integer value by rounding up `num` if necessary.

### Parameters

`num`

  The value to round

### Return Values

`num` rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of int.

### Changelog

Version | Description
--- | ---
8.0.0 | `num` no longer accepts internal objects which support numeric conversion.

### Examples

Example #1 ceil() example

`<?php
echo ceil(4.3), PHP_EOL; // 5
echo ceil(9.999), PHP_EOL; // 10
echo ceil(-3.14), PHP_EOL; // -3
?>`

### See Also

- floor() - Round fractions down
- round() - Rounds a float

# cos

(PHP 4, PHP 5, PHP 7, PHP 8)

cos — Cosine

### Description

cos(float `$num`): float

cos() returns the cosine of the `num` parameter. The `num` parameter is in radians.

### Parameters

`num`

  An angle in radians

### Return Values

The cosine of `num`

### Examples

Example #1 cos() example

`<?php
echo cos(M_PI); // -1
?>`

### See Also

- acos() - Arc cosine
- sin() - Sine
- tan() - Tangent
- deg2rad() - Converts the number in degrees to the radian equivalent

# cosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cosh — Hyperbolic cosine

### Description

cosh(float `$num`): float

Returns the hyperbolic cosine of `num`, defined as `(exp($num) + exp(-$num))/2`.

### Parameters

`num`

  The argument to process

### Return Values

The hyperbolic cosine of `num`

### See Also

- cos() - Cosine
- acosh() - Inverse hyperbolic cosine
- sinh() - Hyperbolic sine
- tanh() - Hyperbolic tangent

# decbin

(PHP 4, PHP 5, PHP 7, PHP 8)

decbin — Decimal to binary

### Description

decbin(int `$num`): string

Returns a string containing a binary representation of the given `num` argument.

### Parameters

`num`

  Decimal value to convert

  Range of inputs on 32-bit machines
  positive `num` | negative `num` | return value
  --- | --- | ---
  0 |  | 0
  1 |  | 1
  2 |  | 10
  ... normal progression ...
  2147483646 |  | 1111111111111111111111111111110
  2147483647 (largest signed integer) |  | 1111111111111111111111111111111 (31 1's)
  2147483648 | -2147483648 | 10000000000000000000000000000000
  ... normal progression ...
  4294967294 | -2 | 11111111111111111111111111111110
  4294967295 (largest unsigned integer) | -1 | 11111111111111111111111111111111 (32 1's)

  Range of inputs on 64-bit machines
  positive `num` | negative `num` | return value
  --- | --- | ---
  0 |  | 0
  1 |  | 1
  2 |  | 10
  ... normal progression ...
  9223372036854775806 |  | 111111111111111111111111111111111111111111111111111111111111110
  9223372036854775807 (largest signed integer) |  | 111111111111111111111111111111111111111111111111111111111111111 (63 1's)
  | -9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000
  ... normal progression ...
  | -2 | 1111111111111111111111111111111111111111111111111111111111111110
  | -1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's)

### Return Values

Binary string representation of `num`

### Examples

Example #1 decbin() example

`<?php
echo decbin(12) . "\n";
echo decbin(26);
?>`

The above example will output:

    1100
    11010

### See Also

- bindec() - Binary to decimal
- decoct() - Decimal to octal
- dechex() - Decimal to hexadecimal
- base_convert() - Convert a number between arbitrary bases
- printf() - Output a formatted string, using `%b`, `%032b` or `%064b` as the format
- sprintf() - Return a formatted string, using `%b`, `%032b` or `%064b` as the format

# dechex

(PHP 4, PHP 5, PHP 7, PHP 8)

dechex — Decimal to hexadecimal

### Description

dechex(int `$num`): string

Returns a string containing a hexadecimal representation of the given unsigned `num` argument.

The largest number that can be converted is `PHP_INT_MAX``* 2 + 1` (or `-1`): on 32-bit platforms, this will be `4294967295` in decimal, which results in dechex() returning `ffffffff`.

### Parameters

`num`

  The decimal value to convert.

  As PHP's int type is signed, but dechex() deals with unsigned integers, negative integers will be treated as though they were unsigned.

### Return Values

Hexadecimal string representation of `num`.

### Examples

Example #1 dechex() example

`<?php
echo dechex(10) . "\n";
echo dechex(47);
?>`

The above example will output:

    a
    2f

Example #2 dechex() example with large integers

`<?php
// The output below assumes a 32-bit platform.
// Note that the output is the same for all values.
echo dechex(-1)."\n";
echo dechex(PHP_INT_MAX * 2 + 1)."\n";
echo dechex(pow(2, 32) - 1)."\n";
?>`

The above example will output:

    ffffffff
    ffffffff
    ffffffff

### See Also

- hexdec() - Hexadecimal to decimal
- decbin() - Decimal to binary
- decoct() - Decimal to octal
- base_convert() - Convert a number between arbitrary bases

# decoct

(PHP 4, PHP 5, PHP 7, PHP 8)

decoct — Decimal to octal

### Description

decoct(int `$num`): string

Returns a string containing an octal representation of the given `num` argument. The largest number that can be converted depends on the platform in use. For 32-bit platforms this is usually `4294967295` in decimal resulting in `37777777777`. For 64-bit platforms this is usually `9223372036854775807` in decimal resulting in `777777777777777777777`.

### Parameters

`num`

  Decimal value to convert

### Return Values

Octal string representation of `num`

### Examples

Example #1 decoct() example

`<?php
echo decoct(15) . "\n";
echo decoct(264);
?>`

The above example will output:

    17
    410

### See Also

- octdec() - Octal to decimal
- decbin() - Decimal to binary
- dechex() - Decimal to hexadecimal
- base_convert() - Convert a number between arbitrary bases

# deg2rad

(PHP 4, PHP 5, PHP 7, PHP 8)

deg2rad — Converts the number in degrees to the radian equivalent

### Description

deg2rad(float `$num`): float

This function converts `num` from degrees to the radian equivalent.

### Parameters

`num`

  Angular value in degrees

### Return Values

The radian equivalent of `num`

### Examples

Example #1 deg2rad() example

`<?php
echo deg2rad(45), PHP_EOL; // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)
?>`

### See Also

- rad2deg() - Converts the radian number to the equivalent number in degrees

# exp

(PHP 4, PHP 5, PHP 7, PHP 8)

exp — Calculates the exponent of `e`

### Description

exp(float `$num`): float

Returns `e` raised to the power of `num`.

> Note:

> '`e`' is the base of the natural system of logarithms, or approximately 2.718282.

### Parameters

`num`

  The argument to process

### Return Values

'e' raised to the power of `num`

### Examples

Example #1 exp() example

`<?php
echo exp(12), PHP_EOL;
echo exp(5.7);
?>`

The above example will output:

    162754.791419
    298.86740096706

### See Also

- log() - Natural logarithm
- pow() - Exponential expression

# expm1

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

expm1 — Returns `exp($num) - 1`, computed in a way that is accurate even when the value of number is close to zero

### Description

expm1(float `$num`): float

expm1() returns the equivalent to `exp($`num`) - 1` computed in a way that is accurate even if the value of `num` is near zero, a case where `exp($`num`) - 1` would be inaccurate due to subtraction of two numbers that are nearly equal.

### Parameters

`num`

  The argument to process

### Return Values

`e` to the power of `num`, minus one.

### See Also

- log1p() - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
- exp() - Calculates the exponent of e

# fdiv

(PHP 8)

fdiv — Divides two numbers, according to IEEE 754

### Description

fdiv(float `$num1`, float `$num2`): float

Returns the floating point result of dividing the `num1` by the `num2`. If the `num2` is zero, then one of `INF`, -`INF`, or `NAN` will be returned.

Note that in comparisons, `NAN` will never be equal (`==`) or identical (`===`) to any value, including itself.

### Parameters

`num1`

  The dividend (numerator)

`num2`

  The divisor

### Return Values

The floating point result of `num1`/`num2`

### Examples

Example #1 Using fdiv()

`<?php
var_dump(fdiv(5.7, 1.3)); // float(4.384615384615385)
var_dump(fdiv(4, 2)); // float(2)
var_dump(fdiv(1.0, 0.0)); // float(INF)
var_dump(fdiv(-1.0, 0.0)); // float(-INF)
var_dump(fdiv(0.0, 0.0)); // float(NAN)
?>`

### See Also

- Division operator `/`
- intdiv() - Integer division - Integer division
- fmod() - Returns the floating point remainder (modulo) of the division of the arguments
- fpow() - Raise one number to the power of another, according to IEEE 754

# floor

(PHP 4, PHP 5, PHP 7, PHP 8)

floor — Round fractions down

### Description

floor(int|float `$num`): float

Returns the next lowest integer value (as float) by rounding down `num` if necessary.

### Parameters

`num`

  The numeric value to round

### Return Values

`num` rounded to the next lowest integer. The return value of floor() is still of type float.

### Changelog

Version | Description
--- | ---
8.0.0 | `num` no longer accepts internal objects which support numeric conversion.

### Examples

Example #1 floor() example

`<?php
echo floor(4.3), PHP_EOL; // 4
echo floor(9.999), PHP_EOL; // 9
echo floor(-3.14), PHP_EOL; // -4
?>`

### See Also

- ceil() - Round fractions up
- round() - Rounds a float

# fmod

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

### Description

fmod(float `$num1`, float `$num2`): float

Returns the floating point remainder of dividing the dividend (`num1`) by the divisor (`num2`). The remainder (r) is defined as: num1 = i * num2 + r, for some integer i. If `num2` is non-zero, r has the same sign as `num1` and a magnitude less than the magnitude of `num2`.

### Parameters

`num1`

  The dividend

`num2`

  The divisor

### Return Values

The floating point remainder of `num1`/`num2`. `NAN` (float) if the second argument is 0.

### Examples

Example #1 Using fmod()

`<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
var_dump($x, $y, $r);
?>`

### See Also

- `/` - Floating-point division
- `%` - Integer modulus
- intdiv() - Integer division - Integer division

# fpow

(PHP 8 >= 8.4.0)

fpow — Raise one number to the power of another, according to IEEE 754

### Description

fpow(float `$num`, float `$exponent`): float

Returns the floating point result of raising `num` to the power of `exponent`. If `num` is zero and `exponent` is less than zero, then `INF` is returned.

### Parameters

`num`
  The base to use.
`exponent`
  The exponent.

### Return Values

Returns a float corresponding to `$num$exponent`.

### Examples

Example #1 fpow() example

`<?php
var_dump(fpow(10, 2));
var_dump(fpow(0, -3));
var_dump(fpow(-1, 5.5));
?>`

The above example will output:

    float(100)
    float(INF)
    float(NAN)

### See Also

- Exponentiation operator `**`
- pow() - Exponential expression
- fdiv() - Divides two numbers, according to IEEE 754
- fmod() - Returns the floating point remainder (modulo) of the division of the arguments

# hexdec

(PHP 4, PHP 5, PHP 7, PHP 8)

hexdec — Hexadecimal to decimal

### Description

hexdec(string `$hex_string`): int|float

Returns the decimal equivalent of the hexadecimal number represented by the `hex_string` argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters. As of PHP 7.4.0 supplying any invalid characters is deprecated.

### Parameters

`hex_string`

  The hexadecimal string to convert

### Return Values

The decimal representation of `hex_string`

### Changelog

Version | Description
--- | ---
7.4.0 | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.

### Examples

Example #1 hexdec() example

`<?php
var_dump(hexdec("ee")); // prints "int(238)"
var_dump(hexdec("a0")); // prints "int(160)"
?>`

Example #2 hexdec() with Invalid Characters

`<?php
var_dump(hexdec("See")); // print "int(238)"
var_dump(hexdec("that")); // print "int(10)"
?>`

### Notes

> Note:

> The function can convert numbers that are too large to fit into the platforms int type, larger values are returned as float in that case.

### See Also

- dechex() - Decimal to hexadecimal
- bindec() - Binary to decimal
- octdec() - Octal to decimal
- base_convert() - Convert a number between arbitrary bases

# hypot

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

hypot — Calculate the length of the hypotenuse of a right-angle triangle

### Description

hypot(float `$x`, float `$y`): float

hypot() returns the length of the hypotenuse of a right-angle triangle with sides of length `x` and `y`, or the distance of the point (`x`, `y`) from the origin. This is equivalent to `sqrt($x*$x + $y*$y)`.

### Parameters

`x`

  Length of first side

`y`

  Length of second side

### Return Values

Calculated length of the hypotenuse

# intdiv

(PHP 7, PHP 8)

intdiv — Integer division

### Description

intdiv(int `$num1`, int `$num2`): int

Returns the integer quotient of the division of `num1` by `num2`.

### Parameters

`num1`

  Number to be divided.

`num2`

  Number which divides the `num1`.

### Return Values

The integer quotient of the division of `num1` by `num2`.

### Errors/Exceptions

If `num2` is `0`, a DivisionByZeroError exception is thrown. If the `num1` is `PHP_INT_MIN` and the `num2` is `-1`, then an ArithmeticError exception is thrown.

### Examples

Example #1 intdiv() example

`<?php
var_dump(intdiv(3, 2));
var_dump(intdiv(-3, 2));
var_dump(intdiv(3, -2));
var_dump(intdiv(-3, -2));
var_dump(intdiv(PHP_INT_MAX, PHP_INT_MAX));
var_dump(intdiv(PHP_INT_MIN, PHP_INT_MIN));
?>`

The above example will output:

    int(1)
    int(-1)
    int(-1)
    int(1)
    int(1)
    int(1)

Example #2 intdiv() Example With Invalid Divisor

`<?php
try {
intdiv(PHP_INT_MIN, -1);
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), PHP_EOL;
}
try {
intdiv(1, 0);
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), PHP_EOL;
}
?>`

The above example will output:

    ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer
    DivisionByZeroError: Division by zero

### See Also

- `/` - Floating-point division
- `%` - Integer modulus
- fmod() - Returns the floating point remainder (modulo) of the division of the arguments - Floating-point modulo

# is_finite

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_finite — Checks whether a float is finite

### Description

is_finite(float `$num`): bool

Returns whether the given `num` is a finite float.

A finite float is neither `NAN` (is_nan()), nor infinite (is_infinite()).

### Parameters

`num`

  The float to check

### Return Values

`true` if `num` is none of `NAN`, `INF`, -`INF`, else `false`.

### Examples

Example #1 is_finite() example

`<?php
$float = 1.2345;
var_dump($float, is_finite($float));
$nan = sqrt(-1);
var_dump($nan, is_finite($nan));
$inf = 1e308 * 2;
var_dump($inf, is_finite($inf));
?>`

The above example will output:

    float(1.2345)
    bool(true)
    float(NAN)
    bool(false)
    float(INF)
    bool(false)

### See Also

- is_infinite() - Checks whether a float is infinite
- is_nan() - Checks whether a float is NAN

# is_infinite

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_infinite — Checks whether a float is infinite

### Description

is_infinite(float `$num`): bool

Returns whether the given `num` is either `INF` or -`INF`.

### Parameters

`num`

  The float to check

### Return Values

`true` if `num` is either `INF` or -`INF`, else `false`.

### Examples

Example #1 is_infinite() example

`<?php
$inf = 1e308 * 2;
var_dump($inf, is_infinite($inf));
$negative_inf = -$inf;
var_dump($negative_inf, is_infinite($negative_inf));
?>`

The above example will output:

    float(INF)
    bool(true)
    float(-INF)
    bool(true)

### See Also

- is_finite() - Checks whether a float is finite
- is_nan() - Checks whether a float is NAN

# is_nan

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_nan — Checks whether a float is NAN

### Description

is_nan(float `$num`): bool

Returns whether the given `num` is `NAN` (Not A Number).

`NAN` is returned from mathematical operations that are undefined, for example when passing parameters outside of function’s input domain. The square root (sqrt()) is only defined for positive numbers, passing a negative number will result in `NAN`. Other examples of operations returning `NAN` are dividing `INF` by `INF` and any operation involving an existing `NAN` value.

> Note:

> Despite its name of Not A Number, `NAN` is a valid value of type float.

Caution

`NAN` does not compare equal to `NAN`. To check whether a float is `NAN`, is_nan() must be used. Checking `$float === NAN` will not work.

### Parameters

`num`

  The float to check

### Return Values

`true` if `num` is `NAN`, else `false`.

### Examples

Example #1 is_nan() example

`<?php
$nan = sqrt(-1);
var_dump($nan, is_nan($nan));
?>`

The above example will output:

    float(NAN)
    bool(true)

### See Also

- is_finite() - Checks whether a float is finite
- is_infinite() - Checks whether a float is infinite

# log

(PHP 4, PHP 5, PHP 7, PHP 8)

log — Natural logarithm

### Description

log(float `$num`, float `$base` = `M_E`): float

If the optional `base` parameter is specified, log() returns logbase `num`, otherwise log() returns the natural logarithm of `num`.

### Parameters

`num`

  The value to calculate the logarithm for

`base`

  The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm).

### Return Values

The logarithm of `num` to `base`, if given, or the natural logarithm.

### See Also

- log10() - Base-10 logarithm
- exp() - Calculates the exponent of e
- pow() - Exponential expression
- error_log() - Send an error message to the defined error handling routines

# log10

(PHP 4, PHP 5, PHP 7, PHP 8)

log10 — Base-10 logarithm

### Description

log10(float `$num`): float

Returns the base-10 logarithm of `num`.

### Parameters

`num`

  The argument to process

### Return Values

The base-10 logarithm of `num`

### See Also

- log() - Natural logarithm

# log1p

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

### Description

log1p(float `$num`): float

log1p() returns log(1 + `num`) computed in a way that is accurate even when the value of `num` is close to zero. log() might only return log(1) in this case due to lack of precision.

### Parameters

`num`

  The argument to process

### Return Values

log(1 + `num`)

### See Also

- expm1() - Returns exp($num) - 1, computed in a way that is accurate even when the value of number is close to zero
- log() - Natural logarithm
- log10() - Base-10 logarithm

# max

(PHP 4, PHP 5, PHP 7, PHP 8)

max — Find highest value

### Description

max(mixed `$value`, mixed `...$values`): mixed

Alternative signature (not supported with named arguments):

max(array `$value_array`): mixed

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.

> Note:

> Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an int as though it were `0`, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Caution

Be careful when passing arguments of different types because max() can produce unpredictable results.

### Parameters

`value`

  Any comparable value.

`values`

  Any comparable values.

`value_array`

  An array containing the values.

### Return Values

max() returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. `0` and `'abc'`) the first provided to the function will be returned.

### Errors/Exceptions

If an empty array is passed, max() throws a ValueError.

### Changelog

Version | Description
--- | ---
8.0.0 | max() throws a ValueError on failure now; previously, `false` was returned and an `E_WARNING` error was emitted.
8.0.0 | As string to number comparisons were changed, max() no longer returns a different value based on the argument order in those cases.

### Examples

Example #1 Example uses of max()

`<?php
echo max(2, 3, 1, 6, 7), PHP_EOL; // 7
echo max(array(2, 4, 5)), PHP_EOL; // 5
// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1), PHP_EOL; // hello
// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)
var_dump($val);
// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)
var_dump($val);
// If both an array and non-array are given, the array will be returned
// as comparisons treat arrays as greater than any other value
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
var_dump($val);
// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison
$val = max(-10, FALSE); // -10
var_dump($val);
// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
var_dump($val);
?>`

### See Also

- min() - Find lowest value
- count() - Counts all elements in an array or in a Countable object

# min

(PHP 4, PHP 5, PHP 7, PHP 8)

min — Find lowest value

### Description

min(mixed `$value`, mixed `...$values`): mixed

Alternative signature (not supported with named arguments):

min(array `$value_array`): mixed

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

> Note:

> Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an int as though it were `0`, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Caution

Be careful when passing arguments of different types because min() can produce unpredictable results.

### Parameters

`value`

  Any comparable value.

`values`

  Any comparable values.

`value_array`

  An array containing the values.

### Return Values

min() returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. `0` and `'abc'`) the first provided to the function will be returned.

### Errors/Exceptions

If an empty array is passed, min() throws a ValueError.

### Changelog

Version | Description
--- | ---
8.0.0 | min() throws a ValueError on failure now; previously, `false` was returned and an `E_WARNING` error was emitted.
8.0.0 | As string to number comparisons were changed, min() no longer returns a different value based on the argument order in those cases.

### Examples

Example #1 Example uses of min()

`<?php
echo min(2, 3, 1, 6, 7), PHP_EOL; // 1
echo min(array(2, 4, 5)), PHP_EOL; // 2
// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1), PHP_EOL; // -1
// With multiple arrays of different lengths, min returns the shortest
$val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2)
var_dump($val);
// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
var_dump($val);
// If both an array and non-array are given, the array is never returned
// as comparisons treat arrays as greater than any other value
$val = min('string', array(2, 5, 7), 42); // string
var_dump($val);
// If one argument is NULL or a boolean, it will be compared against
// other values using the rules FALSE < TRUE and NULL == FALSE regardless of the
// other types involved
// In the below examples, both -10 and 10 are treated as TRUE in the comparison
$val = min(-10, FALSE, 10); // FALSE
var_dump($val);
$val = min(-10, NULL, 10); // NULL
var_dump($val);
// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = min(0, TRUE); // 0
var_dump($val);
?>`

### See Also

- max() - Find highest value
- count() - Counts all elements in an array or in a Countable object

# octdec

(PHP 4, PHP 5, PHP 7, PHP 8)

octdec — Octal to decimal

### Description

octdec(string `$octal_string`): int|float

Returns the decimal equivalent of the octal number represented by the `octal_string` argument.

### Parameters

`octal_string`

  The octal string to convert. Any invalid characters in `octal_string` are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.

### Return Values

The decimal representation of `octal_string`

### Changelog

Version | Description
--- | ---
7.4.0 | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.

### Examples

Example #1 octdec() example

`<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>`

The above example will output:

    63
    45

### Notes

> Note:

> The function can convert numbers that are too large to fit into the platforms int type, larger values are returned as float in that case.

### See Also

- decoct() - Decimal to octal
- bindec() - Binary to decimal
- hexdec() - Hexadecimal to decimal
- base_convert() - Convert a number between arbitrary bases

# pi

(PHP 4, PHP 5, PHP 7, PHP 8)

pi — Get value of pi

### Description

pi(): float

Returns an approximation of pi. Also, you can use the `M_PI` constant which yields identical results to pi().

### Parameters

This function has no parameters.

### Return Values

The value of pi as float.

### Examples

Example #1 pi() example

`<?php
echo pi(), PHP_EOL; // 3.1415926535898
echo M_PI, PHP_EOL; // 3.1415926535898
?>`

# pow

(PHP 4, PHP 5, PHP 7, PHP 8)

pow — Exponential expression

### Description

pow(mixed `$num`, mixed `$exponent`): int|float|object

Returns `num` raised to the power of `exponent`.

> Note:

> It is possible to use the ** operator instead.

### Parameters

`num`

  The base to use

`exponent`

  The exponent

### Return Values

`num` raised to the power of `exponent`. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with int type, otherwise it will be returned as a float.

PHP-Extensions may override the behaviour of this operation and make it return an object.

### Changelog

Version | Description
--- | ---
8.4.0 | Raising `0` to a negative `exponent` is now deprecated.

### Examples

Example #1 Some examples of pow()

`<?php
var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20), PHP_EOL; // 1
echo pow(0, 0), PHP_EOL; // 1
echo pow(10, -1), PHP_EOL; // 0.1
echo pow(-1, 5.5), PHP_EOL; // NAN
?>`

Example #2 Examples of pow() With GMP Extension Object

`<?php
var_dump(pow(new GMP("3"), new GMP("2"))); // object(GMP)
?>`

### Notes

> Note:

> This function will convert all input to a number, even non-scalar values, which could lead to weird results.

### See Also

- Exponentiation operator `**`
- fpow() - Raise one number to the power of another, according to IEEE 754
- exp() - Calculates the exponent of e
- sqrt() - Square root
- bcpow() - Raise an arbitrary precision number to another
- gmp_pow() - Raise number into power

# rad2deg

(PHP 4, PHP 5, PHP 7, PHP 8)

rad2deg — Converts the radian number to the equivalent number in degrees

### Description

rad2deg(float `$num`): float

This function converts `num` from radian to degrees.

### Parameters

`num`

  A radian value

### Return Values

The equivalent of `num` in degrees

### Examples

Example #1 rad2deg() example

`<?php
echo rad2deg(M_PI_4); // 45
?>`

### See Also

- deg2rad() - Converts the number in degrees to the radian equivalent

# round

(PHP 4, PHP 5, PHP 7, PHP 8)

round — Rounds a float

### Description

round(int|float `$num`, int `$precision` = 0, int|RoundingMode `$mode` = `RoundingMode::HalfAwayFromZero`): float

Returns the rounded value of `num` to specified `precision` (number of digits after the decimal point). `precision` can also be negative or zero (default).

### Parameters

`num`

  The value to round.

`precision`

  The optional number of decimal digits to round to.

  If the `precision` is positive, `num` is rounded to `precision` significant digits after the decimal point.

  If the `precision` is negative, `num` is rounded to `precision` significant digits before the decimal point, i.e. to the nearest multiple of `pow(10, -$precision)`, e.g. for a `precision` of -1 `num` is rounded to tens, for a `precision` of -2 to hundreds, etc.

`mode`

  Use RoundingMode or one of the following constants to specify the mode in which rounding occurs.

  Constants | Description
  --- | ---
  `PHP_ROUND_HALF_UP` | Rounds `num` away from zero when it is half way there, making 1.5 into 2 and -1.5 into -2.
  `PHP_ROUND_HALF_DOWN` | Rounds `num` towards zero when it is half way there, making 1.5 into 1 and -1.5 into -1.
  `PHP_ROUND_HALF_EVEN` | Rounds `num` towards the nearest even value when it is half way there, making both 1.5 and 2.5 into 2.
  `PHP_ROUND_HALF_ODD` | Rounds `num` towards the nearest odd value when it is half way there, making 1.5 into 1 and 2.5 into 3.

  However, please note that some newly added modes only exist in RoundingMode.

### Return Values

The value rounded to the given `precision` as a float.

### Errors/Exceptions

The function throws a ValueError if `mode` is invalid. Prior to PHP 8.4.0, an invalid mode would silently default to `PHP_ROUND_HALF_UP`.

### Changelog

Version | Description
--- | ---
8.4.0 | Four new rounding modes have been added.
8.4.0 | Now throws a ValueError if `mode` is invalid.
8.0.0 | `num` no longer accepts internal objects which support numeric conversion.

### Examples

Example #1 round() examples

`<?php
var_dump(round(3.4));
var_dump(round(3.5));
var_dump(round(3.6));
var_dump(round(3.6, 0));
var_dump(round(5.045, 2));
var_dump(round(5.055, 2));
var_dump(round(345, -2));
var_dump(round(345, -3));
var_dump(round(678, -2));
var_dump(round(678, -3));
?>`

The above example will output:

    float(3)
    float(4)
    float(4)
    float(4)
    float(5.05)
    float(5.06)
    float(300)
    float(0)
    float(700)
    float(1000)

Example #2 How `precision` affects a float

`<?php
$number = 135.79;
var_dump(round($number, 3));
var_dump(round($number, 2));
var_dump(round($number, 1));
var_dump(round($number, 0));
var_dump(round($number, -1));
var_dump(round($number, -2));
var_dump(round($number, -3));
?>`

The above example will output:

    float(135.79)
    float(135.79)
    float(135.8)
    float(136)
    float(140)
    float(100)
    float(0)

Example #3 `mode` examples

`<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
var_dump(round(9.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(9.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_ODD));
echo PHP_EOL;
echo 'Rounding modes with 8.5' . PHP_EOL;
var_dump(round(8.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(8.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_ODD));
?>`

The above example will output:

    Rounding modes with 9.5
    float(10)
    float(9)
    float(10)
    float(9)

    Rounding modes with 8.5
    float(9)
    float(8)
    float(8)
    float(9)

Example #4 `mode` with `precision` examples

`<?php
echo 'Using PHP_ROUND_HALF_UP with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_UP));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_DOWN));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_EVEN));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_ODD with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_ODD));
?>`

The above example will output:

    Using PHP_ROUND_HALF_UP with 1 decimal digit precision
    float(1.6)
    float(-1.6)

    Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
    float(1.5)
    float(-1.5)

    Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
    float(1.6)
    float(-1.6)

    Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
    float(1.5)
    float(-1.5)

Example #5 Example of using RoundingMode

`<?php
foreach (RoundingMode::cases() as $mode) {
foreach ([
8.5,
9.5,
-3.5,
] as $number) {
printf("%-17s: %+.17g -> %+.17g\n", $mode->name, $number, round($number, 0, $mode));
}
echo "\n";
}
?>`

The above example will output:

    HalfAwayFromZero : +8.5 -> +9
    HalfAwayFromZero : +9.5 -> +10
    HalfAwayFromZero : -3.5 -> -4

    HalfTowardsZero  : +8.5 -> +8
    HalfTowardsZero  : +9.5 -> +9
    HalfTowardsZero  : -3.5 -> -3

    HalfEven         : +8.5 -> +8
    HalfEven         : +9.5 -> +10
    HalfEven         : -3.5 -> -4

    HalfOdd          : +8.5 -> +9
    HalfOdd          : +9.5 -> +9
    HalfOdd          : -3.5 -> -3

    TowardsZero      : +8.5 -> +8
    TowardsZero      : +9.5 -> +9
    TowardsZero      : -3.5 -> -3

    AwayFromZero     : +8.5 -> +9
    AwayFromZero     : +9.5 -> +10
    AwayFromZero     : -3.5 -> -4

    NegativeInfinity : +8.5 -> +8
    NegativeInfinity : +9.5 -> +9
    NegativeInfinity : -3.5 -> -4

    PositiveInfinity : +8.5 -> +9
    PositiveInfinity : +9.5 -> +10
    PositiveInfinity : -3.5 -> -3

### See Also

- ceil() - Round fractions up
- floor() - Round fractions down
- number_format() - Format a number with grouped thousands

# sin

(PHP 4, PHP 5, PHP 7, PHP 8)

sin — Sine

### Description

sin(float `$num`): float

sin() returns the sine of the `num` parameter. The `num` parameter is in radians.

### Parameters

`num`

  A value in radians

### Return Values

The sine of `num`

### Examples

Example #1 sin() example

`<?php
// Precision depends on your precision directive
echo sin(deg2rad(60)), PHP_EOL; // 0.866025403 ...
echo sin(60), PHP_EOL; // -0.304810621 ...
?>`

### See Also

- asin() - Arc sine
- sinh() - Hyperbolic sine
- cos() - Cosine
- tan() - Tangent
- deg2rad() - Converts the number in degrees to the radian equivalent

# sinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

sinh — Hyperbolic sine

### Description

sinh(float `$num`): float

Returns the hyperbolic sine of `num`, defined as `(exp($num) - exp(-$num))/2`.

### Parameters

`num`

  The argument to process

### Return Values

The hyperbolic sine of `num`

### See Also

- sin() - Sine
- asinh() - Inverse hyperbolic sine
- cosh() - Hyperbolic cosine
- tanh() - Hyperbolic tangent

# sqrt

(PHP 4, PHP 5, PHP 7, PHP 8)

sqrt — Square root

### Description

sqrt(float `$num`): float

Returns the square root of `num`.

### Parameters

`num`

  The argument to process

### Return Values

The square root of `num` or the special value `NAN` for negative numbers.

### Examples

Example #1 sqrt() example

`<?php
// Precision depends on your precision directive
echo sqrt(9), PHP_EOL; // 3
echo sqrt(10), PHP_EOL; // 3.16227766 ...
?>`

### See Also

- pow() - Exponential expression
- `M_SQRTPI` - `sqrt(pi)`
- `M_2_SQRTPI` - `2/sqrt(pi)`
- `M_SQRT2` - `sqrt(2)`
- `M_SQRT3` - `sqrt(3)`
- `M_SQRT1_2` - `1/sqrt(2)`

# tan

(PHP 4, PHP 5, PHP 7, PHP 8)

tan — Tangent

### Description

tan(float `$num`): float

tan() returns the tangent of the `num` parameter. The `num` parameter is in radians.

### Parameters

`num`

  The argument to process in radians

### Return Values

The tangent of `num`

### Examples

Example #1 tan() example

`<?php
echo tan(M_PI_4); // 1
?>`

### See Also

- atan() - Arc tangent
- atan2() - Arc tangent of two variables
- sin() - Sine
- cos() - Cosine
- tanh() - Hyperbolic tangent
- deg2rad() - Converts the number in degrees to the radian equivalent

# tanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

tanh — Hyperbolic tangent

### Description

tanh(float `$num`): float

Returns the hyperbolic tangent of `num`, defined as `sinh($num)/cosh($num)`.

### Parameters

`num`

  The argument to process

### Return Values

The hyperbolic tangent of `num`

### See Also

- tan() - Tangent
- atanh() - Inverse hyperbolic tangent
- sinh() - Hyperbolic sine
- cosh() - Hyperbolic cosine

## Table of Contents

- abs — Absolute value
- acos — Arc cosine
- acosh — Inverse hyperbolic cosine
- asin — Arc sine
- asinh — Inverse hyperbolic sine
- atan — Arc tangent
- atan2 — Arc tangent of two variables
- atanh — Inverse hyperbolic tangent
- base_convert — Convert a number between arbitrary bases
- bindec — Binary to decimal
- ceil — Round fractions up
- cos — Cosine
- cosh — Hyperbolic cosine
- decbin — Decimal to binary
- dechex — Decimal to hexadecimal
- decoct — Decimal to octal
- deg2rad — Converts the number in degrees to the radian equivalent
- exp — Calculates the exponent of e
- expm1 — Returns exp($num) - 1, computed in a way that is accurate even when the value of number is close to zero
- fdiv — Divides two numbers, according to IEEE 754
- floor — Round fractions down
- fmod — Returns the floating point remainder (modulo) of the division of the arguments
- fpow — Raise one number to the power of another, according to IEEE 754
- hexdec — Hexadecimal to decimal
- hypot — Calculate the length of the hypotenuse of a right-angle triangle
- intdiv — Integer division
- is_finite — Checks whether a float is finite
- is_infinite — Checks whether a float is infinite
- is_nan — Checks whether a float is NAN
- log — Natural logarithm
- log10 — Base-10 logarithm
- log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
- max — Find highest value
- min — Find lowest value
- octdec — Octal to decimal
- pi — Get value of pi
- pow — Exponential expression
- rad2deg — Converts the radian number to the equivalent number in degrees
- round — Rounds a float
- sin — Sine
- sinh — Hyperbolic sine
- sqrt — Square root
- tan — Tangent
- tanh — Hyperbolic tangent

- Predefined Constants
- RoundingMode — The RoundingMode Enum
- Math Functions
  - abs — Absolute value
  - acos — Arc cosine
  - acosh — Inverse hyperbolic cosine
  - asin — Arc sine
  - asinh — Inverse hyperbolic sine
  - atan — Arc tangent
  - atan2 — Arc tangent of two variables
  - atanh — Inverse hyperbolic tangent
  - base_convert — Convert a number between arbitrary bases
  - bindec — Binary to decimal
  - ceil — Round fractions up
  - cos — Cosine
  - cosh — Hyperbolic cosine
  - decbin — Decimal to binary
  - dechex — Decimal to hexadecimal
  - decoct — Decimal to octal
  - deg2rad — Converts the number in degrees to the radian equivalent
  - exp — Calculates the exponent of e
  - expm1 — Returns exp($num) - 1, computed in a way that is accurate even when the value of number is close to zero
  - fdiv — Divides two numbers, according to IEEE 754
  - floor — Round fractions down
  - fmod — Returns the floating point remainder (modulo) of the division of the arguments
  - fpow — Raise one number to the power of another, according to IEEE 754
  - hexdec — Hexadecimal to decimal
  - hypot — Calculate the length of the hypotenuse of a right-angle triangle
  - intdiv — Integer division
  - is_finite — Checks whether a float is finite
  - is_infinite — Checks whether a float is infinite
  - is_nan — Checks whether a float is NAN
  - log — Natural logarithm
  - log10 — Base-10 logarithm
  - log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  - max — Find highest value
  - min — Find lowest value
  - octdec — Octal to decimal
  - pi — Get value of pi
  - pow — Exponential expression
  - rad2deg — Converts the radian number to the equivalent number in degrees
  - round — Rounds a float
  - sin — Sine
  - sinh — Hyperbolic sine
  - sqrt — Square root
  - tan — Tangent
  - tanh — Hyperbolic tangent

# Statistics

# Introduction

Warning

This extension is unmaintained.

This is the statistics extension. It contains few dozens of functions useful for statistical computations. It is a wrapper around 2 scientific libraries, namely DCDFLIB (Library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters) by B. Brown & J. Lavato and RANDLIB by Barry Brown, James Lavato & Kathy Russell. Includes CD and PD functions.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

No external libraries are needed. The extension comes bundled with the libraries used.

## Installation

This » PECL extension is not bundled with PHP.

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » https://pecl.php.net/package/stats.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

# Statistic Functions

# stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

### Description

stats_absolute_deviation(array `$a`): float

Returns the absolute deviation of the values in `a`.

### Parameters

`a`

  The input array

### Return Values

Returns the absolute deviation of the values in `a`, or `false` if `a` is empty or is not an array.

# stats_cdf_beta

(PECL stats >= 1.0.0)

stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others

### Description

stats_cdf_beta(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the beta distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, alpha, and beta denotes cumulative distribution function, the value of the random variable, and shape parameters of the beta distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | alpha | beta
2 | x | CDF | alpha | beta
3 | alpha | x | CDF | beta
4 | beta | x | CDF | alpha

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, alpha, or beta, determined by `which`.

# stats_cdf_binomial

(PECL stats >= 1.0.0)

stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others

### Description

stats_cdf_binomial(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the binomial distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, n, and p denotes cumulative distribution function, the number of successes, the number of trials, and the success rate for each trial, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | n | p
2 | x | CDF | n | p
3 | n | x | CDF | p
4 | p | x | CDF | n

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, n, or p, determined by `which`.

# stats_cdf_cauchy

(PECL stats >= 1.0.0)

stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others

### Description

stats_cdf_cauchy(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Cauchy distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, x0, and gamma denotes cumulative distribution function, the value of the random variable, the location and the scale parameter of the Cauchy distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | x0 | gamma
2 | x | CDF | x0 | gamma
3 | x0 | x | CDF | gamma
4 | gamma | x | CDF | x0

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, x0, or gamma, determined by `which`.

# stats_cdf_chisquare

(PECL stats >= 1.0.0)

stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others

### Description

stats_cdf_chisquare(float `$par1`, float `$par2`, int `$which`): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the chi-square distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, and k denotes cumulative distribution function, the value of the random variable, and the degree of freedom of the chi-square distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2`
--- | --- | --- | ---
1 | CDF | x | k
2 | x | CDF | k
3 | k | x | CDF

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, or k, determined by `which`.

# stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others

### Description

stats_cdf_exponential(float `$par1`, float `$par2`, int `$which`): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the exponential distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, and lambda denotes cumulative distribution function, the value of the random variable, and the rate parameter of the exponential distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2`
--- | --- | --- | ---
1 | CDF | x | lambda
2 | x | CDF | lambda
3 | lambda | x | CDF

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, or lambda, determined by `which`.

# stats_cdf_f

(PECL stats >= 1.0.0)

stats_cdf_f — Calculates any one parameter of the F distribution given values for the others

### Description

stats_cdf_f(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the F distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, d1, and d2 denotes cumulative distribution function, the value of the random variable, and the degree of freedoms of the F distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | d1 | d2
2 | x | CDF | d1 | d2
3 | d1 | x | CDF | d2
4 | d2 | x | CDF | d1

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, d1, or d2, determined by `which`.

# stats_cdf_gamma

(PECL stats >= 1.0.0)

stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others

### Description

stats_cdf_gamma(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the gamma distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, k, and theta denotes cumulative distribution function, the value of the random variable, and the shape and the scale parameter of the gamma distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | k | theta
2 | x | CDF | k | theta
3 | k | x | CDF | theta
4 | theta | x | CDF | k

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, k, or theta, determined by `which`.

# stats_cdf_laplace

(PECL stats >= 1.0.0)

stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others

### Description

stats_cdf_laplace(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Laplace distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, mu, and b denotes cumulative distribution function, the value of the random variable, and the location and the scale parameter of the Laplace distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | mu | b
2 | x | CDF | mu | b
3 | mu | x | CDF | b
4 | b | x | CDF | mu

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, mu, or b, determined by `which`.

# stats_cdf_logistic

(PECL stats >= 1.0.0)

stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others

### Description

stats_cdf_logistic(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the logistic distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, mu, and s denotes cumulative distribution function, the value of the random variable, and the location and the scale parameter of the logistic distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | mu | s
2 | x | CDF | mu | s
3 | mu | x | CDF | s
4 | s | x | CDF | mu

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, mu, or s, determined by `which`.

# stats_cdf_negative_binomial

(PECL stats >= 1.0.0)

stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others

### Description

stats_cdf_negative_binomial(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the negative binomial distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, r, and p denotes cumulative distribution function, the number of failure, the number of success, and the success rate for each trial, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | r | p
2 | x | CDF | r | p
3 | r | x | CDF | p
4 | p | x | CDF | r

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, r, or p, determined by `which`.

# stats_cdf_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others

### Description

stats_cdf_noncentral_chisquare(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central chi-square distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, k, and lambda denotes cumulative distribution function, the value of the random variable, the degree of freedom and the non-centrality parameter of the distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | k | lambda
2 | x | CDF | k | lambda
3 | k | x | CDF | lambda
4 | lambda | x | CDF | k

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, k, or lambda, determined by `which`.

# stats_cdf_noncentral_f

(PECL stats >= 1.0.0)

stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others

### Description

stats_cdf_noncentral_f(
float `$par1`,
float `$par2`,
float `$par3`,
float `$par4`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central F distribution. The kind of the return value and parameters (`par1`, `par2`, `par3`, and `par4`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, nu1, nu2, and lambda denotes cumulative distribution function, the value of the random variable, the degree of freedoms and the non-centrality parameter of the distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3` | `par4`
--- | --- | --- | --- | --- | ---
1 | CDF | x | nu1 | nu2 | lambda
2 | x | CDF | nu1 | nu2 | lambda
3 | nu1 | x | CDF | nu2 | lambda
4 | nu2 | x | CDF | nu1 | lambda
5 | lambda | x | CDF | nu1 | nu2

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`par4`

  The fourth parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, nu1, nu2, or lambda, determined by `which`.

# stats_cdf_noncentral_t

(PECL stats >= 1.0.0)

stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others

### Description

stats_cdf_noncentral_t(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central t-distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, nu, and mu denotes cumulative distribution function, the value of the random variable, the degrees of freedom and the non-centrality parameter of the distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | nu | mu
2 | x | CDF | nu | mu
3 | nu | x | CDF | mu
4 | mu | x | CDF | nu

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, nu, or mu, determined by `which`.

# stats_cdf_normal

(PECL stats >= 1.0.0)

stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others

### Description

stats_cdf_normal(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the normal distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, mu, and sigma denotes cumulative distribution function, the value of the random variable, the mean and the standard deviation of the normal distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | mu | sigma
2 | x | CDF | mu | sigma
3 | mu | x | CDF | sigma
4 | sigma | x | CDF | mu

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, mu, or sigma, determined by `which`.

# stats_cdf_poisson

(PECL stats >= 1.0.0)

stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others

### Description

stats_cdf_poisson(float `$par1`, float `$par2`, int `$which`): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Poisson distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, and lambda denotes cumulative distribution function, the value of the random variable, and the parameter of the Poisson distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2`
--- | --- | --- | ---
1 | CDF | x | lambda
2 | x | CDF | lambda
3 | lambda | x | CDF

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, or lambda, determined by `which`.

# stats_cdf_t

(PECL stats >= 1.0.0)

stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others

### Description

stats_cdf_t(float `$par1`, float `$par2`, int `$which`): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the t-distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, and nu denotes cumulative distribution function, the value of the random variable, and the degrees of freedom of the t-distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2`
--- | --- | --- | ---
1 | CDF | x | nu
2 | x | CDF | nu
3 | nu | x | CDF

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, or nu, determined by `which`.

# stats_cdf_uniform

(PECL stats >= 1.0.0)

stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others

### Description

stats_cdf_uniform(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the uniform distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, a, and b denotes cumulative distribution function, the value of the random variable, the lower bound and the higher bound of the uniform distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | a | b
2 | x | CDF | a | b
3 | a | x | CDF | b
4 | b | x | CDF | a

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, a, or b, determined by `which`.

# stats_cdf_weibull

(PECL stats >= 1.0.0)

stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others

### Description

stats_cdf_weibull(
float `$par1`,
float `$par2`,
float `$par3`,
int `$which`
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Weibull distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.

The following table lists the return value and parameters by `which`. CDF, x, k, and lambda denotes cumulative distribution function, the value of the random variable, the shape and the scale parameter of the Weibull distribution, respectively.

Return value and parameters
`which` | Return value | `par1` | `par2` | `par3`
--- | --- | --- | --- | ---
1 | CDF | x | k | lambda
2 | x | CDF | k | lambda
3 | k | x | CDF | lambda
4 | lambda | x | CDF | k

### Parameters

`par1`

  The first parameter

`par2`

  The second parameter

`par3`

  The third parameter

`which`

  The flag to determine what to be calculated

### Return Values

Returns CDF, x, k, or lambda, determined by `which`.

# stats_covariance

(PECL stats >= 1.0.0)

stats_covariance — Computes the covariance of two data sets

### Description

stats_covariance(array `$a`, array `$b`): float

Returns the covariance of `a` and `b`.

### Parameters

`a`

  The first array

`b`

  The second array

### Return Values

Returns the covariance of `a` and `b`, or `false` on failure.

# stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Probability density function of the beta distribution

### Description

stats_dens_beta(float `$x`, float `$a`, float `$b`): float

Returns the probability density at `x`, where the random variable follows the beta distribution of which the shape parameters are `a` and `b`.

### Parameters

`x`

  The value at which the probability density is calculated

`a`

  The shape parameter of the distribution

`b`

  The shape parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Probability density function of the Cauchy distribution

### Description

stats_dens_cauchy(float `$x`, float `$ave`, float `$stdev`): float

Returns the probability density at `x`, where the random variable follows the Cauchy distribution whose location and scale are `ave` and `stdev`, respectively.

### Parameters

`x`

  The value at which the probability density is calculated

`ave`

  The location parameter of the distribution

`stdev`

  The scale parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Probability density function of the chi-square distribution

### Description

stats_dens_chisquare(float `$x`, float `$dfr`): float

Returns the probability density at `x`, where the random variable follows the chi-square distribution of which the degree of freedom is `dfr`.

### Parameters

`x`

  The value at which the probability density is calculated

`dfr`

  The degree of freedom of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Probability density function of the exponential distribution

### Description

stats_dens_exponential(float `$x`, float `$scale`): float

Returns the probability density at `x`, where the random variable follows the exponential distribution of which the scale is `scale`.

### Parameters

`x`

  The value at which the probability density is calculated

`scale`

  The scale of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f — Probability density function of the F distribution

### Description

stats_dens_f(float `$x`, float `$dfr1`, float `$dfr2`): float

Returns the probability density at `x`, where the random variable follows the F distribution of which the degree of freedoms are `dfr1` and `dfr2`.

### Parameters

`x`

  The value at which the probability density is calculated

`dfr1`

  The degree of freedom of the distribution

`dfr2`

  The degree of freedom of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Probability density function of the gamma distribution

### Description

stats_dens_gamma(float `$x`, float `$shape`, float `$scale`): float

Returns the probability density at `x`, where the random variable follows the gamma distribution of which the shape parameter is `shape` and the scale parameter is `scale`.

### Parameters

`x`

  The value at which the probability density is calculated

`shape`

  The shape parameter of the distribution

`scale`

  The scale parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Probability density function of the Laplace distribution

### Description

stats_dens_laplace(float `$x`, float `$ave`, float `$stdev`): float

Returns the probability density at `x`, where the random variable follows the Laplace distribution of which the location parameter is `ave` and the scale parameter is `stdev`.

### Parameters

`x`

  The value at which the probability density is calculated

`ave`

  The location parameter of the distribution

`stdev`

  The shape parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Probability density function of the logistic distribution

### Description

stats_dens_logistic(float `$x`, float `$ave`, float `$stdev`): float

Returns the probability density at `x`, where the random variable follows the logistic distribution of which the location parameter is `ave` and the scale parameter is `stdev`.

### Parameters

`x`

  The value at which the probability density is calculated

`ave`

  The location parameter of the distribution

`stdev`

  The shape parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Probability density function of the normal distribution

### Description

stats_dens_normal(float `$x`, float `$ave`, float `$stdev`): float

Returns the probability density at `x`, where the random variable follows the normal distribution of which the mean is `ave` and the standard deviation is `stdev`.

### Parameters

`x`

  The value at which the probability density is calculated

`ave`

  The mean of the distribution

`stdev`

  The standard deviation of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_binomial — Probability mass function of the binomial distribution

### Description

stats_dens_pmf_binomial(float `$x`, float `$n`, float `$pi`): float

Returns the probability mass at `x`, where the random variable follows the binomial distribution of which the number of trials is `n` and the success rate is `pi`.

### Parameters

`x`

  The value at which the probability mass is calculated

`n`

  The number of trials of the distribution

`pi`

  The success rate of the distribution

### Return Values

The probability mass at `x` or `false` for failure.

# stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution

### Description

stats_dens_pmf_hypergeometric(
float `$n1`,
float `$n2`,
float `$N1`,
float `$N2`
): float

Returns the probability mass at `n1`, where the random variable follows the hypergeometric distribution of which the number of failure is `n2`, the number of success samples is `N1`, and the number of failure samples is `N2`.

### Parameters

`n1`

  The number of success, at which the probability mass is calculated

`n2`

  The number of failure of the distribution

`N1`

  The number of success samples of the distribution

`N2`

  The number of failure samples of the distribution

### Return Values

The probability mass at `n1` or `false` for failure.

# stats_dens_pmf_negative_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution

### Description

stats_dens_pmf_negative_binomial(float `$x`, float `$n`, float `$pi`): float

Returns the probability mass at `x`, where the random variable follows the negative binomial distribution of which the number of the success is `n` and the success rate is `pi`.

### Parameters

`x`

  The value at which the probability mass is calculated

`n`

  The number of the success of the distribution

`pi`

  The success rate of the distribution

### Return Values

The probability mass at `x` or `false` for failure.

# stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Probability mass function of the Poisson distribution

### Description

stats_dens_pmf_poisson(float `$x`, float `$lb`): float

Returns the probability mass at `x`, where the random variable follows the Poisson distribution whose parameter is `lb`.

### Parameters

`x`

  The value at which the probability mass is calculated

`lb`

  The parameter of the Poisson distribution

### Return Values

The probability mass at `x` or `false` for failure.

# stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Probability density function of the t-distribution

### Description

stats_dens_t(float `$x`, float `$dfr`): float

Returns the probability density at `x`, where the random variable follows the t-distribution of which the degree of freedom is `dfr`.

### Parameters

`x`

  The value at which the probability density is calculated

`dfr`

  The degree of freedom of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_uniform

(PECL stats >= 1.0.0)

stats_dens_uniform — Probability density function of the uniform distribution

### Description

stats_dens_uniform(float `$x`, float `$a`, float `$b`): float

Returns the probability density at `x`, where the random variable follows the uniform distribution of which the lower bound is `a` and the upper bound is `b`.

### Parameters

`x`

  The value at which the probability density is calculated

`a`

  The lower bound of the distribution

`b`

  The upper bound of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Probability density function of the Weibull distribution

### Description

stats_dens_weibull(float `$x`, float `$a`, float `$b`): float

Returns the probability density at `x`, where the random variable follows the Weibull distribution of which the shape parameter is `a` and the scale parameter is `b`.

### Parameters

`x`

  The value at which the probability density is calculated

`a`

  The shape parameter of the distribution

`b`

  The scale parameter of the distribution

### Return Values

The probability density at `x` or `false` for failure.

# stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

### Description

stats_harmonic_mean(array `$a`): number

Returns the harmonic mean of the values in `a`.

### Parameters

`a`

  The input array

### Return Values

Returns the harmonic mean of the values in `a`, or `false` if `a` is empty or is not an array.

# stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

### Description

stats_kurtosis(array `$a`): float

Returns the kurtosis of the values in `a`.

### Parameters

`a`

  The input array

### Return Values

Returns the kurtosis of the values in `a`, or `false` if `a` is empty or is not an array.

# stats_rand_gen_beta

(PECL stats >= 1.0.0)

stats_rand_gen_beta — Generates a random deviate from the beta distribution

### Description

stats_rand_gen_beta(float `$a`, float `$b`): float

Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng.

### Parameters

`a`

  The shape parameter of the beta distribution

`b`

  The shape parameter of the beta distribution

### Return Values

A random deviate

# stats_rand_gen_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution

### Description

stats_rand_gen_chisquare(float `$df`): float

Returns a random deviate from the chi-square distribution where the degrees of freedom is `df`.

### Parameters

`df`

  The degrees of freedom

### Return Values

A random deviate

# stats_rand_gen_exponential

(PECL stats >= 1.0.0)

stats_rand_gen_exponential — Generates a random deviate from the exponential distribution

### Description

stats_rand_gen_exponential(float `$av`): float

Returns a random deviate from the exponential distribution of which the scale is `av`.

### Parameters

`av`

  The scale parameter

### Return Values

A random deviate

# stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate from the F distribution

### Description

stats_rand_gen_f(float `$dfn`, float `$dfd`): float

Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates.

### Parameters

`dfn`

  The degrees of freedom in the numerator

`dfd`

  The degrees of freedom in the denominator

### Return Values

A random deviate

# stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

### Description

stats_rand_gen_funiform(float `$low`, float `$high`): float

Returns a random deviate from the uniform distribution from `low` to `high`.

### Parameters

`low`

  The lower bound (exclusive)

`high`

  The upper bound (exclusive)

### Return Values

A random deviate

# stats_rand_gen_gamma

(PECL stats >= 1.0.0)

stats_rand_gen_gamma — Generates a random deviate from the gamma distribution

### Description

stats_rand_gen_gamma(float `$a`, float `$r`): float

Generates a random deviate from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X).

### Parameters

`a`

  location parameter of Gamma distribution (`a` > 0).

`r`

  shape parameter of Gamma distribution (`r` > 0).

### Return Values

A random deviate

# stats_rand_gen_ibinomial

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution

### Description

stats_rand_gen_ibinomial(int `$n`, float `$pp`): int

Returns a random deviate from the binomial distribution whose number of trials is `n` and whose probability of an event in each trial is `pp`.

### Parameters

`n`

  The number of trials

`pp`

  The probability of an event in each trial

### Return Values

A random deviate

# stats_rand_gen_ibinomial_negative

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution

### Description

stats_rand_gen_ibinomial_negative(int `$n`, float `$p`): int

Returns a random deviate from a negative binomial distribution where the number of success is `n` and the success rate is `p`.

### Parameters

`n`

  The number of success

`p`

  The success rate

### Return Values

A random deviate, which is the number of failure.

# stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

### Description

stats_rand_gen_int(): int

Returns a random integer between 1 and 2147483562

### Parameters

This function has no parameters.

### Return Values

A random integer

# stats_rand_gen_ipoisson

(PECL stats >= 1.0.0)

stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution

### Description

stats_rand_gen_ipoisson(float `$mu`): int

Returns a random deviate from the Poisson distribution with parameter `mu`.

### Parameters

`mu`

  The parameter of the Poisson distribution

### Return Values

A random deviate

# stats_rand_gen_iuniform

(PECL stats >= 1.0.0)

stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

### Description

stats_rand_gen_iuniform(int `$low`, int `$high`): int

Returns a random integer from the discrete uniform distribution between `low` (inclusive) and `high` (inclusive).

### Parameters

`low`

  The lower bound

`high`

  The upper bound

### Return Values

A random integer

# stats_rand_gen_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution

### Description

stats_rand_gen_noncentral_chisquare(float `$df`, float `$xnonc`): float

Returns a random deviate from the non-central chi-square distribution with degrees of freedom, `df`, and non-centrality parameter, `xnonc`.

### Parameters

`df`

  The degrees of freedom

`xnonc`

  The non-centrality parameter

### Return Values

A random deviate

# stats_rand_gen_noncentral_f

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution

### Description

stats_rand_gen_noncentral_f(float `$dfn`, float `$dfd`, float `$xnonc`): float

Returns a random deviate from the non-central F distribution where the degrees of freedoms are `dfn` (numerator) and `dfd` (denominator), and the non-centrality parameter is `xnonc`.

### Parameters

`dfn`

  The degrees of freedom of the numerator

`dfd`

  The degrees of freedom of the denominator

`xnonc`

  The non-centrality parameter

### Return Values

A random deviate

# stats_rand_gen_noncentral_t

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution

### Description

stats_rand_gen_noncentral_t(float `$df`, float `$xnonc`): float

Returns a random deviate from the non-central t-distribution with the degrees of freedom, `df`, and the non-centrality parameter, `xnonc`.

### Parameters

`df`

  The degrees of freedom

`xnonc`

  The non-centrality parameter

### Return Values

A random deviate

# stats_rand_gen_normal

(PECL stats >= 1.0.0)

stats_rand_gen_normal — Generates a single random deviate from a normal distribution

### Description

stats_rand_gen_normal(float `$av`, float `$sd`): float

Returns a random deviate from the normal distribution with mean, `av`, and standard deviation, `sd`.

### Parameters

`av`

  The mean of the normal distribution

`sd`

  The standard deviation of the normal distribution

### Return Values

A random deviate

# stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a t-distribution

### Description

stats_rand_gen_t(float `$df`): float

Returns a random deviate from the t-distribution with the degrees of freedom, `df`.

### Parameters

`df`

  The degrees of freedom

### Return Values

A random deviate

# stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Get the seed values of the random number generator

### Description

stats_rand_get_seeds(): array

Returns the current seed values of the random number generator

### Parameters

This function has no parameters.

### Return Values

Returns an array of two integers.

# stats_rand_phrase_to_seeds

(PECL stats >= 1.0.0)

stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator

### Description

stats_rand_phrase_to_seeds(string `$phrase`): array

Generate two seeds for the random number generator from a `phrase`.

### Parameters

`phrase`

  The input phrase

### Return Values

Returns an array of two integers.

# stats_rand_ranf

(PECL stats >= 1.0.0)

stats_rand_ranf — Generates a random floating point number between 0 and 1

### Description

stats_rand_ranf(): float

Returns a random floating point number from a uniform distribution between 0 (exclusive) and 1 (exclusive).

### Parameters

This function has no parameters.

### Return Values

A random floating point number

# stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Set seed values to the random generator

### Description

stats_rand_setall(int `$iseed1`, int `$iseed2`): void

Set `iseed1` and `iseed2` as seed values to the random generator used in statistic functions.

### Parameters

`iseed1`

  The value which is used as the random seed

`iseed2`

  The value which is used as the random seed

### Return Values

No values are returned.

# stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

### Description

stats_skew(array `$a`): float

Returns the skewness of the values in `a`.

### Parameters

`a`

  The input array

### Return Values

Returns the skewness of the values in `a`, or `false` if `a` is empty or is not an array.

# stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

### Description

stats_standard_deviation(array `$a`, bool `$sample` = `false`): float

Returns the standard deviation of the values in `a`.

### Parameters

`a`

  The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

`sample`

  Indicates if `a` represents a sample of the population; defaults to `false`.

### Return Values

Returns the standard deviation on success; `false` on failure.

### Errors/Exceptions

Raises an `E_WARNING` when there are fewer than 2 values in `a`.

# stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Returns a binomial coefficient

### Description

stats_stat_binomial_coef(int `$x`, int `$n`): float

Returns the binomial coefficient of `n` choose `x`.

### Parameters

`x`

  The number of chooses from the set

`n`

  The number of elements in the set

### Return Values

Returns the binomial coefficient

# stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets

### Description

stats_stat_correlation(array `$arr1`, array `$arr2`): float

Returns the Pearson correlation coefficient between `arr1` and `arr2`.

### Parameters

`arr1`

  The first array

`arr2`

  The second array

### Return Values

Returns the Pearson correlation coefficient between `arr1` and `arr2`, or `false` on failure.

# stats_stat_factorial

(PECL stats >= 1.0.0)

stats_stat_factorial — Returns the factorial of an integer

### Description

stats_stat_factorial(int `$n`): float

Returns the factorial of an integer, `n`.

### Parameters

`n`

  An integer

### Return Values

The factorial of `n`.

# stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Returns the t-value from the independent two-sample t-test

### Description

stats_stat_independent_t(array `$arr1`, array `$arr2`): float

Returns the t-value of the independent two-sample t-test between `arr1` and `arr2`.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`arr1`

  The first set of values

`arr2`

  The second set of values

### Return Values

Returns the t-value, or `false` if failure.

# stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct — Returns the inner product of two vectors

### Description

stats_stat_innerproduct(array `$arr1`, array `$arr2`): float

Returns the inner product of `arr1` and `arr2`.

### Parameters

`arr1`

  The first array

`arr2`

  The second array

### Return Values

Returns the inner product of `arr1` and `arr2`, or `false` on failure.

# stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples

### Description

stats_stat_paired_t(array `$arr1`, array `$arr2`): float

Returns the t-value of the dependent t-test for paired samples `arr1` and `arr2`.

### Parameters

`arr1`

  The first samples

`arr2`

  The second samples

### Return Values

Returns the t-value, or `false` if failure.

# stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Returns the percentile value

### Description

stats_stat_percentile(array `$arr`, float `$perc`): float

Returns the `perc`-th percentile value of the array `arr`.

### Parameters

`arr`

  The input array

`perc`

  The percentile

### Return Values

Returns the percentile values of the input array.

# stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Returns the power sum of a vector

### Description

stats_stat_powersum(array `$arr`, float `$power`): float

Returns the sum of the `power`-th power of a vector represented as an array `arr`.

### Parameters

`arr`

  The input array

`power`

  The power

### Return Values

Returns the power sum of the input array.

# stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the variance

### Description

stats_variance(array `$a`, bool `$sample` = `false`): float

Returns the variance of the values in `a`.

### Parameters

`a`

  The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

`sample`

  Indicates if `a` represents a sample of the population; defaults to `false`.

### Return Values

Returns the variance on success; `false` on failure.

## Table of Contents

- stats_absolute_deviation — Returns the absolute deviation of an array of values
- stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others
- stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others
- stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others
- stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others
- stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others
- stats_cdf_f — Calculates any one parameter of the F distribution given values for the others
- stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others
- stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others
- stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others
- stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others
- stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others
- stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others
- stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others
- stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others
- stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others
- stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others
- stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others
- stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others
- stats_covariance — Computes the covariance of two data sets
- stats_dens_beta — Probability density function of the beta distribution
- stats_dens_cauchy — Probability density function of the Cauchy distribution
- stats_dens_chisquare — Probability density function of the chi-square distribution
- stats_dens_exponential — Probability density function of the exponential distribution
- stats_dens_f — Probability density function of the F distribution
- stats_dens_gamma — Probability density function of the gamma distribution
- stats_dens_laplace — Probability density function of the Laplace distribution
- stats_dens_logistic — Probability density function of the logistic distribution
- stats_dens_normal — Probability density function of the normal distribution
- stats_dens_pmf_binomial — Probability mass function of the binomial distribution
- stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution
- stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution
- stats_dens_pmf_poisson — Probability mass function of the Poisson distribution
- stats_dens_t — Probability density function of the t-distribution
- stats_dens_uniform — Probability density function of the uniform distribution
- stats_dens_weibull — Probability density function of the Weibull distribution
- stats_harmonic_mean — Returns the harmonic mean of an array of values
- stats_kurtosis — Computes the kurtosis of the data in the array
- stats_rand_gen_beta — Generates a random deviate from the beta distribution
- stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution
- stats_rand_gen_exponential — Generates a random deviate from the exponential distribution
- stats_rand_gen_f — Generates a random deviate from the F distribution
- stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
- stats_rand_gen_gamma — Generates a random deviate from the gamma distribution
- stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution
- stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution
- stats_rand_gen_int — Generates random integer between 1 and 2147483562
- stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution
- stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
- stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution
- stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution
- stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution
- stats_rand_gen_normal — Generates a single random deviate from a normal distribution
- stats_rand_gen_t — Generates a single random deviate from a t-distribution
- stats_rand_get_seeds — Get the seed values of the random number generator
- stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator
- stats_rand_ranf — Generates a random floating point number between 0 and 1
- stats_rand_setall — Set seed values to the random generator
- stats_skew — Computes the skewness of the data in the array
- stats_standard_deviation — Returns the standard deviation
- stats_stat_binomial_coef — Returns a binomial coefficient
- stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets
- stats_stat_factorial — Returns the factorial of an integer
- stats_stat_independent_t — Returns the t-value from the independent two-sample t-test
- stats_stat_innerproduct — Returns the inner product of two vectors
- stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples
- stats_stat_percentile — Returns the percentile value
- stats_stat_powersum — Returns the power sum of a vector
- stats_variance — Returns the variance

- Installing/Configuring
  - Requirements
  - Installation
- Statistic Functions
  - stats_absolute_deviation — Returns the absolute deviation of an array of values
  - stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others
  - stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others
  - stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others
  - stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others
  - stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others
  - stats_cdf_f — Calculates any one parameter of the F distribution given values for the others
  - stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others
  - stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others
  - stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others
  - stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others
  - stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others
  - stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others
  - stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others
  - stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others
  - stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others
  - stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others
  - stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others
  - stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others
  - stats_covariance — Computes the covariance of two data sets
  - stats_dens_beta — Probability density function of the beta distribution
  - stats_dens_cauchy — Probability density function of the Cauchy distribution
  - stats_dens_chisquare — Probability density function of the chi-square distribution
  - stats_dens_exponential — Probability density function of the exponential distribution
  - stats_dens_f — Probability density function of the F distribution
  - stats_dens_gamma — Probability density function of the gamma distribution
  - stats_dens_laplace — Probability density function of the Laplace distribution
  - stats_dens_logistic — Probability density function of the logistic distribution
  - stats_dens_normal — Probability density function of the normal distribution
  - stats_dens_pmf_binomial — Probability mass function of the binomial distribution
  - stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution
  - stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution
  - stats_dens_pmf_poisson — Probability mass function of the Poisson distribution
  - stats_dens_t — Probability density function of the t-distribution
  - stats_dens_uniform — Probability density function of the uniform distribution
  - stats_dens_weibull — Probability density function of the Weibull distribution
  - stats_harmonic_mean — Returns the harmonic mean of an array of values
  - stats_kurtosis — Computes the kurtosis of the data in the array
  - stats_rand_gen_beta — Generates a random deviate from the beta distribution
  - stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution
  - stats_rand_gen_exponential — Generates a random deviate from the exponential distribution
  - stats_rand_gen_f — Generates a random deviate from the F distribution
  - stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
  - stats_rand_gen_gamma — Generates a random deviate from the gamma distribution
  - stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution
  - stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution
  - stats_rand_gen_int — Generates random integer between 1 and 2147483562
  - stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution
  - stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
  - stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution
  - stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution
  - stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution
  - stats_rand_gen_normal — Generates a single random deviate from a normal distribution
  - stats_rand_gen_t — Generates a single random deviate from a t-distribution
  - stats_rand_get_seeds — Get the seed values of the random number generator
  - stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator
  - stats_rand_ranf — Generates a random floating point number between 0 and 1
  - stats_rand_setall — Set seed values to the random generator
  - stats_skew — Computes the skewness of the data in the array
  - stats_standard_deviation — Returns the standard deviation
  - stats_stat_binomial_coef — Returns a binomial coefficient
  - stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets
  - stats_stat_factorial — Returns the factorial of an integer
  - stats_stat_independent_t — Returns the t-value from the independent two-sample t-test
  - stats_stat_innerproduct — Returns the inner product of two vectors
  - stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples
  - stats_stat_percentile — Returns the percentile value
  - stats_stat_powersum — Returns the power sum of a vector
  - stats_variance — Returns the variance

# Technical Analysis for Traders

# Introduction

The trader extension is a free open source stock library based on TA-Lib. It's dedicated to trading software developers requiring to perform technical analysis of financial market data. Alongside many indicators like ADX, MACD, RSI, Stochastic, TRIX the candlestick pattern recognition and several vector arithmetic and algebraic functions are present.

Calculations can be done in two modes - TA-Lib and Metastock. Changing it using trader_set_compat() will affect the way some trader functions work.

Some trader functions provide different results depending of the "starting point" of the data being involved. This is often referred as a function having memories. An example of such function is the Exponential Moving Average. It is possible to control the unstable period (the amount of data to strip off) using trader_set_unstable_period() function.

Extended documentation about indicators, formulas and implementations in other programming languages can be found under » https://ta-lib.org/.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

The trader extension is based on » TA-Lib. TA-Lib is fully integrated into the extension, therefore no external libraries are needed.

## Installation

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: » https://pecl.php.net/package/trader.

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Trader Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
trader.real_precision | 3 | `INI_ALL` | Since trader 0.2.1
trader.real_round_mode | HALF_DOWN | `INI_ALL` | Since trader 0.3.0

Here's a short explanation of the configuration directives.

`trader.real_precision` int

  All the values in the returned arrays will be rounded to this precision. However the calculations inside TA-Lib happen with unrounded values.

`trader.real_round_mode` string

  Controls the trader real rounding policy. Valid values are `HALF_UP`, `HALF_DOWN`, `HALF_EVEN` and `HALF_ODD`. The behaviour is identical to the round() function used with the mode argument.

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

`TRADER_MA_TYPE_SMA` (int)
`TRADER_MA_TYPE_EMA` (int)
`TRADER_MA_TYPE_WMA` (int)
`TRADER_MA_TYPE_DEMA` (int)
`TRADER_MA_TYPE_TEMA` (int)
`TRADER_MA_TYPE_TRIMA` (int)
`TRADER_MA_TYPE_KAMA` (int)
`TRADER_MA_TYPE_MAMA` (int)
`TRADER_MA_TYPE_T3` (int)
`TRADER_REAL_MIN` (float)
`TRADER_REAL_MAX` (float)
`TRADER_FUNC_UNST_ADX` (int)
`TRADER_FUNC_UNST_ADXR` (int)
`TRADER_FUNC_UNST_ATR` (int)
`TRADER_FUNC_UNST_CMO` (int)
`TRADER_FUNC_UNST_DX` (int)
`TRADER_FUNC_UNST_EMA` (int)
`TRADER_FUNC_UNST_HT_DCPERIOD` (int)
`TRADER_FUNC_UNST_HT_DCPHASE` (int)
`TRADER_FUNC_UNST_HT_PHASOR` (int)
`TRADER_FUNC_UNST_HT_SINE` (int)
`TRADER_FUNC_UNST_HT_TRENDLINE` (int)
`TRADER_FUNC_UNST_HT_TRENDMODE` (int)
`TRADER_FUNC_UNST_KAMA` (int)
`TRADER_FUNC_UNST_MAMA` (int)
`TRADER_FUNC_UNST_MFI` (int)
`TRADER_FUNC_UNST_MINUS_DI` (int)
`TRADER_FUNC_UNST_MINUS_DM` (int)
`TRADER_FUNC_UNST_NATR` (int)
`TRADER_FUNC_UNST_PLUS_DI` (int)
`TRADER_FUNC_UNST_PLUS_DM` (int)
`TRADER_FUNC_UNST_RSI` (int)
`TRADER_FUNC_UNST_STOCHRSI` (int)
`TRADER_FUNC_UNST_T3` (int)
`TRADER_FUNC_UNST_ALL` (int)
`TRADER_FUNC_UNST_NONE` (int)
`TRADER_COMPATIBILITY_DEFAULT` (int)
`TRADER_COMPATIBILITY_METASTOCK` (int)
`TRADER_ERR_SUCCESS` (int)
`TRADER_ERR_LIB_NOT_INITIALIZE` (int)
`TRADER_ERR_BAD_PARAM` (int)
`TRADER_ERR_ALLOC_ERR` (int)
`TRADER_ERR_GROUP_NOT_FOUND` (int)
`TRADER_ERR_FUNC_NOT_FOUND` (int)
`TRADER_ERR_INVALID_HANDLE` (int)
`TRADER_ERR_INVALID_PARAM_HOLDER` (int)
`TRADER_ERR_INVALID_PARAM_HOLDER_TYPE` (int)
`TRADER_ERR_INVALID_PARAM_FUNCTION` (int)
`TRADER_ERR_INPUT_NOT_ALL_INITIALIZE` (int)
`TRADER_ERR_OUTPUT_NOT_ALL_INITIALIZE` (int)
`TRADER_ERR_OUT_OF_RANGE_START_INDEX` (int)
`TRADER_ERR_OUT_OF_RANGE_END_INDEX` (int)
`TRADER_ERR_INVALID_LIST_TYPE` (int)
`TRADER_ERR_BAD_OBJECT` (int)
`TRADER_ERR_NOT_SUPPORTED` (int)
`TRADER_ERR_INTERNAL_ERROR` (int)
`TRADER_ERR_UNKNOWN_ERROR` (int)

# Trader Functions

# trader_acos

(PECL trader >= 0.2.0)

trader_acos — Vector Trigonometric ACos

### Description

trader_acos(array `$real`): array

Calculates the arc cosine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ad

(PECL trader >= 0.2.0)

trader_ad — Chaikin A/D Line

### Description

trader_ad(
array `$high`,
array `$low`,
array `$close`,
array `$volume`
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`volume`

  Volume traded, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_add

(PECL trader >= 0.2.0)

trader_add — Vector Arithmetic Add

### Description

trader_add(array `$real0`, array `$real1`): array

Calculates the vector addition of `real0` to `real1` and returns the resulting vector.

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_adosc

(PECL trader >= 0.2.0)

trader_adosc — Chaikin A/D Oscillator

### Description

trader_adosc(
array `$high`,
array `$low`,
array `$close`,
array `$volume`,
int `$fastPeriod` = ?,
int `$slowPeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`volume`

  Volume traded, array of real values.

`fastPeriod`

  Number of period for the fast MA. Valid range from 2 to 100000.

`slowPeriod`

  Number of period for the slow MA. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_adx

(PECL trader >= 0.2.0)

trader_adx — Average Directional Movement Index

### Description

trader_adx(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_adxr

(PECL trader >= 0.2.0)

trader_adxr — Average Directional Movement Index Rating

### Description

trader_adxr(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_apo

(PECL trader >= 0.2.0)

trader_apo — Absolute Price Oscillator

### Description

trader_apo(
array `$real`,
int `$fastPeriod` = ?,
int `$slowPeriod` = ?,
int `$mAType` = ?
): array

### Parameters

`real`

  Array of real values.

`fastPeriod`

  Number of period for the fast MA. Valid range from 2 to 100000.

`slowPeriod`

  Number of period for the slow MA. Valid range from 2 to 100000.

`mAType`

  Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_aroon

(PECL trader >= 0.2.0)

trader_aroon — Aroon

### Description

trader_aroon(array `$high`, array `$low`, int `$timePeriod` = ?): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_aroonosc

(PECL trader >= 0.2.0)

trader_aroonosc — Aroon Oscillator

### Description

trader_aroonosc(array `$high`, array `$low`, int `$timePeriod` = ?): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_asin

(PECL trader >= 0.2.0)

trader_asin — Vector Trigonometric ASin

### Description

trader_asin(array `$real`): array

Calculates the arc sine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_atan

(PECL trader >= 0.2.0)

trader_atan — Vector Trigonometric ATan

### Description

trader_atan(array `$real`): array

Calculates the arc tangent for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_atr

(PECL trader >= 0.2.0)

trader_atr — Average True Range

### Description

trader_atr(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_avgprice

(PECL trader >= 0.2.0)

trader_avgprice — Average Price

### Description

trader_avgprice(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_bbands

(PECL trader >= 0.2.0)

trader_bbands — Bollinger Bands

### Description

trader_bbands(
array `$real`,
int `$timePeriod` = ?,
float `$nbDevUp` = ?,
float `$nbDevDn` = ?,
int `$mAType` = ?
): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`nbDevUp`

  Deviation multiplier for upper band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

`nbDevDn`

  Deviation multiplier for lower band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

`mAType`

  Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_beta

(PECL trader >= 0.2.0)

trader_beta — Beta

### Description

trader_beta(array `$real0`, array `$real1`, int `$timePeriod` = ?): array

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_bop

(PECL trader >= 0.2.0)

trader_bop — Balance Of Power

### Description

trader_bop(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cci

(PECL trader >= 0.2.0)

trader_cci — Commodity Channel Index

### Description

trader_cci(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl2crows

(PECL trader >= 0.2.0)

trader_cdl2crows — Two Crows

### Description

trader_cdl2crows(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3blackcrows

(PECL trader >= 0.2.0)

trader_cdl3blackcrows — Three Black Crows

### Description

trader_cdl3blackcrows(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3inside

(PECL trader >= 0.2.0)

trader_cdl3inside — Three Inside Up/Down

### Description

trader_cdl3inside(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3linestrike

(PECL trader >= 0.2.0)

trader_cdl3linestrike — Three-Line Strike

### Description

trader_cdl3linestrike(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3outside

(PECL trader >= 0.2.0)

trader_cdl3outside — Three Outside Up/Down

### Description

trader_cdl3outside(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3starsinsouth

(PECL trader >= 0.2.0)

trader_cdl3starsinsouth — Three Stars In The South

### Description

trader_cdl3starsinsouth(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdl3whitesoldiers

(PECL trader >= 0.2.0)

trader_cdl3whitesoldiers — Three Advancing White Soldiers

### Description

trader_cdl3whitesoldiers(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlabandonedbaby

(PECL trader >= 0.2.0)

trader_cdlabandonedbaby — Abandoned Baby

### Description

trader_cdlabandonedbaby(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdladvanceblock

(PECL trader >= 0.2.0)

trader_cdladvanceblock — Advance Block

### Description

trader_cdladvanceblock(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlbelthold

(PECL trader >= 0.2.0)

trader_cdlbelthold — Belt-hold

### Description

trader_cdlbelthold(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlbreakaway

(PECL trader >= 0.2.0)

trader_cdlbreakaway — Breakaway

### Description

trader_cdlbreakaway(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlclosingmarubozu

(PECL trader >= 0.2.0)

trader_cdlclosingmarubozu — Closing Marubozu

### Description

trader_cdlclosingmarubozu(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlconcealbabyswall

(PECL trader >= 0.2.0)

trader_cdlconcealbabyswall — Concealing Baby Swallow

### Description

trader_cdlconcealbabyswall(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlcounterattack

(PECL trader >= 0.2.0)

trader_cdlcounterattack — Counterattack

### Description

trader_cdlcounterattack(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdldarkcloudcover

(PECL trader >= 0.2.0)

trader_cdldarkcloudcover — Dark Cloud Cover

### Description

trader_cdldarkcloudcover(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdldoji

(PECL trader >= 0.2.0)

trader_cdldoji — Doji

### Description

trader_cdldoji(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdldojistar

(PECL trader >= 0.2.0)

trader_cdldojistar — Doji Star

### Description

trader_cdldojistar(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdldragonflydoji

(PECL trader >= 0.2.0)

trader_cdldragonflydoji — Dragonfly Doji

### Description

trader_cdldragonflydoji(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlengulfing

(PECL trader >= 0.2.0)

trader_cdlengulfing — Engulfing Pattern

### Description

trader_cdlengulfing(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdleveningdojistar

(PECL trader >= 0.2.0)

trader_cdleveningdojistar — Evening Doji Star

### Description

trader_cdleveningdojistar(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdleveningstar

(PECL trader >= 0.2.0)

trader_cdleveningstar — Evening Star

### Description

trader_cdleveningstar(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlgapsidesidewhite

(PECL trader >= 0.2.0)

trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines

### Description

trader_cdlgapsidesidewhite(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlgravestonedoji

(PECL trader >= 0.2.0)

trader_cdlgravestonedoji — Gravestone Doji

### Description

trader_cdlgravestonedoji(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhammer

(PECL trader >= 0.2.0)

trader_cdlhammer — Hammer

### Description

trader_cdlhammer(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhangingman

(PECL trader >= 0.2.0)

trader_cdlhangingman — Hanging Man

### Description

trader_cdlhangingman(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlharami

(PECL trader >= 0.2.0)

trader_cdlharami — Harami Pattern

### Description

trader_cdlharami(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlharamicross

(PECL trader >= 0.2.0)

trader_cdlharamicross — Harami Cross Pattern

### Description

trader_cdlharamicross(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhighwave

(PECL trader >= 0.2.0)

trader_cdlhighwave — High-Wave Candle

### Description

trader_cdlhighwave(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhikkake

(PECL trader >= 0.2.0)

trader_cdlhikkake — Hikkake Pattern

### Description

trader_cdlhikkake(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhikkakemod

(PECL trader >= 0.2.0)

trader_cdlhikkakemod — Modified Hikkake Pattern

### Description

trader_cdlhikkakemod(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlhomingpigeon

(PECL trader >= 0.2.0)

trader_cdlhomingpigeon — Homing Pigeon

### Description

trader_cdlhomingpigeon(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlidentical3crows

(PECL trader >= 0.2.0)

trader_cdlidentical3crows — Identical Three Crows

### Description

trader_cdlidentical3crows(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlinneck

(PECL trader >= 0.2.0)

trader_cdlinneck — In-Neck Pattern

### Description

trader_cdlinneck(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlinvertedhammer

(PECL trader >= 0.2.0)

trader_cdlinvertedhammer — Inverted Hammer

### Description

trader_cdlinvertedhammer(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlkicking

(PECL trader >= 0.2.0)

trader_cdlkicking — Kicking

### Description

trader_cdlkicking(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlkickingbylength

(PECL trader >= 0.2.0)

trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu

### Description

trader_cdlkickingbylength(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlladderbottom

(PECL trader >= 0.2.0)

trader_cdlladderbottom — Ladder Bottom

### Description

trader_cdlladderbottom(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdllongleggeddoji

(PECL trader >= 0.2.0)

trader_cdllongleggeddoji — Long Legged Doji

### Description

trader_cdllongleggeddoji(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdllongline

(PECL trader >= 0.2.0)

trader_cdllongline — Long Line Candle

### Description

trader_cdllongline(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlmarubozu

(PECL trader >= 0.2.0)

trader_cdlmarubozu — Marubozu

### Description

trader_cdlmarubozu(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlmatchinglow

(PECL trader >= 0.2.0)

trader_cdlmatchinglow — Matching Low

### Description

trader_cdlmatchinglow(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlmathold

(PECL trader >= 0.2.0)

trader_cdlmathold — Mat Hold

### Description

trader_cdlmathold(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlmorningdojistar

(PECL trader >= 0.2.0)

trader_cdlmorningdojistar — Morning Doji Star

### Description

trader_cdlmorningdojistar(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlmorningstar

(PECL trader >= 0.2.0)

trader_cdlmorningstar — Morning Star

### Description

trader_cdlmorningstar(
array `$open`,
array `$high`,
array `$low`,
array `$close`,
float `$penetration` = ?
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`penetration`

  Percentage of penetration of a candle within another candle.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlonneck

(PECL trader >= 0.2.0)

trader_cdlonneck — On-Neck Pattern

### Description

trader_cdlonneck(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlpiercing

(PECL trader >= 0.2.0)

trader_cdlpiercing — Piercing Pattern

### Description

trader_cdlpiercing(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlrickshawman

(PECL trader >= 0.2.0)

trader_cdlrickshawman — Rickshaw Man

### Description

trader_cdlrickshawman(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlrisefall3methods

(PECL trader >= 0.2.0)

trader_cdlrisefall3methods — Rising/Falling Three Methods

### Description

trader_cdlrisefall3methods(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlseparatinglines

(PECL trader >= 0.2.0)

trader_cdlseparatinglines — Separating Lines

### Description

trader_cdlseparatinglines(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlshootingstar

(PECL trader >= 0.2.0)

trader_cdlshootingstar — Shooting Star

### Description

trader_cdlshootingstar(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlshortline

(PECL trader >= 0.2.0)

trader_cdlshortline — Short Line Candle

### Description

trader_cdlshortline(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlspinningtop

(PECL trader >= 0.2.0)

trader_cdlspinningtop — Spinning Top

### Description

trader_cdlspinningtop(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlstalledpattern

(PECL trader >= 0.2.0)

trader_cdlstalledpattern — Stalled Pattern

### Description

trader_cdlstalledpattern(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlsticksandwich

(PECL trader >= 0.2.0)

trader_cdlsticksandwich — Stick Sandwich

### Description

trader_cdlsticksandwich(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdltakuri

(PECL trader >= 0.2.0)

trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)

### Description

trader_cdltakuri(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdltasukigap

(PECL trader >= 0.2.0)

trader_cdltasukigap — Tasuki Gap

### Description

trader_cdltasukigap(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlthrusting

(PECL trader >= 0.2.0)

trader_cdlthrusting — Thrusting Pattern

### Description

trader_cdlthrusting(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdltristar

(PECL trader >= 0.2.0)

trader_cdltristar — Tristar Pattern

### Description

trader_cdltristar(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlunique3river

(PECL trader >= 0.2.0)

trader_cdlunique3river — Unique 3 River

### Description

trader_cdlunique3river(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlupsidegap2crows

(PECL trader >= 0.2.0)

trader_cdlupsidegap2crows — Upside Gap Two Crows

### Description

trader_cdlupsidegap2crows(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cdlxsidegap3methods

(PECL trader >= 0.2.0)

trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods

### Description

trader_cdlxsidegap3methods(
array `$open`,
array `$high`,
array `$low`,
array `$close`
): array

### Parameters

`open`

  Opening price, array of real values.

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ceil

(PECL trader >= 0.2.0)

trader_ceil — Vector Ceil

### Description

trader_ceil(array `$real`): array

Calculates the next highest integer for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cmo

(PECL trader >= 0.2.0)

trader_cmo — Chande Momentum Oscillator

### Description

trader_cmo(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_correl

(PECL trader >= 0.2.0)

trader_correl — Pearson's Correlation Coefficient (r)

### Description

trader_correl(array `$real0`, array `$real1`, int `$timePeriod` = ?): array

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cos

(PECL trader >= 0.2.0)

trader_cos — Vector Trigonometric Cos

### Description

trader_cos(array `$real`): array

Calculates the cosine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_cosh

(PECL trader >= 0.2.0)

trader_cosh — Vector Trigonometric Cosh

### Description

trader_cosh(array `$real`): array

Calculates the hyperbolic cosine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_dema

(PECL trader >= 0.2.0)

trader_dema — Double Exponential Moving Average

### Description

trader_dema(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_div

(PECL trader >= 0.2.0)

trader_div — Vector Arithmetic Div

### Description

trader_div(array `$real0`, array `$real1`): array

Divides each value from `real0` by the corresponding value from `real1` and returns the resulting array.

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_dx

(PECL trader >= 0.2.0)

trader_dx — Directional Movement Index

### Description

trader_dx(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ema

(PECL trader >= 0.2.0)

trader_ema — Exponential Moving Average

### Description

trader_ema(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_errno

(PECL trader >= 0.3.0)

trader_errno — Get error code

### Description

trader_errno(): int

Get error code of the last operation.

### Parameters

This function has no parameters.

### Return Values

Returns the error code identified by one of the TRADER_ERR_* constants.

# trader_exp

(PECL trader >= 0.2.0)

trader_exp — Vector Arithmetic Exp

### Description

trader_exp(array `$real`): array

Calculates `e` raised to the power of each value in `real`. Returns an array with the calculated data.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_floor

(PECL trader >= 0.2.0)

trader_floor — Vector Floor

### Description

trader_floor(array `$real`): array

Calculates the next lowest integer for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_get_compat

(PECL trader >= 0.2.2)

trader_get_compat — Get compatibility mode

### Description

trader_get_compat(): int

Get compatibility mode which affects the way calculations are done by all the extension functions.

### Parameters

This function has no parameters.

### Return Values

Returns the compatibility mode id which can be identified by TRADER_COMPATIBILITY_* series of constants.

# trader_get_unstable_period

(PECL trader >= 0.2.2)

trader_get_unstable_period — Get unstable period

### Description

trader_get_unstable_period(int `$functionId`): int

Get unstable period factor for a particular function.

### Parameters

`functionId`

  Function ID the factor to be read for. TRADER_FUNC_UNST_* series of constants should be used.

### Return Values

Returns the unstable period factor for the corresponding function.

# trader_ht_dcperiod

(PECL trader >= 0.2.0)

trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period

### Description

trader_ht_dcperiod(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ht_dcphase

(PECL trader >= 0.2.0)

trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase

### Description

trader_ht_dcphase(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ht_phasor

(PECL trader >= 0.2.0)

trader_ht_phasor — Hilbert Transform - Phasor Components

### Description

trader_ht_phasor(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ht_sine

(PECL trader >= 0.2.0)

trader_ht_sine — Hilbert Transform - SineWave

### Description

trader_ht_sine(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ht_trendline

(PECL trader >= 0.2.0)

trader_ht_trendline — Hilbert Transform - Instantaneous Trendline

### Description

trader_ht_trendline(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ht_trendmode

(PECL trader >= 0.2.0)

trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode

### Description

trader_ht_trendmode(array `$real`): array

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_kama

(PECL trader >= 0.2.0)

trader_kama — Kaufman Adaptive Moving Average

### Description

trader_kama(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_linearreg

(PECL trader >= 0.2.0)

trader_linearreg — Linear Regression

### Description

trader_linearreg(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_linearreg_angle

(PECL trader >= 0.2.0)

trader_linearreg_angle — Linear Regression Angle

### Description

trader_linearreg_angle(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_linearreg_intercept

(PECL trader >= 0.2.0)

trader_linearreg_intercept — Linear Regression Intercept

### Description

trader_linearreg_intercept(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_linearreg_slope

(PECL trader >= 0.2.0)

trader_linearreg_slope — Linear Regression Slope

### Description

trader_linearreg_slope(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ln

(PECL trader >= 0.2.0)

trader_ln — Vector Log Natural

### Description

trader_ln(array `$real`): array

Calculates the natural logarithm for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_log10

(PECL trader >= 0.2.0)

trader_log10 — Vector Log10

### Description

trader_log10(array `$real`): array

Calculates the base-10 logarithm for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ma

(PECL trader >= 0.2.0)

trader_ma — Moving average

### Description

trader_ma(array `$real`, int `$timePeriod` = ?, int `$mAType` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`mAType`

  Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_macd

(PECL trader >= 0.2.0)

trader_macd — Moving Average Convergence/Divergence

### Description

trader_macd(
array `$real`,
int `$fastPeriod` = ?,
int `$slowPeriod` = ?,
int `$signalPeriod` = ?
): array

### Parameters

`real`

  Array of real values.

`fastPeriod`

  Number of period for the fast MA. Valid range from 2 to 100000.

`slowPeriod`

  Number of period for the slow MA. Valid range from 2 to 100000.

`signalPeriod`

  Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_macdext

(PECL trader >= 0.2.0)

trader_macdext — MACD with controllable MA type

### Description

trader_macdext(
array `$real`,
int `$fastPeriod` = ?,
int `$fastMAType` = ?,
int `$slowPeriod` = ?,
int `$slowMAType` = ?,
int `$signalPeriod` = ?,
int `$signalMAType` = ?
): array

### Parameters

`real`

  Array of real values.

`fastPeriod`

  Number of period for the fast MA. Valid range from 2 to 100000.

`fastMAType`

  Type of Moving Average for fast MA. TRADER_MA_TYPE_* series of constants should be used.

`slowPeriod`

  Number of period for the slow MA. Valid range from 2 to 100000.

`slowMAType`

  Type of Moving Average for slow MA. TRADER_MA_TYPE_* series of constants should be used.

`signalPeriod`

  Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

`signalMAType`

  Type of Moving Average for signal line. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_macdfix

(PECL trader >= 0.2.0)

trader_macdfix — Moving Average Convergence/Divergence Fix 12/26

### Description

trader_macdfix(array `$real`, int `$signalPeriod` = ?): array

### Parameters

`real`

  Array of real values.

`signalPeriod`

  Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_mama

(PECL trader >= 0.2.0)

trader_mama — MESA Adaptive Moving Average

### Description

trader_mama(array `$real`, float `$fastLimit` = ?, float `$slowLimit` = ?): array

### Parameters

`real`

  Array of real values.

`fastLimit`

  Upper limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

`slowLimit`

  Lower limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

### Return Values

Returns an array with calculated data or false on failure.

# trader_mavp

(PECL trader >= 0.2.0)

trader_mavp — Moving average with variable period

### Description

trader_mavp(
array `$real`,
array `$periods`,
int `$minPeriod` = ?,
int `$maxPeriod` = ?,
int `$mAType` = ?
): array

### Parameters

`real`

  Array of real values.

`periods`

  Array of real values.

`minPeriod`

  Value less than minimum will be changed to Minimum period. Valid range from 2 to 100000

`maxPeriod`

  Value higher than minimum will be changed to Maximum period. Valid range from 2 to 100000

`mAType`

  Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_max

(PECL trader >= 0.2.0)

trader_max — Highest value over a specified period

### Description

trader_max(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_maxindex

(PECL trader >= 0.2.0)

trader_maxindex — Index of highest value over a specified period

### Description

trader_maxindex(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_medprice

(PECL trader >= 0.2.0)

trader_medprice — Median Price

### Description

trader_medprice(array `$high`, array `$low`): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_mfi

(PECL trader >= 0.2.0)

trader_mfi — Money Flow Index

### Description

trader_mfi(
array `$high`,
array `$low`,
array `$close`,
array `$volume`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`volume`

  Volume traded, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_midpoint

(PECL trader >= 0.2.0)

trader_midpoint — MidPoint over period

### Description

trader_midpoint(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_midprice

(PECL trader >= 0.2.0)

trader_midprice — Midpoint Price over period

### Description

trader_midprice(array `$high`, array `$low`, int `$timePeriod` = ?): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_min

(PECL trader >= 0.2.0)

trader_min — Lowest value over a specified period

### Description

trader_min(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_minindex

(PECL trader >= 0.2.0)

trader_minindex — Index of lowest value over a specified period

### Description

trader_minindex(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_minmax

(PECL trader >= 0.2.0)

trader_minmax — Lowest and highest values over a specified period

### Description

trader_minmax(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_minmaxindex

(PECL trader >= 0.2.0)

trader_minmaxindex — Indexes of lowest and highest values over a specified period

### Description

trader_minmaxindex(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_minus_di

(PECL trader >= 0.2.0)

trader_minus_di — Minus Directional Indicator

### Description

trader_minus_di(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_minus_dm

(PECL trader >= 0.2.0)

trader_minus_dm — Minus Directional Movement

### Description

trader_minus_dm(array `$high`, array `$low`, int `$timePeriod` = ?): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_mom

(PECL trader >= 0.2.0)

trader_mom — Momentum

### Description

trader_mom(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_mult

(PECL trader >= 0.2.0)

trader_mult — Vector Arithmetic Mult

### Description

trader_mult(array `$real0`, array `$real1`): array

Calculates the vector dot product of `real0` with `real1` and returns the resulting vector.

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_natr

(PECL trader >= 0.2.0)

trader_natr — Normalized Average True Range

### Description

trader_natr(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_obv

(PECL trader >= 0.2.0)

trader_obv — On Balance Volume

### Description

trader_obv(array `$real`, array `$volume`): array

### Parameters

`real`

  Array of real values.

`volume`

  Volume traded, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_plus_di

(PECL trader >= 0.2.0)

trader_plus_di — Plus Directional Indicator

### Description

trader_plus_di(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_plus_dm

(PECL trader >= 0.2.0)

trader_plus_dm — Plus Directional Movement

### Description

trader_plus_dm(array `$high`, array `$low`, int `$timePeriod` = ?): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ppo

(PECL trader >= 0.2.0)

trader_ppo — Percentage Price Oscillator

### Description

trader_ppo(
array `$real`,
int `$fastPeriod` = ?,
int `$slowPeriod` = ?,
int `$mAType` = ?
): array

### Parameters

`real`

  Array of real values.

`fastPeriod`

  Number of period for the fast MA. Valid range from 2 to 100000.

`slowPeriod`

  Number of period for the slow MA. Valid range from 2 to 100000.

`mAType`

  Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_roc

(PECL trader >= 0.2.0)

trader_roc — Rate of change : ((price/prevPrice)-1)*100

### Description

trader_roc(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_rocp

(PECL trader >= 0.2.0)

trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice

### Description

trader_rocp(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_rocr

(PECL trader >= 0.2.0)

trader_rocr — Rate of change ratio: (price/prevPrice)

### Description

trader_rocr(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_rocr100

(PECL trader >= 0.2.0)

trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100

### Description

trader_rocr100(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_rsi

(PECL trader >= 0.2.0)

trader_rsi — Relative Strength Index

### Description

trader_rsi(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sar

(PECL trader >= 0.2.0)

trader_sar — Parabolic SAR

### Description

trader_sar(
array `$high`,
array `$low`,
float `$acceleration` = ?,
float `$maximum` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`acceleration`

  Acceleration Factor used up to the Maximum value. Valid range from 0 to TRADER_REAL_MAX.

`maximum`

  Acceleration Factor Maximum value. Valid range from 0 to TRADER_REAL_MAX.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sarext

(PECL trader >= 0.2.0)

trader_sarext — Parabolic SAR - Extended

### Description

trader_sarext(
array `$high`,
array `$low`,
float `$startValue` = ?,
float `$offsetOnReverse` = ?,
float `$accelerationInitLong` = ?,
float `$accelerationLong` = ?,
float `$accelerationMaxLong` = ?,
float `$accelerationInitShort` = ?,
float `$accelerationShort` = ?,
float `$accelerationMaxShort` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`startValue`

  Start value and direction. 0 for Auto, >0 for Long, <0 for Short. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

`offsetOnReverse`

  Percent offset added/removed to initial stop on short/long reversal. Valid range from 0 to TRADER_REAL_MAX.

`accelerationInitLong`

  Acceleration Factor initial value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

`accelerationLong`

  Acceleration Factor for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

`accelerationMaxLong`

  Acceleration Factor maximum value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

`accelerationInitShort`

  Acceleration Factor initial value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

`accelerationShort`

  Acceleration Factor for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

`accelerationMaxShort`

  Acceleration Factor maximum value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

### Return Values

Returns an array with calculated data or false on failure.

# trader_set_compat

(PECL trader >= 0.2.2)

trader_set_compat — Set compatibility mode

### Description

trader_set_compat(int `$compatId`): void

Set compatibility mode which will affect the way calculations are done by all the extension functions.

### Parameters

`compatId`

  Compatibility Id. TRADER_COMPATIBILITY_* series of constants should be used.

### Return Values

No value is returned.

# trader_set_unstable_period

(PECL trader >= 0.2.2)

trader_set_unstable_period — Set unstable period

### Description

trader_set_unstable_period(int `$functionId`, int `$timePeriod`): void

Influences unstable period factor for functions, which are sensible to it. More information about unstable periods can be found on the » TA-Lib API documentation page.

### Parameters

`functionId`

  Function ID the factor should be set for. TRADER_FUNC_UNST_* constant series can be used to affect the corresponding function.

`timePeriod`

  Unstable period value.

### Return Values

No value is returned.

# trader_sin

(PECL trader >= 0.2.0)

trader_sin — Vector Trigonometric Sin

### Description

trader_sin(array `$real`): array

Calculates the sine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sinh

(PECL trader >= 0.2.0)

trader_sinh — Vector Trigonometric Sinh

### Description

trader_sinh(array `$real`): array

Calculates the hyperbolic sine for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sma

(PECL trader >= 0.2.0)

trader_sma — Simple Moving Average

### Description

trader_sma(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sqrt

(PECL trader >= 0.2.0)

trader_sqrt — Vector Square Root

### Description

trader_sqrt(array `$real`): array

Calculates the square root of each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_stddev

(PECL trader >= 0.2.0)

trader_stddev — Standard Deviation

### Description

trader_stddev(array `$real`, int `$timePeriod` = ?, float `$nbDev` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`nbDev`

### Return Values

Returns an array with calculated data or false on failure.

# trader_stoch

(PECL trader >= 0.2.0)

trader_stoch — Stochastic

### Description

trader_stoch(
array `$high`,
array `$low`,
array `$close`,
int `$fastK_Period` = ?,
int `$slowK_Period` = ?,
int `$slowK_MAType` = ?,
int `$slowD_Period` = ?,
int `$slowD_MAType` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`fastK_Period`

  Time period for building the Fast-K line. Valid range from 1 to 100000.

`slowK_Period`

  Smoothing for making the Slow-K line. Valid range from 1 to 100000, usually set to 3.

`slowK_MAType`

  Type of Moving Average for Slow-K. TRADER_MA_TYPE_* series of constants should be used.

`slowD_Period`

  Smoothing for making the Slow-D line. Valid range from 1 to 100000.

`slowD_MAType`

  Type of Moving Average for Slow-D. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_stochf

(PECL trader >= 0.2.0)

trader_stochf — Stochastic Fast

### Description

trader_stochf(
array `$high`,
array `$low`,
array `$close`,
int `$fastK_Period` = ?,
int `$fastD_Period` = ?,
int `$fastD_MAType` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`fastK_Period`

  Time period for building the Fast-K line. Valid range from 1 to 100000.

`fastD_Period`

  Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

`fastD_MAType`

  Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_stochrsi

(PECL trader >= 0.2.0)

trader_stochrsi — Stochastic Relative Strength Index

### Description

trader_stochrsi(
array `$real`,
int `$timePeriod` = ?,
int `$fastK_Period` = ?,
int `$fastD_Period` = ?,
int `$fastD_MAType` = ?
): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`fastK_Period`

  Time period for building the Fast-K line. Valid range from 1 to 100000.

`fastD_Period`

  Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

`fastD_MAType`

  Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sub

(PECL trader >= 0.2.0)

trader_sub — Vector Arithmetic Subtraction

### Description

trader_sub(array `$real0`, array `$real1`): array

Calculates the vector subtraction of `real1` from `real0` and returns the resulting vector.

### Parameters

`real0`

  Array of real values.

`real1`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_sum

(PECL trader >= 0.2.0)

trader_sum — Summation

### Description

trader_sum(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_t3

(PECL trader >= 0.2.0)

trader_t3 — Triple Exponential Moving Average (T3)

### Description

trader_t3(array `$real`, int `$timePeriod` = ?, float `$vFactor` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`vFactor`

  Volume Factor. Valid range from 1 to 0.

### Return Values

Returns an array with calculated data or false on failure.

# trader_tan

(PECL trader >= 0.2.0)

trader_tan — Vector Trigonometric Tan

### Description

trader_tan(array `$real`): array

Calculates the tangent for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_tanh

(PECL trader >= 0.2.0)

trader_tanh — Vector Trigonometric Tanh

### Description

trader_tanh(array `$real`): array

Calculates the hyperbolic tangent for each value in `real` and returns the resulting array.

### Parameters

`real`

  Array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_tema

(PECL trader >= 0.2.0)

trader_tema — Triple Exponential Moving Average

### Description

trader_tema(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_trange

(PECL trader >= 0.2.0)

trader_trange — True Range

### Description

trader_trange(array `$high`, array `$low`, array `$close`): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_trima

(PECL trader >= 0.2.0)

trader_trima — Triangular Moving Average

### Description

trader_trima(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_trix

(PECL trader >= 0.2.0)

trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

### Description

trader_trix(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_tsf

(PECL trader >= 0.2.0)

trader_tsf — Time Series Forecast

### Description

trader_tsf(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_typprice

(PECL trader >= 0.2.0)

trader_typprice — Typical Price

### Description

trader_typprice(array `$high`, array `$low`, array `$close`): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_ultosc

(PECL trader >= 0.2.0)

trader_ultosc — Ultimate Oscillator

### Description

trader_ultosc(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod1` = ?,
int `$timePeriod2` = ?,
int `$timePeriod3` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod1`

  Number of bars for 1st period. Valid range from 1 to 100000.

`timePeriod2`

  Number of bars for 2nd period. Valid range from 1 to 100000.

`timePeriod3`

  Number of bars for 3rd period. Valid range from 1 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_var

(PECL trader >= 0.2.0)

trader_var — Variance

### Description

trader_var(array `$real`, int `$timePeriod` = ?, float `$nbDev` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

`nbDev`

### Return Values

Returns an array with calculated data or false on failure.

# trader_wclprice

(PECL trader >= 0.2.0)

trader_wclprice — Weighted Close Price

### Description

trader_wclprice(array `$high`, array `$low`, array `$close`): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

### Return Values

Returns an array with calculated data or false on failure.

# trader_willr

(PECL trader >= 0.2.0)

trader_willr — Williams' %R

### Description

trader_willr(
array `$high`,
array `$low`,
array `$close`,
int `$timePeriod` = ?
): array

### Parameters

`high`

  High price, array of real values.

`low`

  Low price, array of real values.

`close`

  Closing price, array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

# trader_wma

(PECL trader >= 0.2.0)

trader_wma — Weighted Moving Average

### Description

trader_wma(array `$real`, int `$timePeriod` = ?): array

### Parameters

`real`

  Array of real values.

`timePeriod`

  Number of period. Valid range from 2 to 100000.

### Return Values

Returns an array with calculated data or false on failure.

## Table of Contents

- trader_acos — Vector Trigonometric ACos
- trader_ad — Chaikin A/D Line
- trader_add — Vector Arithmetic Add
- trader_adosc — Chaikin A/D Oscillator
- trader_adx — Average Directional Movement Index
- trader_adxr — Average Directional Movement Index Rating
- trader_apo — Absolute Price Oscillator
- trader_aroon — Aroon
- trader_aroonosc — Aroon Oscillator
- trader_asin — Vector Trigonometric ASin
- trader_atan — Vector Trigonometric ATan
- trader_atr — Average True Range
- trader_avgprice — Average Price
- trader_bbands — Bollinger Bands
- trader_beta — Beta
- trader_bop — Balance Of Power
- trader_cci — Commodity Channel Index
- trader_cdl2crows — Two Crows
- trader_cdl3blackcrows — Three Black Crows
- trader_cdl3inside — Three Inside Up/Down
- trader_cdl3linestrike — Three-Line Strike
- trader_cdl3outside — Three Outside Up/Down
- trader_cdl3starsinsouth — Three Stars In The South
- trader_cdl3whitesoldiers — Three Advancing White Soldiers
- trader_cdlabandonedbaby — Abandoned Baby
- trader_cdladvanceblock — Advance Block
- trader_cdlbelthold — Belt-hold
- trader_cdlbreakaway — Breakaway
- trader_cdlclosingmarubozu — Closing Marubozu
- trader_cdlconcealbabyswall — Concealing Baby Swallow
- trader_cdlcounterattack — Counterattack
- trader_cdldarkcloudcover — Dark Cloud Cover
- trader_cdldoji — Doji
- trader_cdldojistar — Doji Star
- trader_cdldragonflydoji — Dragonfly Doji
- trader_cdlengulfing — Engulfing Pattern
- trader_cdleveningdojistar — Evening Doji Star
- trader_cdleveningstar — Evening Star
- trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
- trader_cdlgravestonedoji — Gravestone Doji
- trader_cdlhammer — Hammer
- trader_cdlhangingman — Hanging Man
- trader_cdlharami — Harami Pattern
- trader_cdlharamicross — Harami Cross Pattern
- trader_cdlhighwave — High-Wave Candle
- trader_cdlhikkake — Hikkake Pattern
- trader_cdlhikkakemod — Modified Hikkake Pattern
- trader_cdlhomingpigeon — Homing Pigeon
- trader_cdlidentical3crows — Identical Three Crows
- trader_cdlinneck — In-Neck Pattern
- trader_cdlinvertedhammer — Inverted Hammer
- trader_cdlkicking — Kicking
- trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
- trader_cdlladderbottom — Ladder Bottom
- trader_cdllongleggeddoji — Long Legged Doji
- trader_cdllongline — Long Line Candle
- trader_cdlmarubozu — Marubozu
- trader_cdlmatchinglow — Matching Low
- trader_cdlmathold — Mat Hold
- trader_cdlmorningdojistar — Morning Doji Star
- trader_cdlmorningstar — Morning Star
- trader_cdlonneck — On-Neck Pattern
- trader_cdlpiercing — Piercing Pattern
- trader_cdlrickshawman — Rickshaw Man
- trader_cdlrisefall3methods — Rising/Falling Three Methods
- trader_cdlseparatinglines — Separating Lines
- trader_cdlshootingstar — Shooting Star
- trader_cdlshortline — Short Line Candle
- trader_cdlspinningtop — Spinning Top
- trader_cdlstalledpattern — Stalled Pattern
- trader_cdlsticksandwich — Stick Sandwich
- trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
- trader_cdltasukigap — Tasuki Gap
- trader_cdlthrusting — Thrusting Pattern
- trader_cdltristar — Tristar Pattern
- trader_cdlunique3river — Unique 3 River
- trader_cdlupsidegap2crows — Upside Gap Two Crows
- trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
- trader_ceil — Vector Ceil
- trader_cmo — Chande Momentum Oscillator
- trader_correl — Pearson's Correlation Coefficient (r)
- trader_cos — Vector Trigonometric Cos
- trader_cosh — Vector Trigonometric Cosh
- trader_dema — Double Exponential Moving Average
- trader_div — Vector Arithmetic Div
- trader_dx — Directional Movement Index
- trader_ema — Exponential Moving Average
- trader_errno — Get error code
- trader_exp — Vector Arithmetic Exp
- trader_floor — Vector Floor
- trader_get_compat — Get compatibility mode
- trader_get_unstable_period — Get unstable period
- trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
- trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
- trader_ht_phasor — Hilbert Transform - Phasor Components
- trader_ht_sine — Hilbert Transform - SineWave
- trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
- trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
- trader_kama — Kaufman Adaptive Moving Average
- trader_linearreg — Linear Regression
- trader_linearreg_angle — Linear Regression Angle
- trader_linearreg_intercept — Linear Regression Intercept
- trader_linearreg_slope — Linear Regression Slope
- trader_ln — Vector Log Natural
- trader_log10 — Vector Log10
- trader_ma — Moving average
- trader_macd — Moving Average Convergence/Divergence
- trader_macdext — MACD with controllable MA type
- trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
- trader_mama — MESA Adaptive Moving Average
- trader_mavp — Moving average with variable period
- trader_max — Highest value over a specified period
- trader_maxindex — Index of highest value over a specified period
- trader_medprice — Median Price
- trader_mfi — Money Flow Index
- trader_midpoint — MidPoint over period
- trader_midprice — Midpoint Price over period
- trader_min — Lowest value over a specified period
- trader_minindex — Index of lowest value over a specified period
- trader_minmax — Lowest and highest values over a specified period
- trader_minmaxindex — Indexes of lowest and highest values over a specified period
- trader_minus_di — Minus Directional Indicator
- trader_minus_dm — Minus Directional Movement
- trader_mom — Momentum
- trader_mult — Vector Arithmetic Mult
- trader_natr — Normalized Average True Range
- trader_obv — On Balance Volume
- trader_plus_di — Plus Directional Indicator
- trader_plus_dm — Plus Directional Movement
- trader_ppo — Percentage Price Oscillator
- trader_roc — Rate of change : ((price/prevPrice)-1)*100
- trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
- trader_rocr — Rate of change ratio: (price/prevPrice)
- trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
- trader_rsi — Relative Strength Index
- trader_sar — Parabolic SAR
- trader_sarext — Parabolic SAR - Extended
- trader_set_compat — Set compatibility mode
- trader_set_unstable_period — Set unstable period
- trader_sin — Vector Trigonometric Sin
- trader_sinh — Vector Trigonometric Sinh
- trader_sma — Simple Moving Average
- trader_sqrt — Vector Square Root
- trader_stddev — Standard Deviation
- trader_stoch — Stochastic
- trader_stochf — Stochastic Fast
- trader_stochrsi — Stochastic Relative Strength Index
- trader_sub — Vector Arithmetic Subtraction
- trader_sum — Summation
- trader_t3 — Triple Exponential Moving Average (T3)
- trader_tan — Vector Trigonometric Tan
- trader_tanh — Vector Trigonometric Tanh
- trader_tema — Triple Exponential Moving Average
- trader_trange — True Range
- trader_trima — Triangular Moving Average
- trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
- trader_tsf — Time Series Forecast
- trader_typprice — Typical Price
- trader_ultosc — Ultimate Oscillator
- trader_var — Variance
- trader_wclprice — Weighted Close Price
- trader_willr — Williams' %R
- trader_wma — Weighted Moving Average

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- Predefined Constants
- Trader Functions
  - trader_acos — Vector Trigonometric ACos
  - trader_ad — Chaikin A/D Line
  - trader_add — Vector Arithmetic Add
  - trader_adosc — Chaikin A/D Oscillator
  - trader_adx — Average Directional Movement Index
  - trader_adxr — Average Directional Movement Index Rating
  - trader_apo — Absolute Price Oscillator
  - trader_aroon — Aroon
  - trader_aroonosc — Aroon Oscillator
  - trader_asin — Vector Trigonometric ASin
  - trader_atan — Vector Trigonometric ATan
  - trader_atr — Average True Range
  - trader_avgprice — Average Price
  - trader_bbands — Bollinger Bands
  - trader_beta — Beta
  - trader_bop — Balance Of Power
  - trader_cci — Commodity Channel Index
  - trader_cdl2crows — Two Crows
  - trader_cdl3blackcrows — Three Black Crows
  - trader_cdl3inside — Three Inside Up/Down
  - trader_cdl3linestrike — Three-Line Strike
  - trader_cdl3outside — Three Outside Up/Down
  - trader_cdl3starsinsouth — Three Stars In The South
  - trader_cdl3whitesoldiers — Three Advancing White Soldiers
  - trader_cdlabandonedbaby — Abandoned Baby
  - trader_cdladvanceblock — Advance Block
  - trader_cdlbelthold — Belt-hold
  - trader_cdlbreakaway — Breakaway
  - trader_cdlclosingmarubozu — Closing Marubozu
  - trader_cdlconcealbabyswall — Concealing Baby Swallow
  - trader_cdlcounterattack — Counterattack
  - trader_cdldarkcloudcover — Dark Cloud Cover
  - trader_cdldoji — Doji
  - trader_cdldojistar — Doji Star
  - trader_cdldragonflydoji — Dragonfly Doji
  - trader_cdlengulfing — Engulfing Pattern
  - trader_cdleveningdojistar — Evening Doji Star
  - trader_cdleveningstar — Evening Star
  - trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
  - trader_cdlgravestonedoji — Gravestone Doji
  - trader_cdlhammer — Hammer
  - trader_cdlhangingman — Hanging Man
  - trader_cdlharami — Harami Pattern
  - trader_cdlharamicross — Harami Cross Pattern
  - trader_cdlhighwave — High-Wave Candle
  - trader_cdlhikkake — Hikkake Pattern
  - trader_cdlhikkakemod — Modified Hikkake Pattern
  - trader_cdlhomingpigeon — Homing Pigeon
  - trader_cdlidentical3crows — Identical Three Crows
  - trader_cdlinneck — In-Neck Pattern
  - trader_cdlinvertedhammer — Inverted Hammer
  - trader_cdlkicking — Kicking
  - trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
  - trader_cdlladderbottom — Ladder Bottom
  - trader_cdllongleggeddoji — Long Legged Doji
  - trader_cdllongline — Long Line Candle
  - trader_cdlmarubozu — Marubozu
  - trader_cdlmatchinglow — Matching Low
  - trader_cdlmathold — Mat Hold
  - trader_cdlmorningdojistar — Morning Doji Star
  - trader_cdlmorningstar — Morning Star
  - trader_cdlonneck — On-Neck Pattern
  - trader_cdlpiercing — Piercing Pattern
  - trader_cdlrickshawman — Rickshaw Man
  - trader_cdlrisefall3methods — Rising/Falling Three Methods
  - trader_cdlseparatinglines — Separating Lines
  - trader_cdlshootingstar — Shooting Star
  - trader_cdlshortline — Short Line Candle
  - trader_cdlspinningtop — Spinning Top
  - trader_cdlstalledpattern — Stalled Pattern
  - trader_cdlsticksandwich — Stick Sandwich
  - trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
  - trader_cdltasukigap — Tasuki Gap
  - trader_cdlthrusting — Thrusting Pattern
  - trader_cdltristar — Tristar Pattern
  - trader_cdlunique3river — Unique 3 River
  - trader_cdlupsidegap2crows — Upside Gap Two Crows
  - trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
  - trader_ceil — Vector Ceil
  - trader_cmo — Chande Momentum Oscillator
  - trader_correl — Pearson's Correlation Coefficient (r)
  - trader_cos — Vector Trigonometric Cos
  - trader_cosh — Vector Trigonometric Cosh
  - trader_dema — Double Exponential Moving Average
  - trader_div — Vector Arithmetic Div
  - trader_dx — Directional Movement Index
  - trader_ema — Exponential Moving Average
  - trader_errno — Get error code
  - trader_exp — Vector Arithmetic Exp
  - trader_floor — Vector Floor
  - trader_get_compat — Get compatibility mode
  - trader_get_unstable_period — Get unstable period
  - trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
  - trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
  - trader_ht_phasor — Hilbert Transform - Phasor Components
  - trader_ht_sine — Hilbert Transform - SineWave
  - trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
  - trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
  - trader_kama — Kaufman Adaptive Moving Average
  - trader_linearreg — Linear Regression
  - trader_linearreg_angle — Linear Regression Angle
  - trader_linearreg_intercept — Linear Regression Intercept
  - trader_linearreg_slope — Linear Regression Slope
  - trader_ln — Vector Log Natural
  - trader_log10 — Vector Log10
  - trader_ma — Moving average
  - trader_macd — Moving Average Convergence/Divergence
  - trader_macdext — MACD with controllable MA type
  - trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
  - trader_mama — MESA Adaptive Moving Average
  - trader_mavp — Moving average with variable period
  - trader_max — Highest value over a specified period
  - trader_maxindex — Index of highest value over a specified period
  - trader_medprice — Median Price
  - trader_mfi — Money Flow Index
  - trader_midpoint — MidPoint over period
  - trader_midprice — Midpoint Price over period
  - trader_min — Lowest value over a specified period
  - trader_minindex — Index of lowest value over a specified period
  - trader_minmax — Lowest and highest values over a specified period
  - trader_minmaxindex — Indexes of lowest and highest values over a specified period
  - trader_minus_di — Minus Directional Indicator
  - trader_minus_dm — Minus Directional Movement
  - trader_mom — Momentum
  - trader_mult — Vector Arithmetic Mult
  - trader_natr — Normalized Average True Range
  - trader_obv — On Balance Volume
  - trader_plus_di — Plus Directional Indicator
  - trader_plus_dm — Plus Directional Movement
  - trader_ppo — Percentage Price Oscillator
  - trader_roc — Rate of change : ((price/prevPrice)-1)*100
  - trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
  - trader_rocr — Rate of change ratio: (price/prevPrice)
  - trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
  - trader_rsi — Relative Strength Index
  - trader_sar — Parabolic SAR
  - trader_sarext — Parabolic SAR - Extended
  - trader_set_compat — Set compatibility mode
  - trader_set_unstable_period — Set unstable period
  - trader_sin — Vector Trigonometric Sin
  - trader_sinh — Vector Trigonometric Sinh
  - trader_sma — Simple Moving Average
  - trader_sqrt — Vector Square Root
  - trader_stddev — Standard Deviation
  - trader_stoch — Stochastic
  - trader_stochf — Stochastic Fast
  - trader_stochrsi — Stochastic Relative Strength Index
  - trader_sub — Vector Arithmetic Subtraction
  - trader_sum — Summation
  - trader_t3 — Triple Exponential Moving Average (T3)
  - trader_tan — Vector Trigonometric Tan
  - trader_tanh — Vector Trigonometric Tanh
  - trader_tema — Triple Exponential Moving Average
  - trader_trange — True Range
  - trader_trima — Triangular Moving Average
  - trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
  - trader_tsf — Time Series Forecast
  - trader_typprice — Typical Price
  - trader_ultosc — Ultimate Oscillator
  - trader_var — Variance
  - trader_wclprice — Weighted Close Price
  - trader_willr — Williams' %R
  - trader_wma — Weighted Moving Average

- BC Math — BCMath Arbitrary Precision Mathematics
  - Installing/Configuring
  - BC Math Functions
  - BcMath\Number — The BcMath\Number class
- GMP — GNU Multiple Precision
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - GMP Functions
  - GMP — The GMP class
- Math — Mathematical Functions
  - Predefined Constants
  - RoundingMode — The RoundingMode Enum
  - Math Functions
- Statistics
  - Installing/Configuring
  - Statistic Functions
- Trader — Technical Analysis for Traders
  - Installing/Configuring
  - Predefined Constants
  - Trader Functions

# Non-Text MIME Output

# Forms Data Format

# Introduction

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at » http://www.adobe.com/devnet/acrobat/fdftoolkit.html for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType `application/vnd.fdf`. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name `FDF`. Such an object may contain a number of entries like `Fields`, `F`, `Status` etc.. The most commonly used entries are `Fields` which points to a list of input fields, and `F` which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

You need the FDF toolkit SDK available from » http://www.adobe.com/devnet/acrobat/fdftoolkit.html. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.

## Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » https://svn.php.net/viewvc/pecl/fdf.

This extension is no longer bundled with PHP.

> Note: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local.

> Note: Note to Win32 Users
> In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: fdftk.dll

## Resource Types

Most fdf functions require a `fdf` resource as their first parameter. A `fdf` resource is a handle to an opened fdf file. `fdf` resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().

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

`FDFValue` (int)
`FDFStatus` (int)
`FDFFile` (int)
`FDFID` (int)
`FDFFf` (int)
`FDFSetFf` (int)
`FDFClearFf` (int)
`FDFFlags` (int)
`FDFSetF` (int)
`FDFClrF` (int)
`FDFAP` (int)
`FDFAS` (int)
`FDFAction` (int)
`FDFAA` (int)
`FDFAPRef` (int)
`FDFIF` (int)
`FDFEnter` (int)
`FDFExit` (int)
`FDFDown` (int)
`FDFUp` (int)
`FDFFormat` (int)
`FDFValidate` (int)
`FDFKeystroke` (int)
`FDFCalculate` (int)
`FDFNormalAP` (int)
`FDFRolloverAP` (int)
`FDFDownAP` (int)

# Examples

The following examples shows just the evaluation of form data.

Example #1 Evaluating a FDF document

`<?php
// Open fdf from input string provided by the extension
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<b>$volume</b>'<br />";
$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<b>$date</b>'<br />";
$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<b>$comment</b>'<br />";
if (fdf_get_value($fdf, "show_publisher") == "On") {
$publisher = fdf_get_value($fdf, "publisher");
echo "The publisher field has the value '<b>$publisher</b>'<br />";
} else
echo "Publisher shall not be shown.<br />";
if (fdf_get_value($fdf, "show_preparer") == "On") {
$preparer = fdf_get_value($fdf, "preparer");
echo "The preparer field has the value '<b>$preparer</b>'<br />";
} else
echo "Preparer shall not be shown.<br />";
fdf_close($fdf);
?>`

# FDF Functions

# fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_add_doc_javascript — Adds javascript code to the FDF document

### Description

fdf_add_doc_javascript(resource `$fdf_document`, string `$script_name`, string `$script_code`): bool

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`script_name`
  The script name.
`script_code`
  The script code. It is strongly suggested to use `\r` for linebreaks within the script code.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Adding JavaScript code to a FDF

`<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r return x+1;\r}\r");
fdf_save($fdf);
?>`

will create a FDF like this:

    %FDF-1.2
    %âãÏÓ
    1 0 obj
    <<
    /FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
    >>
    endobj
    trailer
    <<
    /Root 1 0 R

    >>
    %%EOF

# fdf_add_template

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_add_template — Adds a template into the FDF document

### Description

fdf_add_template(
resource `$fdf_document`,
int `$newpage`,
string `$filename`,
string `$template`,
int `$rename`
): bool
Warning

This function is currently not documented; only its argument list is available.

# fdf_close

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_close — Close an FDF document

### Description

fdf_close(resource `$fdf_document`): void

Closes the FDF document.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

No value is returned.

### See Also

- fdf_open() - Open a FDF document

# fdf_create

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_create — Create a new FDF document

### Description

fdf_create(): resource

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

### Parameters

This function has no parameters.

### Return Values

Returns a FDF document handle, or `false` on error.

### Examples

Example #1 Populating a PDF document

`<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);
fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>`

### See Also

- fdf_close() - Close an FDF document
- fdf_save() - Save a FDF document
- fdf_open() - Open a FDF document

# fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_enum_values — Call a user defined function for each document value

### Description

fdf_enum_values(resource `$fdf_document`, callable `$function`, mixed `$userdata` = ?): bool
Warning

This function is currently not documented; only its argument list is available.

# fdf_errno

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_errno — Return error code for last fdf operation

### Description

fdf_errno(): int

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

### Parameters

This function has no parameters.

### Return Values

Returns the error code as an integer, or zero if there was no errors.

### See Also

- fdf_error() - Return error description for FDF error code

# fdf_error

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_error — Return error description for FDF error code

### Description

fdf_error(int `$error_code` = -1): string

Gets a textual description for the FDF error code given in `error_code`.

### Parameters

`error_code`
  An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

### Return Values

Returns the error message as a string, or the string `no error` if nothing went wrong.

### See Also

- fdf_errno() - Return error code for last fdf operation

# fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_ap — Get the appearance of a field

### Description

fdf_get_ap(
resource `$fdf_document`,
string `$field`,
int `$face`,
string `$filename`
): bool

Gets the appearance of a `field` (i.e. the value of the /AP key) and stores it in a file.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`field`
`face`
  The possible values are `FDFNormalAP`, `FDFRolloverAP` and `FDFDownAP`.
`filename`
  The appearance will be stored in this parameter.

### Return Values

Returns `true` on success or `false` on failure.

# fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

### Description

fdf_get_attachment(resource `$fdf_document`, string `$fieldname`, string `$savepath`): array

Extracts a file uploaded by means of the "file selection" field `fieldname` and stores it under `savepath`.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
`savepath`
  May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

  > Note: There seems to be no other way to find out the original filename but to store the file using a directory as `savepath` and check for the basename it was stored under.

### Return Values

The returned array contains the following fields:

- `path` - path were the file got stored
- `size` - size of the stored file in bytes
- `type` - mimetype if given in the FDF

### Examples

Example #1 Storing an uploaded file

`<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
$data = fdf_get_attachment($fdf, "filename", "/tmpdir");
echo "The uploaded file is stored in $data[path]";
?>`

# fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_encoding — Get the value of the /Encoding key

### Description

fdf_get_encoding(resource `$fdf_document`): string

Gets the value of the `/Encoding` key.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

Returns the encoding as a string. An empty string is returned if the default `PDFDocEncoding/Unicode` scheme is used.

### See Also

- fdf_set_encoding() - Sets FDF character encoding

# fdf_get_file

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_file — Get the value of the /F key

### Description

fdf_get_file(resource `$fdf_document`): string

Gets the value of the `/F` key.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

Returns the key value, as a string.

### See Also

- fdf_set_file() - Set PDF document to display FDF data in

# fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_flags — Gets the flags of a field

### Description

fdf_get_flags(resource `$fdf_document`, string `$fieldname`, int `$whichflags`): int
Warning

This function is currently not documented; only its argument list is available.

# fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECLv)

fdf_get_opt — Gets a value from the opt array of a field

### Description

fdf_get_opt(resource `$fdf_document`, string `$fieldname`, int `$element` = -1): mixed
Warning

This function is currently not documented; only its argument list is available.

# fdf_get_status

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_status — Get the value of the /STATUS key

### Description

fdf_get_status(resource `$fdf_document`): string

Gets the value of the `/STATUS` key.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

Returns the key value, as a string.

### See Also

- fdf_set_status() - Set the value of the /STATUS key

# fdf_get_value

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_value — Get the value of a field

### Description

fdf_get_value(resource `$fdf_document`, string `$fieldname`, int `$which` = -1): mixed

Gets the value for the requested field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`which`
  Elements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.

### Return Values

Returns the field value.

### See Also

- fdf_set_value() - Set the value of a field

# fdf_get_version

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_version — Gets version number for FDF API or file

### Description

fdf_get_version(resource `$fdf_document` = ?): string

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

Returns the version as a string. For the current FDF toolkit 5.0 the API version number is `5.0` and the document version number is either `1.2`, `1.3` or `1.4`.

### See Also

- fdf_set_version() - Sets version number for a FDF file

# fdf_header

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVNf)

fdf_header — Sets FDF-specific output headers

### Description

fdf_header(): void

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the `Content-type:` to `application/vnd.fdf`.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# fdf_next_field_name

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_next_field_name — Get the next field name

### Description

fdf_next_field_name(resource `$fdf_document`, string `$fieldname` = ?): string

Gets the name of the field after the given field. This name can be used with several functions.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string. If not given, the first field will be assumed.

### Return Values

Returns the field name as a string.

### Examples

Example #1 Detecting all fieldnames in a FDF

`<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf);
$field != "";
$field = fdf_next_field_name($fdf, $field)) {
echo "field: $field\n";
}
?>`

### See Also

- fdf_get_value() - Get the value of a field

# fdf_open

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_open — Open a FDF document

### Description

fdf_open(string `$filename`): resource

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

### Parameters

`filename`
  Path to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

### Return Values

Returns a FDF document handle, or `false` on error.

### Examples

Example #1 Accessing the form data

`<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);
// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
/* ... */
fdf_close($fdf);
?>`

### See Also

- fdf_open_string() - Read a FDF document from a string
- fdf_close() - Close an FDF document
- fdf_create() - Create a new FDF document
- fdf_save() - Save a FDF document

# fdf_open_string

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_open_string — Read a FDF document from a string

### Description

fdf_open_string(string `$fdf_data`): resource

Reads form data from a string.

You can use fdf_open_string() together with $HTTP_FDF_DATA to process FDF form input from a remote client.

### Parameters

`fdf_data`
  The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

### Return Values

Returns a FDF document handle, or `false` on error.

### Examples

Example #1 Accessing the form data

`<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>`

### See Also

- fdf_open() - Open a FDF document
- fdf_close() - Close an FDF document
- fdf_create() - Create a new FDF document
- fdf_save_string() - Returns the FDF document as a string

# fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_remove_item — Sets target frame for form

### Description

fdf_remove_item(resource `$fdf_document`, string `$fieldname`, int `$item`): bool
Warning

This function is currently not documented; only its argument list is available.

# fdf_save

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_save — Save a FDF document

### Description

fdf_save(resource `$fdf_document`, string `$filename` = ?): bool

Saves a FDF document.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`filename`
  If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_close() - Close an FDF document
- fdf_create() - Create a new FDF document
- fdf_save_string() - Returns the FDF document as a string

# fdf_save_string

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_save_string — Returns the FDF document as a string

### Description

fdf_save_string(resource `$fdf_document`): string

Returns the FDF document as a string.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

### Return Values

Returns the document as a string, or `false` on error.

### Examples

Example #1 Retrieving FDF as a string

`<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>`

The above example will output:

    %FDF-1.2
    %âãÏÓ
    1 0 obj
    <<
    /FDF << /Fields 2 0 R >>
    >>
    endobj
    2 0 obj
    [
    << /T (foo)/V (bar)>>
    ]
    endobj
    trailer
    <<
    /Root 1 0 R

    >>
    %%EOF

### See Also

- fdf_open_string() - Read a FDF document from a string
- fdf_close() - Close an FDF document
- fdf_create() - Create a new FDF document
- fdf_save() - Save a FDF document

# fdf_set_ap

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_ap — Set the appearance of a field

### Description

fdf_set_ap(
resource `$fdf_document`,
string `$field_name`,
int `$face`,
string `$filename`,
int `$page_number`
): bool

Sets the appearance of a field (i.e. the value of the `/AP` key).

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`field_name`
`face`
  The possible values `FDFNormalAP`, `FDFRolloverAP` and `FDFDownAP`.
`filename`
`page_number`

### Return Values

Returns `true` on success or `false` on failure.

# fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_encoding — Sets FDF character encoding

### Description

fdf_set_encoding(resource `$fdf_document`, string `$encoding`): bool

Sets the character encoding for the FDF document.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`encoding`
  The encoding name. The following values are supported: "`Shift-JIS`", "`UHC`", "`GBK`" and "`BigFive`". An empty string resets the encoding to the default `PDFDocEncoding/Unicode` scheme.

### Return Values

Returns `true` on success or `false` on failure.

# fdf_set_file

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_file — Set PDF document to display FDF data in

### Description

fdf_set_file(resource `$fdf_document`, string `$url`, string `$target_frame` = ?): bool

Selects a different PDF document to display the form results in then the form it originated from.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`url`
  Should be given as an absolute URL.
`target_frame`
  Use this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Passing FDF data to a second form

`<?php
/* set content type for Adobe FDF */
fdf_header();
/* start new fdf */
$fdf = fdf_create();
/* set field "foo" to value "bar" */
fdf_set_value($fdf, "foo", "bar");
/* tell client to display FDF data using "fdf_form.pdf" */
fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");
/* output fdf */
fdf_save($fdf);
/* clean up */
fdf_close($fdf);
?>`

### See Also

- fdf_get_file() - Get the value of the /F key
- fdf_set_target_frame() - Set target frame for form display

# fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_flags — Sets a flag of a field

### Description

fdf_set_flags(
resource `$fdf_document`,
string `$fieldname`,
int `$whichFlags`,
int `$newFlags`
): bool

Sets certain flags of the given field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`whichFlags`
`newFlags`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_set_opt() - Sets an option of a field

# fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_javascript_action — Sets an javascript action of a field

### Description

fdf_set_javascript_action(
resource `$fdf_document`,
string `$fieldname`,
int `$trigger`,
string `$script`
): bool

Sets a javascript action for the given field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`trigger`
`script`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_set_submit_form_action() - Sets a submit form action of a field

# fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

### Description

fdf_set_on_import_javascript(resource `$fdf_document`, string `$script`, bool `$before_data_import`): bool
Warning

This function is currently not documented; only its argument list is available.

### See Also

- fdf_add_doc_javascript() - Adds javascript code to the FDF document
- fdf_set_javascript_action() - Sets an javascript action of a field

# fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_opt — Sets an option of a field

### Description

fdf_set_opt(
resource `$fdf_document`,
string `$fieldname`,
int `$element`,
string `$str1`,
string `$str2`
): bool

Sets options of the given field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`element`
`str1`
`str2`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_set_flags() - Sets a flag of a field

# fdf_set_status

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_status — Set the value of the /STATUS key

### Description

fdf_set_status(resource `$fdf_document`, string `$status`): bool

Sets the value of the `/STATUS` key. When a client receives a FDF with a status set it will present the value in an alert box.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`status`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_get_status() - Get the value of the /STATUS key

# fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_submit_form_action — Sets a submit form action of a field

### Description

fdf_set_submit_form_action(
resource `$fdf_document`,
string `$fieldname`,
int `$trigger`,
string `$script`,
int `$flags`
): bool

Sets a submit form action for the given field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`trigger`
`script`
`flags`

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_set_javascript_action() - Sets an javascript action of a field

# fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_target_frame — Set target frame for form display

### Description

fdf_set_target_frame(resource `$fdf_document`, string `$frame_name`): bool

Sets the target frame to display a result PDF defined with fdf_save_file() in.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`frame_name`
  The frame name, as a string.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_save_file()

# fdf_set_value

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_value — Set the value of a field

### Description

fdf_set_value(
resource `$fdf_document`,
string `$fieldname`,
mixed `$value`,
int `$isName` = ?
): bool

Sets the `value` for the given field.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`fieldname`
  Name of the FDF field, as a string.
`value`
  This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.
`isName`

  > Note: In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0). The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter, but ignored internally.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_get_value() - Get the value of a field
- fdf_remove_item() - Sets target frame for form

# fdf_set_version

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_version — Sets version number for a FDF file

### Description

fdf_set_version(resource `$fdf_document`, string `$version`): bool

Sets the FDF `version` for the given document.

Some features supported by this extension are only available in newer FDF versions.

### Parameters

`fdf_document`
  The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
`version`
  The version number. For the current FDF toolkit 5.0, this may be either `1.2`, `1.3` or `1.4`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- fdf_get_version() - Gets version number for FDF API or file

## Table of Contents

- fdf_add_doc_javascript — Adds javascript code to the FDF document
- fdf_add_template — Adds a template into the FDF document
- fdf_close — Close an FDF document
- fdf_create — Create a new FDF document
- fdf_enum_values — Call a user defined function for each document value
- fdf_errno — Return error code for last fdf operation
- fdf_error — Return error description for FDF error code
- fdf_get_ap — Get the appearance of a field
- fdf_get_attachment — Extracts uploaded file embedded in the FDF
- fdf_get_encoding — Get the value of the /Encoding key
- fdf_get_file — Get the value of the /F key
- fdf_get_flags — Gets the flags of a field
- fdf_get_opt — Gets a value from the opt array of a field
- fdf_get_status — Get the value of the /STATUS key
- fdf_get_value — Get the value of a field
- fdf_get_version — Gets version number for FDF API or file
- fdf_header — Sets FDF-specific output headers
- fdf_next_field_name — Get the next field name
- fdf_open — Open a FDF document
- fdf_open_string — Read a FDF document from a string
- fdf_remove_item — Sets target frame for form
- fdf_save — Save a FDF document
- fdf_save_string — Returns the FDF document as a string
- fdf_set_ap — Set the appearance of a field
- fdf_set_encoding — Sets FDF character encoding
- fdf_set_file — Set PDF document to display FDF data in
- fdf_set_flags — Sets a flag of a field
- fdf_set_javascript_action — Sets an javascript action of a field
- fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
- fdf_set_opt — Sets an option of a field
- fdf_set_status — Set the value of the /STATUS key
- fdf_set_submit_form_action — Sets a submit form action of a field
- fdf_set_target_frame — Set target frame for form display
- fdf_set_value — Set the value of a field
- fdf_set_version — Sets version number for a FDF file

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- Examples
- FDF Functions
  - fdf_add_doc_javascript — Adds javascript code to the FDF document
  - fdf_add_template — Adds a template into the FDF document
  - fdf_close — Close an FDF document
  - fdf_create — Create a new FDF document
  - fdf_enum_values — Call a user defined function for each document value
  - fdf_errno — Return error code for last fdf operation
  - fdf_error — Return error description for FDF error code
  - fdf_get_ap — Get the appearance of a field
  - fdf_get_attachment — Extracts uploaded file embedded in the FDF
  - fdf_get_encoding — Get the value of the /Encoding key
  - fdf_get_file — Get the value of the /F key
  - fdf_get_flags — Gets the flags of a field
  - fdf_get_opt — Gets a value from the opt array of a field
  - fdf_get_status — Get the value of the /STATUS key
  - fdf_get_value — Get the value of a field
  - fdf_get_version — Gets version number for FDF API or file
  - fdf_header — Sets FDF-specific output headers
  - fdf_next_field_name — Get the next field name
  - fdf_open — Open a FDF document
  - fdf_open_string — Read a FDF document from a string
  - fdf_remove_item — Sets target frame for form
  - fdf_save — Save a FDF document
  - fdf_save_string — Returns the FDF document as a string
  - fdf_set_ap — Set the appearance of a field
  - fdf_set_encoding — Sets FDF character encoding
  - fdf_set_file — Set PDF document to display FDF data in
  - fdf_set_flags — Sets a flag of a field
  - fdf_set_javascript_action — Sets an javascript action of a field
  - fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
  - fdf_set_opt — Sets an option of a field
  - fdf_set_status — Set the value of the /STATUS key
  - fdf_set_submit_form_action — Sets a submit form action of a field
  - fdf_set_target_frame — Set target frame for form display
  - fdf_set_value — Set the value of a field
  - fdf_set_version — Sets version number for a FDF file

# GNU Privacy Guard

# Introduction

This module allows you to interact with » gnupg.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

This extension requires the » gpgme library

## Installation

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: » https://pecl.php.net/package/gnupg.

# Predefined Constants

`GNUPG_SIG_MODE_NORMAL` (int)
`GNUPG_SIG_MODE_DETACH` (int)
`GNUPG_SIG_MODE_CLEAR` (int)
`GNUPG_VALIDITY_UNKNOWN` (int)
`GNUPG_VALIDITY_UNDEFINED` (int)
`GNUPG_VALIDITY_NEVER` (int)
`GNUPG_VALIDITY_MARGINAL` (int)
`GNUPG_VALIDITY_FULL` (int)
`GNUPG_VALIDITY_ULTIMATE` (int)
`GNUPG_PROTOCOL_OpenPGP` (int)
`GNUPG_PROTOCOL_CMS` (int)
`GNUPG_SIGSUM_VALID` (int)
`GNUPG_SIGSUM_GREEN` (int)
`GNUPG_SIGSUM_RED` (int)
`GNUPG_SIGSUM_KEY_REVOKED` (int)
`GNUPG_SIGSUM_KEY_EXPIRED` (int)
`GNUPG_SIGSUM_KEY_MISSING` (int)
`GNUPG_SIGSUM_SIG_EXPIRED` (int)
`GNUPG_SIGSUM_CRL_MISSING` (int)
`GNUPG_SIGSUM_CRL_TOO_OLD` (int)
`GNUPG_SIGSUM_BAD_POLICY` (int)
`GNUPG_SIGSUM_SYS_ERROR` (int)
`GNUPG_ERROR_WARNING` (int)
`GNUPG_ERROR_EXCEPTION` (int)
`GNUPG_ERROR_SILENT` (int)

# Examples

## Table of Contents

- Clearsign text

## Clearsign text

This example will clearsign a given text.

Example #1 gnupg clearsign example (procedural)

`<?php
// init gnupg
$res = gnupg_init();
// not really needed. Clearsign is default
gnupg_setsignmode($res,GNUPG_SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = gnupg_sign($res,"just a test");
echo $signed;
?>`

Example #2 gnupg clearsign example (OO)

`<?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg->setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg->sign("just a test");
echo $signed;
?>`

Example #3 keylistiterator

This extension also comes with an Iterator for your keyring.

`<?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint => $userid){
echo $fingerprint." -> ".$userid."\n";
}
?>`

# GnuPG Functions

# Notes

This extension makes use of the keyring of the current user. This keyring is normally located in ~./.gnupg/. To specify a custom location, store the path to the keyring in the environment variable GNUPGHOME. See putenv for more information how to do this.

Some functions require the specification of a key. This specification can be anything that refers to a unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.

> Note: As alternative to the explicitly documented functions using resources, you can also use an object-oriented style using gnupg objects.

# gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

### Description

gnupg_adddecryptkey(resource `$identifier`, string `$fingerprint`, string `$passphrase`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`fingerprint`

  The fingerprint key.

`passphrase`
  The pass phrase.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_adddecryptkey() example

`<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>`

Example #2 OO gnupg_adddecryptkey() example

`<?php
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>`

# gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

### Description

gnupg_addencryptkey(resource `$identifier`, string `$fingerprint`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`fingerprint`

  The fingerprint key.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_addencryptkey() example

`<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>`

Example #2 OO gnupg_addencryptkey() example

`<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>`

# gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

### Description

gnupg_addsignkey(resource `$identifier`, string `$fingerprint`, string `$passphrase` = ?): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`fingerprint`

  The fingerprint key.

`passphrase`
  The pass phrase.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_addsignkey() example

`<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>`

Example #2 OO gnupg_addsignkey() example

`<?php
$gpg = new gnupg();
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>`

# gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

### Description

gnupg_cleardecryptkeys(resource `$identifier`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_cleardecryptkeys() example

`<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>`

Example #2 OO gnupg_cleardecryptkeys() example

`<?php
$gpg = new gnupg();
$gpg->cleardecryptkeys();
?>`

# gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

### Description

gnupg_clearencryptkeys(resource `$identifier`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_clearencryptkeys() example

`<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>`

Example #2 OO gnupg_clearencryptkeys() example

`<?php
$gpg = new gnupg();
$gpg->clearencryptkeys();
?>`

# gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

### Description

gnupg_clearsignkeys(resource `$identifier`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_clearsignkeys() example

`<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>`

Example #2 OO gnupg_clearsignkeys() example

`<?php
$gpg = new gnupg();
$gpg->clearsignkeys();
?>`

# gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

### Description

gnupg_decrypt(resource `$identifier`, string `$text`): string|false

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`text`
  The text being decrypted.

### Return Values

On success, this function returns the decrypted text. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_decrypt() example

`<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>`

Example #2 OO gnupg_decrypt() example

`<?php
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg->decrypt($encrypted_text);
echo $plain;
?>`

# gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

### Description

gnupg_decryptverify(resource `$identifier`, string `$text`, string `&$plaintext`): array|false

Decrypts and verifies a given text and returns information about the signature.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`text`
  The text being decrypted.
`plaintext`
  The parameter `plaintext` gets filled with the decrypted text.

### Return Values

On success, this function returns information about the signature and fills the `plaintext` parameter with the decrypted text. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_decryptverify() example

`<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>`

Example #2 OO gnupg_decryptverify() example

`<?php
$plaintext = "";
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg->decryptverify($text,$plaintext);
print_r($info);
?>`

# gnupg_deletekey

(PECL gnupg >= 0.5)

gnupg_deletekey — Delete a key from the keyring

### Description

gnupg_deletekey(resource `$identifier`, string `$key`, bool `$allow_secret`): bool

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`key`
  The key to delete.
`allow_secret`
  It specifies whether to delete secret keys as well.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_deletekey() example

`<?php
$res = gnupg_init();
gnupg_deletekey($res, "8660281B6051D071D94B5B230549F9DC851566DC");
?>`

Example #2 OO gnupg_deletekey() example

`<?php
$gpg = new gnupg();
$gpg->deletekey("8660281B6051D071D94B5B230549F9DC851566DC");
?>`

# gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

### Description

gnupg_encrypt(resource `$identifier`, string `$plaintext`): string|false

Encrypts the given `plaintext` with the keys, which were set with gnupg_addencryptkey before and returns the encrypted text.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`plaintext`
  The text being encrypted.

### Return Values

On success, this function returns the encrypted text. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_encrypt() example

`<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>`

Example #2 OO gnupg_encrypt() example

`<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg->encrypt("just a test");
echo $enc;
?>`

# gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

### Description

gnupg_encryptsign(resource `$identifier`, string `$plaintext`): string|false

Encrypts and signs the given `plaintext` with the keys, which were set with gnupg_addsignkey and gnupg_addencryptkey before and returns the encrypted and signed text.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`plaintext`
  The text being encrypted.

### Return Values

On success, this function returns the encrypted and signed text. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_encryptsign() example

`<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>`

Example #2 OO gnupg_encryptsign() example

`<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg->encryptsign("just a test");
echo $enc;
?>`

# gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

### Description

gnupg_export(resource `$identifier`, string `$fingerprint`): string|false

Exports the key `fingerprint`.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`fingerprint`

  The fingerprint key.

### Return Values

On success, this function returns the keydata. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_export() example

`<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>`

Example #2 OO gnupg_export() example

`<?php
$gpg = new gnupg();
$export = $gpg->export("8660281B6051D071D94B5B230549F9DC851566DC");
?>`

# gnupg_getengineinfo

(PECL gnupg >= 1.5)

gnupg_getengineinfo — Returns the engine info

### Description

gnupg_getengineinfo(resource `$identifier`): array

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns an array with engine info consting of `protocol`, `file_name` and `home_dir`.

### Examples

Example #1 Procedural gnupg_getengineinfo() example

`<?php
$res = gnupg_init();
print_r(gnupg_getengineinfo($res));
?>`

The above example will output:

    array(3) {
      ["protocol"]=>
      int(0)
      ["file_name"]=>
      string(12) "/usr/bin/gpg"
      ["home_dir"]=>
      string(0) ""
    }

Example #2 OO gnupg_getengineinfo() example

`<?php
$gpg = new gnupg(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
print_r($gpg->getengineinfo());
?>`

The above example will output:

    array(3) {
      ["protocol"]=>
      int(0)
      ["file_name"]=>
      string(13) "/usr/bin/gpg2"
      ["home_dir"]=>
      string(15) "/var/www/.gnupg"
    }

# gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

### Description

gnupg_geterror(resource `$identifier`): string|false

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns an errortext, if an error has occurred, otherwise `false`.

### Examples

Example #1 Procedural gnupg_geterror() example

`<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>`

Example #2 OO gnupg_geterror() example

`<?php
$gpg = new gnupg();
echo $gpg->geterror();
?>`

# gnupg_geterrorinfo

(PECL gnupg >= 1.5)

gnupg_geterrorinfo — Returns the error info

### Description

gnupg_geterrorinfo(resource `$identifier`): array

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns an array with error info.

### Examples

Example #1 Procedural gnupg_geterrorinfo() example

`<?php
$res = gnupg_init();
// this is called without any error
print_r(gnupg_geterrorinfo($res));
?>`

The above example will output:

    array(4) {
      ["generic_message"]=>
      bool(false)
      ["gpgme_code"]=>
      int(0)
      ["gpgme_source"]=>
      string(18) "Unspecified source"
      ["gpgme_message"]=>
      string(7) "Success"
    }

Example #2 OO gnupg_geterrorinfo() example

`<?php
$gpg = new gnupg();
// error call
$gpg->decrypt('abc');
// error info should be displayed
print_r($gpg->geterrorinfo());
?>`

The above example will output:

    array(4) {
      ["generic_message"]=>
      string(14) "decrypt failed"
      ["gpgme_code"]=>
      int(117440570)
      ["gpgme_source"]=>
      string(5) "GPGME"
      ["gpgme_message"]=>
      string(7) "No data"
    }

# gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

### Description

gnupg_getprotocol(resource `$identifier`): int

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

### Return Values

Returns the currently active protocol, which can be one of `GNUPG_PROTOCOL_OpenPGP` or `GNUPG_PROTOCOL_CMS`.

### Examples

Example #1 Procedural gnupg_getprotocol() example

`<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>`

Example #2 OO gnupg_getprotocol() example

`<?php
$gpg = new gnupg();
echo $gpg->getprotocol();
?>`

# gnupg_gettrustlist

(PECL gnupg >= 0.5)

gnupg_gettrustlist — Search the trust items

### Description

gnupg_gettrustlist(resource `$identifier`, string `$pattern`): ?array

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`pattern`
  Expression to limit the list of trust items to only the ones matching the pattern.

### Return Values

On success, this function returns an array of trust items. On failure, this function returns `null`.

### Examples

Example #1 Procedural gnupg_gettrustlist() example

`<?php
$res = gnupg_init();
$items = gnupg_gettrustlist($res);
print_r($items);
?>`

Example #2 OO gnupg_gettrustlist() example

`<?php
$gpg = new gnupg();
$items = $gpg->gettrustlist();
print_r($items);
?>`

# gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

### Description

gnupg_import(resource `$identifier`, string `$keydata`): array|false

Imports the key `keydata` and returns an array with information about the importprocess.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`keydata`
  The data key that is being imported.

### Return Values

On success, this function returns and info-array about the importprocess. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_import() example

`<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>`

Example #2 OO gnupg_import() example

`<?php
$gpg = new gnupg();
$info = $gpg->import($keydata);
print_r($info);
?>`

# gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

### Description

gnupg_init(?array `$options` = `null`): resource

### Parameters

`options`

  Must be an associative array. It is used to change the default configuration of the crypto engine.

  Configuration overrides
  key | type | description
  --- | --- | ---
  file_name | string | It is the file name of the executable program implementing this protocol which is usually path of the `gpg` executable.
  home_dir | string | It is the directory name of the configuration directory. It also overrides `GNUPGHOME` environment variable that is used for the same purpose.

### Return Values

A GnuPG resource connection used by other GnuPG functions.

### Changelog

Version | Description
--- | ---
PECL gnupg 1.5.0 | The `options` parameter was added.

### Examples

Example #1 Procedural gnupg_init() example with default setting

`<?php
$res = gnupg_init();
?>`

Example #2 Procedural gnupg_init() example with overridden file name and home dir

`<?php
$res = gnupg_init(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
?>`

Example #3 OO gnupg initializer example with default setting

`<?php
$gpg = new gnupg();
?>`

Example #4 OO gnupg initializer example with overridden file name and home dir

`<?php
$gpg = new gnupg(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
?>`

# gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

### Description

gnupg_keyinfo(resource `$identifier`, string `$pattern`): array|false

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`pattern`
  The pattern being checked against the keys.

### Return Values

Returns an array with information about all keys that matches the given pattern or `false`, if an error has occurred.

### Examples

Example #1 Procedural gnupg_keyinfo() example

`<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>`

Example #2 OO gnupg_keyinfo() example

`<?php
$gpg = new gnupg();
$info = $gpg->keyinfo("test");
print_r($info);
?>`

# gnupg_listsignatures

(PECL gnupg >= 0.5)

gnupg_listsignatures — List key signatures

### Description

gnupg_listsignatures(resource `$identifier`, string `$keyid`): ?array

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`keyid`
  The key ID to list signatures for.

### Return Values

On success, this function returns an array of key signatures. On failure, this function returns `null`.

### Examples

Example #1 Procedural gnupg_listsignatures() example

`<?php
$res = gnupg_init();
$signatures = gnupg_listsignatures($res, "8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>`

Example #2 OO gnupg_listsignatures() example

`<?php
$gpg = new gnupg();
$signatures = $gpg->listsignatures("8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>`

# gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

### Description

gnupg_setarmor(resource `$identifier`, int `$armor`): bool

Toggle the armored output.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`armor`
  Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_setarmor() example

`<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>`

Example #2 OO gnupg_setarmor() example

`<?php
$gpg = new gnupg();
$gpg->setarmor(1); // enable armored output;
$gpg->setarmor(0); // disable armored output;
?>`

# gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

### Description

gnupg_seterrormode(resource `$identifier`, int `$errormode`): void

Sets the mode for error_reporting.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`errormode`
  The error mode. `errormode` takes a constant indicating what type of error_reporting should be used. The possible values are `GNUPG_ERROR_WARNING`, `GNUPG_ERROR_EXCEPTION` and `GNUPG_ERROR_SILENT`. By default `GNUPG_ERROR_SILENT` is used.

### Return Values

No value is returned.

### Examples

Example #1 Procedural gnupg_seterrormode() example

`<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>`

Example #2 OO gnupg_seterrormode() example

`<?php
$gpg = new gnupg();
$gpg->seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?>`

# gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

### Description

gnupg_setsignmode(resource `$identifier`, int `$signmode`): bool

Sets the mode for signing.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`sigmode`
  The mode for signing. `signmode` takes a constant indicating what type of signature should be produced. The possible values are `GNUPG_SIG_MODE_NORMAL`, `GNUPG_SIG_MODE_DETACH` and `GNUPG_SIG_MODE_CLEAR`. By default `GNUPG_SIG_MODE_CLEAR` is used.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Procedural gnupg_setsignmode() example

`<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>`

Example #2 OO gnupg_setsignmode() example

`<?php
$gpg = new gnupg();
$gpg->setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>`

# gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

### Description

gnupg_sign(resource `$identifier`, string `$plaintext`): string|false

Signs the given `plaintext` with the keys, which were set with gnupg_addsignkey before and returns the signed text or the signature, depending on what was set with gnupg_setsignmode.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`plaintext`
  The plain text being signed.

### Return Values

On success, this function returns the signed text or the signature. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_sign() example

`<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>`

Example #2 OO gnupg_sign() example

`<?php
$gpg = new gnupg();
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg->sign("just a test");
echo $signed;
?>`

# gnupg_verify

(PECL gnupg >= 0.1)

gnupg_verify — Verifies a signed text

### Description

gnupg_verify(
resource `$identifier`,
string `$signed_text`,
string `$signature`,
string `&$plaintext` = ?
): array|false

Verifies the given `signed_text` and returns information about the signature.

### Parameters

`identifier`

  The gnupg identifier, from a call to gnupg_init() or gnupg.

`signed_text`
  The signed text.
`signature`
  The signature. To verify a clearsigned text, set signature to `false`.
`plaintext`
  The plain text. If this optional parameter is passed, it is filled with the plain text.

### Return Values

On success, this function returns information about the signature. On failure, this function returns `false`.

### Examples

Example #1 Procedural gnupg_verify() example

`<?php
$plaintext = "";
$res = gnupg_init();
// clearsigned
$info = gnupg_verify($res,$signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = gnupg_verify($res,$signed_text,$signature);
print_r($info);
?>`

Example #2 OO gnupg_verify() example

`<?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg->verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg->verify($signed_text,$signature);
print_r($info);
?>`

## Table of Contents

- gnupg_adddecryptkey — Add a key for decryption
- gnupg_addencryptkey — Add a key for encryption
- gnupg_addsignkey — Add a key for signing
- gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
- gnupg_clearencryptkeys — Removes all keys which were set for encryption before
- gnupg_clearsignkeys — Removes all keys which were set for signing before
- gnupg_decrypt — Decrypts a given text
- gnupg_decryptverify — Decrypts and verifies a given text
- gnupg_deletekey — Delete a key from the keyring
- gnupg_encrypt — Encrypts a given text
- gnupg_encryptsign — Encrypts and signs a given text
- gnupg_export — Exports a key
- gnupg_getengineinfo — Returns the engine info
- gnupg_geterror — Returns the errortext, if a function fails
- gnupg_geterrorinfo — Returns the error info
- gnupg_getprotocol — Returns the currently active protocol for all operations
- gnupg_gettrustlist — Search the trust items
- gnupg_import — Imports a key
- gnupg_init — Initialize a connection
- gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
- gnupg_listsignatures — List key signatures
- gnupg_setarmor — Toggle armored output
- gnupg_seterrormode — Sets the mode for error_reporting
- gnupg_setsignmode — Sets the mode for signing
- gnupg_sign — Signs a given text
- gnupg_verify — Verifies a signed text

- Installing/Configuring
  - Requirements
  - Installation
- Predefined Constants
- Examples
  - Clearsign text
- GnuPG Functions
  - gnupg_adddecryptkey — Add a key for decryption
  - gnupg_addencryptkey — Add a key for encryption
  - gnupg_addsignkey — Add a key for signing
  - gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
  - gnupg_clearencryptkeys — Removes all keys which were set for encryption before
  - gnupg_clearsignkeys — Removes all keys which were set for signing before
  - gnupg_decrypt — Decrypts a given text
  - gnupg_decryptverify — Decrypts and verifies a given text
  - gnupg_deletekey — Delete a key from the keyring
  - gnupg_encrypt — Encrypts a given text
  - gnupg_encryptsign — Encrypts and signs a given text
  - gnupg_export — Exports a key
  - gnupg_getengineinfo — Returns the engine info
  - gnupg_geterror — Returns the errortext, if a function fails
  - gnupg_geterrorinfo — Returns the error info
  - gnupg_getprotocol — Returns the currently active protocol for all operations
  - gnupg_gettrustlist — Search the trust items
  - gnupg_import — Imports a key
  - gnupg_init — Initialize a connection
  - gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
  - gnupg_listsignatures — List key signatures
  - gnupg_setarmor — Toggle armored output
  - gnupg_seterrormode — Sets the mode for error_reporting
  - gnupg_setsignmode — Sets the mode for signing
  - gnupg_sign — Signs a given text
  - gnupg_verify — Verifies a signed text

# wkhtmltox

# Introduction

libwkhtmltox is an open source LGPLv3 library for rendering HTML into PDF and various image formats using the QtWebKit rendering engine.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Runtime Configuration

## Requirements

libwkhtmltox source and binary releases are distributed at » wkhtmltopdf.org.

Caution

Windows users need to take the additional step of adding wkhtmltox.dll to their PATH.

## Installation

The source code of this extension, and binaries for Windows are hosted by » github,

Fetching the source code and building the extension:

    git clone https://github.com/krakjoe/wkhtmltox
    cd wkhtmltox
    phpize
    ./configure --with-wkhtmltox=/path/to/wkhtmltox/installation
    make
    sudo make install

Fetching updates and rebuilding the extension:

    cd wkhtmltox
    phpize --clean
    git pull origin master
    phpize
    ./configure --with-wkhtmltox=/path/to/wkhtmltox/installation
    make
    sudo make install

## Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

wkhtmltox Configure Options
Name | Default | Changeable | Changelog
--- | --- | --- | ---
wkhtmltox.graphics | Off | `INI_SYSTEM`|`INI_PERDIR` | >= 0.3.2

For further details and definitions of the INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

`wkhtmltox.graphics` bool

  Allow libwkhtmltox to use graphics.

# The wkhtmltox\PDF\Converter class

(wkhtmltox >= 0.1.0)

## Introduction

Converts an HTML input, or set of HTML inputs, into PDF output

## Class synopsis

class wkhtmltox\PDF\Converter {
/* Constructor */
public __construct(array `$settings` = ?)
/* Methods */
public add(wkhtmltox\PDF\Object `$object`): void
public convert(): ?string
public getVersion(): string
}

# wkhtmltox\PDF\Converter::add

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::add — Add an object for conversion

### Description

public wkhtmltox\PDF\Converter::add(wkhtmltox\PDF\Object `$object`): void

Adds the given object to conversion

### Parameters

`object`

  The object to add

# wkhtmltox\PDF\Converter::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::__construct — Create a new PDF converter

### Description

public wkhtmltox\PDF\Converter::__construct(array `$settings` = ?)

Creates a PDF converter, using optional configuration settings

### Parameters

`settings`

  Name | Description | Values | Changelog
  --- | --- | --- | ---
  size.pageSize | paper size of output document | A4 | >= 0.1.0
  size.width | with of the output document | 210mm | >= 0.1.0
  size.height | height of the output document | 297mm | >= 0.1.0
  orientation | orientation of the output document |
  Landscape
  Portrait
  | >= 0.1.0
  colorMode | color mode of the output document |
  Color
  Greyscale
  | >= 0.1.0
  resolution | resolution of the output document | most likely has no effect | >= 0.1.0
  dpi | dpi to use while printing | 80 | >= 0.1.0
  pageOffset | integer added to page numbers generating headers, footers, and toc |  | >= 0.1.0
  copies |  |  | >= 0.1.0
  collate | collate copies | boolean | >= 0.1.0
  outline | generate PDF outline | boolean | >= 0.1.0
  outlineDepth | maximum depth of outline |  | >= 0.1.0
  dumpOutline | path of file to dump outline XML |  | >= 0.1.0
  out | path of output file, if "-" stdout is used |  | >= 0.1.0
  documentTitle | title for the output document |  | >= 0.1.0
  useCompression | enable or disable lossless compression | boolean | >= 0.1.0
  margin.top | size of the top margin | 2cm | >= 0.1.0
  margin.bottom | size of the bottom margin | 2cm | >= 0.1.0
  margin.left | size of the left margin | 2cm | >= 0.1.0
  margin.right | size of the right margin | 2cm | >= 0.1.0
  imageDPI | maximum DPI for images in the output document |  | >= 0.1.0
  imageQuality | the jpeg compression factor for images in the output document | 94 | >= 0.1.0
  load.cookieJar | path of file used to load and store cookies | /tmp/cookies.txt | >= 0.1.0

# wkhtmltox\PDF\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::convert — Perform PDF conversion

### Description

public wkhtmltox\PDF\Converter::convert(): ?string

Performs conversion of all previously added Objects

### Parameters

This function has no parameters.

### Return Values

Where the return value is used, it will be populated with the contents of the conversion buffer

# wkhtmltox\PDF\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\PDF\Converter::getVersion — Determine version of Converter

### Description

public wkhtmltox\PDF\Converter::getVersion(): string

Determines the version of Converter as reported by libwkhtmltox

### Parameters

This function has no parameters.

### Return Values

Returns a version string

## Table of Contents

- wkhtmltox\PDF\Converter::add — Add an object for conversion
- wkhtmltox\PDF\Converter::__construct — Create a new PDF converter
- wkhtmltox\PDF\Converter::convert — Perform PDF conversion
- wkhtmltox\PDF\Converter::getVersion — Determine version of Converter

# The wkhtmltox\PDF\Object class

(wkhtmltox >= 0.1.0)

## Introduction

Represents an HTML document, input to PDF converter

## Class synopsis

class wkhtmltox\PDF\Object {
/* Constructor */
public __construct(string `$buffer`, array `$settings` = ?)
}

# wkhtmltox\PDF\Object::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Object::__construct — Create a new PDF Object

### Description

public wkhtmltox\PDF\Object::__construct(string `$buffer`, array `$settings` = ?)

Creates a new PDF Object from the given buffer and optional configuration settings

### Parameters

`buffer`

  HTML

`settings`

  Name | Description | Values | Changelog
  --- | --- | --- | ---
  page | URL or path of the HTML to convert |  | >= 0.1.0
  useExternalLinks | set true to convert external links in the input into external PDF links in the output | boolean | >= 0.1.0
  useLocalLinks | set true to convert internal links in the input into internal PDF links in the output | boolean | >= 0.1.0
  produceForms | set true to turn HTML forms into PDF forms | boolean | >= 0.1.0
  replacements | undocumented |  | >= 0.1.0
  includeInOutline | set true to include sections from this object in the outline and toc | boolean | >= 0.1.0
  pagesCount | set true to make page count in toc inclusive of the number of pages in this object | boolean | >= 0.1.0
  tocXsl | set to style sheet to convert this object into a toc object |  | >= 0.1.0
  toc.useDottedLines | set true to use dotted lines in toc | boolean | >= 0.1.0
  toc.captionText | the caption text for toc |  | >= 0.1.0
  toc.forwardLinks | set true to create links from toc to content | boolean | >= 0.1.0
  toc.backLinks | set true to create links from content to toc | boolean | >= 0.1.0
  toc.indentation | indentation for toc | 2em | >= 0.1.0
  toc.fontScale | the factor to scale down the font at every toc level | 0.8 | >= 0.1.0
  header.fontSize | font size for use in header | 13 | >= 0.1.0
  header.fontName | name of font for use in header | times | >= 0.1.0
  header.left | text for left of header |  | >= 0.1.0
  header.center | text for center of header |  | >= 0.1.0
  header.right | text for right of header |  | >= 0.1.0
  header.line | enable or disable horizontal rule under header | boolean | >= 0.1.0
  header.spacing | space between header and content | 1.8 | >= 0.1.0
  header.htmlUrl | URL or path of HTML to use in header |  | >= 0.1.0
  footer.fontSize | font size for use in footer | 13 | >= 0.1.0
  footer.fontName | name of font for use in footer | times | >= 0.1.0
  footer.left | text for left of footer |  | >= 0.1.0
  footer.center | text for center of footer |  | >= 0.1.0
  footer.right | text for right of footer |  | >= 0.1.0
  footer.line | enable or disable horizontal rule under footer | boolean | >= 0.1.0
  footer.spacing | space between footer and content | 1.8 | >= 0.1.0
  footer.htmlUrl | URL or path of HTML to use in footer |  | >= 0.1.0
  load.username | user name to use when loging into a website | bart | >= 0.1.0
  load.password | the password to used when logging into a website | elbarto | >= 0.1.0
  load.jsdelay | the amount of time in milliseconds to wait after a page is loaded until it is captured | 1200 | >= 0.1.0
  load.zoomFactor | how much zoom should be applied to the content | 2.2 | >= 0.1.0
  load.customHeaders | custom headers to send when requesting the main web page |  | >= 0.1.0
  load.repertCustomHeaders | set true to send with all requests | boolean | >= 0.1.0
  load.cookies | cookie string to send when requesting the main web page |  | >= 0.1.0
  load.post | post string to send when requesting the main web page |  | >= 0.1.0
  load.blockLocalFileAccess | disallow local and piped files to access other local files | boolean | >= 0.1.0
  load.stopSlowScript | stop slow running javascript | boolean |
  load.debugJavascript | allow javascript to raise warnings | boolean | >= 0.1.0
  load.loadErrorHandling | set error handling strategy |
  abort | abort the convertion process
  skip | do not add the object to the final output
  ignore | try to add the object to the final output
  | >= 0.1.0
  load.proxy |  |  | >= 0.1.0
  web.background | include background image in output | boolean | >= 0.1.0
  web.loadImages | include images in output | boolean | >= 0.1.0
  web.enableJavascript | enable or disable javascript | boolean | >= 0.1.0
  web.enableIntelligentShrinking | enable to attempt to fit more content on page, only applies to PDF output | boolean | >= 0.1.0
  web.minimumFontSize | the minimum font size allowed | 9 | >= 0.1.0
  web.printMediaType | print content using print media type instead of screen media type | boolean | >= 0.1.0
  web.defaultEncoding | content to use where no encoding is specified | utf-8 | >= 0.1.0
  web.userStyleSheet | URL or path to a user specified style sheet | /path/to/style.css | >= 0.1.0
  web.enablePlugins | enable or disable NS plugins | boolean | >= 0.1.0

## Table of Contents

- wkhtmltox\PDF\Object::__construct — Create a new PDF Object

# The wkhtmltox\Image\Converter class

(wkhtmltox >= 0.1.0)

## Introduction

Converts an HTML input into various image formats

## Class synopsis

class wkhtmltox\Image\Converter {
/* Constructor */
public __construct(string `$buffer` = ?, array `$settings` = ?)
/* Methods */
public convert(): ?string
public getVersion(): string
}

# wkhtmltox\Image\Converter::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\Image\Converter::__construct — Create a new Image converter

### Description

public wkhtmltox\Image\Converter::__construct(string `$buffer` = ?, array `$settings` = ?)

Creates an Image converter, optionally taking an input buffer and configuration settings

### Parameters

`buffer`

  HTML

`settings`

  Name | Description | Values | Changelog
  --- | --- | --- | ---
  in | URL or path of the input file, if "-" stdin is used | /path/to/markup.html | >= 0.1.0
  out | path of output file, if "-" stdout is used, by default an internal buffer is used | /path/to/output.png | >= 0.1.0
  fmt | output format to use |
  "" | default
  jpg | output as JPEG
  png | output as PNG
  bmp | output as bitmap
  svg | output as SVG
  | >= 0.1.0
  transparent | when outputting a PNG or SVG, make the white background transparent | boolean | >= 0.1.0
  screenWidth | the with of the screen used to render in pixels | 800 | >= 0.1.0
  smartWidth | when true, screenWidth is expanded to the content width | boolean | >= 0.1.0
  quality | compression factor to use when outputting a JPEG image | 94 | >= 0.1.0
  crop.left | left/x coordinate of the window to capture in pixels | 200 | >= 0.1.0
  crop.top | top/y coordinate of the window to capture in pixels | 200 | >= 0.1.0
  crop.width | width of the window to capture in pixels | 200 | >= 0.1.0
  crop.height | height of the window to capture in pixels | 200 | >= 0.1.0
  load.cookieJar | path of file used to load and store cookies | /tmp/cookies.txt | >= 0.1.0
  load.username | user name to use when loging into a website | bart | >= 0.1.0
  load.password | the password to used when logging into a website | elbarto | >= 0.1.0
  load.jsdelay | the amount of time in milliseconds to wait after a page is loaded until it is captured | 1200 | >= 0.1.0
  load.zoomFactor | how much zoom should be applied to the content | 2.2 | >= 0.1.0
  load.customHeaders | custom headers to send when requesting the main web page |  | >= 0.1.0
  load.repertCustomHeaders | set true to send with all requests | boolean | >= 0.1.0
  load.cookies | cookie string to send when requesting the main web page |  | >= 0.1.0
  load.post | post string to send when requesting the main web page |  | >= 0.1.0
  load.blockLocalFileAccess | disallow local and piped files to access other local files | boolean | >= 0.1.0
  load.stopSlowScript | stop slow running javascript | boolean |
  load.debugJavascript | allow javascript to raise warnings | boolean | >= 0.1.0
  load.loadErrorHandling | set error handling strategy |
  abort | abort the convertion process
  skip | do not add the object to the final output
  ignore | try to add the object to the final output
  | >= 0.1.0
  load.proxy |  |  | >= 0.1.0
  web.background | include background image in output | boolean | >= 0.1.0
  web.loadImages | include images in output | boolean | >= 0.1.0
  web.enableJavascript | enable or disable javascript | boolean | >= 0.1.0
  web.enableIntelligentShrinking | enable to attempt to fit more content on page, only applies to PDF output | boolean | >= 0.1.0
  web.minimumFontSize | the minimum font size allowed | 9 | >= 0.1.0
  web.printMediaType | print content using print media type instead of screen media type | boolean | >= 0.1.0
  web.defaultEncoding | content to use where no encoding is specified | utf-8 | >= 0.1.0
  web.userStyleSheet | URL or path to a user specified style sheet | /path/to/style.css | >= 0.1.0
  web.enablePlugins | enable or disable NS plugins | boolean | >= 0.1.0

# wkhtmltox\Image\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\Image\Converter::convert — Perform Image conversion

### Description

public wkhtmltox\Image\Converter::convert(): ?string

Performs conversion of the input buffer

### Parameters

This function has no parameters.

### Return Values

Where the return value is used, it will be populated with the contents of the conversion buffer

# wkhtmltox\Image\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\Image\Converter::getVersion — Determine version of Converter

### Description

public wkhtmltox\Image\Converter::getVersion(): string

Determines the version of Converter as reported by libwkhtmltox

### Parameters

This function has no parameters.

### Return Values

Returns a version string

Warning

This is not yet implemented by libwkhtmltox

## Table of Contents

- wkhtmltox\Image\Converter::__construct — Create a new Image converter
- wkhtmltox\Image\Converter::convert — Perform Image conversion
- wkhtmltox\Image\Converter::getVersion — Determine version of Converter

- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
- wkhtmltox\PDF\Converter — The wkhtmltox\PDF\Converter class
  - wkhtmltox\PDF\Converter::add — Add an object for conversion
  - wkhtmltox\PDF\Converter::__construct — Create a new PDF converter
  - wkhtmltox\PDF\Converter::convert — Perform PDF conversion
  - wkhtmltox\PDF\Converter::getVersion — Determine version of Converter
- wkhtmltox\PDF\Object — The wkhtmltox\PDF\Object class
  - wkhtmltox\PDF\Object::__construct — Create a new PDF Object
- wkhtmltox\Image\Converter — The wkhtmltox\Image\Converter class
  - wkhtmltox\Image\Converter::__construct — Create a new Image converter
  - wkhtmltox\Image\Converter::convert — Perform Image conversion
  - wkhtmltox\Image\Converter::getVersion — Determine version of Converter

# PostScript document creation

# Introduction

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

You need at least pslib >= 0.1.12. The ps library (pslib) is available at » http://pslib.sourceforge.net/.

## Installation

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: » https://pecl.php.net/package/ps.

## Resource Types

This extension defines a PostScript document resource returned by ps_new().

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

The following two tables lists all constants defined by the ps extension.

Constants for line caps
Name | Meaning
--- | ---
`ps_LINECAP_BUTT` |
`ps_LINECAP_ROUND` |
`ps_LINECAP_SQUARED` |

Constants for line joins
Name | Meaning
--- | ---
`ps_LINEJOIN_MITER` |
`ps_LINEJOIN_ROUND` |
`ps_LINEJOIN_BEVEL` |

# PS Functions

## Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail » steinm@php.net. Any help is very welcome.

# ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

### Description

ps_add_bookmark(
resource `$psdoc`,
string `$text`,
int `$parent` = 0,
int `$open` = 0
): int

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text used for displaying the bookmark.

`parent`

  A bookmark previously created by this function which is used as the parent of the new bookmark.

`open`

  If `open` is unequal to zero the bookmark will be shown open by the pdf viewer.

### Return Values

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent. The value is greater zero if the function succeeds. In case of an error zero will be returned.

### See Also

- ps_add_launchlink() - Adds link which launches file
- ps_add_pdflink() - Adds link to a page in a second pdf document
- ps_add_weblink() - Adds link to a web location

# ps_add_launchlink

(PECL ps >= 1.1.0)

ps_add_launchlink — Adds link which launches file

### Description

ps_add_launchlink(
resource `$psdoc`,
float `$llx`,
float `$lly`,
float `$urx`,
float `$ury`,
string `$filename`
): bool

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`llx`

  The x-coordinate of the lower left corner.

`lly`

  The y-coordinate of the lower left corner.

`urx`

  The x-coordinate of the upper right corner.

`ury`

  The y-coordinate of the upper right corner.

`filename`

  The path of the program to be started, when the link is clicked on.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_add_locallink() - Adds link to a page in the same document
- ps_add_pdflink() - Adds link to a page in a second pdf document
- ps_add_weblink() - Adds link to a web location

# ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

### Description

ps_add_locallink(
resource `$psdoc`,
float `$llx`,
float `$lly`,
float `$urx`,
float `$ury`,
int `$page`,
string `$dest`
): bool

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (`llx`, `lly`) and its upper right corner at (`urx`, `ury`). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`llx`

  The x-coordinate of the lower left corner.

`lly`

  The y-coordinate of the lower left corner.

`urx`

  The x-coordinate of the upper right corner.

`ury`

  The y-coordinate of the upper right corner.

`page`

  The number of the page displayed when clicking on the link.

`dest`

  The parameter `dest` determines how the document is being viewed. It can be `fitpage`, `fitwidth`, `fitheight`, or `fitbbox`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_add_launchlink() - Adds link which launches file
- ps_add_pdflink() - Adds link to a page in a second pdf document
- ps_add_weblink() - Adds link to a web location

# ps_add_note

(PECL ps >= 1.1.0)

ps_add_note — Adds note to current page

### Description

ps_add_note(
resource `$psdoc`,
float `$llx`,
float `$lly`,
float `$urx`,
float `$ury`,
string `$contents`,
string `$title`,
string `$icon`,
int `$open`
): bool

Adds a note at a certain position on the page. Notes are like little rectangular sheets with text on it, which can be placed anywhere on a page. They are shown either folded or unfolded. If folded, the specified icon is used as a placeholder.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`llx`

  The x-coordinate of the lower left corner.

`lly`

  The y-coordinate of the lower left corner.

`urx`

  The x-coordinate of the upper right corner.

`ury`

  The y-coordinate of the upper right corner.

`contents`

  The text of the note.

`title`

  The title of the note as displayed in the header of the note.

`icon`

  The icon shown if the note is folded. This parameter can be set to `comment`, `insert`, `note`, `paragraph`, `newparagraph`, `key`, or `help`.

`open`

  If `open` is unequal to zero the note will be shown unfolded after opening the document with a pdf viewer.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_add_pdflink() - Adds link to a page in a second pdf document
- ps_add_launchlink() - Adds link which launches file
- ps_add_locallink() - Adds link to a page in the same document
- ps_add_weblink() - Adds link to a web location

# ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

### Description

ps_add_pdflink(
resource `$psdoc`,
float `$llx`,
float `$lly`,
float `$urx`,
float `$ury`,
string `$filename`,
int `$page`,
string `$dest`
): bool

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (`llx`, `lly`) and its upper right corner at (`urx`, `ury`). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`llx`

  The x-coordinate of the lower left corner.

`lly`

  The y-coordinate of the lower left corner.

`urx`

  The x-coordinate of the upper right corner.

`ury`

  The y-coordinate of the upper right corner.

`filename`

  The name of the pdf document to be opened when clicking on this link.

`page`

  The page number of the destination pdf document

`dest`

  The parameter `dest` determines how the document is being viewed. It can be `fitpage`, `fitwidth`, `fitheight`, or `fitbbox`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_add_launchlink() - Adds link which launches file
- ps_add_locallink() - Adds link to a page in the same document
- ps_add_weblink() - Adds link to a web location

# ps_add_weblink

(PECL ps >= 1.1.0)

ps_add_weblink — Adds link to a web location

### Description

ps_add_weblink(
resource `$psdoc`,
float `$llx`,
float `$lly`,
float `$urx`,
float `$ury`,
string `$url`
): bool

Places a hyperlink at the given position pointing to a web page. The hyperlink's source position is a rectangle with its lower left corner at (`llx`, `lly`) and its upper right corner at (`urx`, `ury`). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`llx`

  The x-coordinate of the lower left corner.

`lly`

  The y-coordinate of the lower left corner.

`urx`

  The x-coordinate of the upper right corner.

`ury`

  The y-coordinate of the upper right corner.

`url`

  The url of the hyperlink to be opened when clicking on this link, e.g. `http://www.php.net`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_add_launchlink() - Adds link which launches file
- ps_add_locallink() - Adds link to a page in the same document
- ps_add_pdflink() - Adds link to a page in a second pdf document

# ps_arc

(PECL ps >= 1.1.0)

ps_arc — Draws an arc counterclockwise

### Description

ps_arc(
resource `$psdoc`,
float `$x`,
float `$y`,
float `$radius`,
float `$alpha`,
float `$beta`
): bool

Draws a portion of a circle with at middle point at (`x`, `y`). The arc starts at an angle of `alpha` and ends at an angle of `beta`. It is drawn counterclockwise (use ps_arcn() to draw clockwise). The subpath added to the current path starts on the arc at angle `alpha` and ends on the arc at angle `beta`.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  The x-coordinate of the circle's middle point.

`y`

  The y-coordinate of the circle's middle point.

`radius`

  The radius of the circle

`alpha`

  The start angle given in degrees.

`beta`

  The end angle given in degrees.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_arcn() - Draws an arc clockwise

# ps_arcn

(PECL ps >= 1.1.0)

ps_arcn — Draws an arc clockwise

### Description

ps_arcn(
resource `$psdoc`,
float `$x`,
float `$y`,
float `$radius`,
float `$alpha`,
float `$beta`
): bool

Draws a portion of a circle with at middle point at (`x`, `y`). The arc starts at an angle of `alpha` and ends at an angle of `beta`. It is drawn clockwise (use ps_arc() to draw counterclockwise). The subpath added to the current path starts on the arc at angle `beta` and ends on the arc at angle `alpha`.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  The x-coordinate of the circle's middle point.

`y`

  The y-coordinate of the circle's middle point.

`radius`

  The radius of the circle

`alpha`

  The starting angle given in degrees.

`beta`

  The end angle given in degrees.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_arc() - Draws an arc counterclockwise

# ps_begin_page

(PECL ps >= 1.1.0)

ps_begin_page — Start a new page

### Description

ps_begin_page(resource `$psdoc`, float `$width`, float `$height`): bool

Starts a new page. Although the parameters `width` and `height` imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Though PostScript does not know different page sizes, pslib places a bounding box for each page into the document. This size is evaluated by some PostScript viewers and will have precedence over the BoundingBox in the Header of the document. This can lead to unexpected results when you set a BoundingBox whose lower left corner is not (0, 0), because the bounding box of the page will always have a lower left corner (0, 0) and overwrites the global setting.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. The lower left corner of the bounding box is set to (0, 0). If ps_findfont() was called before, then the header has been output already, and the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field `BoundingBox` and possibly `Orientation` before any ps_findfont() or ps_begin_page() calls.

> Note:

> Up to version 0.2.6 of pslib, this function will always overwrite the BoundingBox and Orientation, if it has been set before with ps_set_info() and ps_findfont() has not been called before.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`width`

  The width of the page in pixel, e.g. 596 for A4 format.

`height`

  The height of the page in pixel, e.g. 842 for A4 format.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_end_page() - End a page
- ps_findfont() - Loads a font
- ps_set_info() - Sets information fields of document

# ps_begin_pattern

(PECL ps >= 1.2.0)

ps_begin_pattern — Start a new pattern

### Description

ps_begin_pattern(
resource `$psdoc`,
float `$width`,
float `$height`,
float `$xstep`,
float `$ystep`,
int `$painttype`
): int|false

Starts a new pattern. A pattern is like a page containing e.g. a drawing which can be used for filling areas. It is used like a color by calling ps_setcolor() and setting the color space to `pattern`.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`width`

  The width of the pattern in pixel.

`height`

  The height of the pattern in pixel.

`xstep`

  The distance in pixel of placements of the pattern in horizontal direction.

`ystep`

  The distance in pixel of placements of the pattern in vertical direction.

`painttype`

  Must be 1 or 2.

### Return Values

The identifier of the pattern or `false` on failure.

### Examples

Example #1 Creating and using a pattern

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "pattern.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");
$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);
ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);
ps_close($ps);
ps_delete($ps);
?>`

### See Also

- ps_end_pattern() - End a pattern
- ps_setcolor() - Sets current color
- ps_shading_pattern() - Creates a pattern based on a shading

# ps_begin_template

(PECL ps >= 1.2.0)

ps_begin_template — Start a new template

### Description

ps_begin_template(resource `$psdoc`, float `$width`, float `$height`): int

Starts a new template. A template is called a form in the postscript language. It is created similar to a pattern but used like an image. Templates are often used for drawings which are placed several times through out the document, e.g. like a company logo. All drawing functions may be used within a template. The template will not be drawn until it is placed by ps_place_image().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`width`

  The width of the template in pixel.

`height`

  The height of the template in pixel.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Creating and using a template

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "template.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "template.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Template example");
$pstemplate = ps_begin_template($ps, 30.0, 30.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 30, 30);
ps_moveto($ps, 0, 30);
ps_lineto($ps, 30, 0);
ps_stroke($ps);
ps_end_template($ps);
ps_begin_page($ps, 596, 842);
ps_place_image($ps, $pstemplate, 20.0, 20.0, 1.0);
ps_place_image($ps, $pstemplate, 50.0, 30.0, 0.5);
ps_place_image($ps, $pstemplate, 70.0, 70.0, 0.6);
ps_place_image($ps, $pstemplate, 30.0, 50.0, 1.3);
ps_end_page($ps);
ps_close($ps);
ps_delete($ps);
?>`

### See Also

- ps_end_template() - End a template

# ps_circle

(PECL ps >= 1.1.0)

ps_circle — Draws a circle

### Description

ps_circle(
resource `$psdoc`,
float `$x`,
float `$y`,
float `$radius`
): bool

Draws a circle with its middle point at (`x`, `y`). The circle starts and ends at position (`x`+`radius`, `y`). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (`x`+`radius`, `y`) then there will be a gap in the path.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  The x-coordinate of the circle's middle point.

`y`

  The y-coordinate of the circle's middle point.

`radius`

  The radius of the circle

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_arc() - Draws an arc counterclockwise
- ps_arcn() - Draws an arc clockwise

# ps_clip

(PECL ps >= 1.1.0)

ps_clip — Clips drawing to current path

### Description

ps_clip(resource `$psdoc`): bool

Takes the current path and uses it to define the border of a clipping area. Everything drawn outside of that area will not be visible.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_closepath() - Closes path

# ps_close

(PECL ps >= 1.1.0)

ps_close — Closes a PostScript document

### Description

ps_close(resource `$psdoc`): bool

Closes the PostScript document.

This function writes the trailer of the PostScript document. It also writes the bookmark tree. ps_close() does not free any resources, which is done by ps_delete().

This function is also called by ps_delete() if it has not been called before.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_open_file() - Opens a file for output
- ps_delete() - Deletes all resources of a PostScript document

# ps_close_image

(PECL ps >= 1.1.0)

ps_close_image — Closes image and frees memory

### Description

ps_close_image(resource `$psdoc`, int `$imageid`): void|false

Closes an image and frees its resources. Once an image is closed it cannot be used anymore.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`imageid`

  Resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

### Return Values

Returns `null` on success or `false` on failure.

### See Also

- ps_open_image() - Reads an image for later placement
- ps_open_image_file() - Opens image from file

# ps_closepath

(PECL ps >= 1.1.0)

ps_closepath — Closes path

### Description

ps_closepath(resource `$psdoc`): bool

Connects the last point with the first point of a path. The resulting path can be used for stroking, filling, clipping, etc..

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_clip() - Clips drawing to current path
- ps_closepath_stroke() - Closes and strokes path

# ps_closepath_stroke

(PECL ps >= 1.1.0)

ps_closepath_stroke — Closes and strokes path

### Description

ps_closepath_stroke(resource `$psdoc`): bool

Connects the last point with first point of a path and draws the resulting closed line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_closepath() - Closes path

# ps_continue_text

(PECL ps >= 1.1.0)

ps_continue_text — Continue text in next line

### Description

ps_continue_text(resource `$psdoc`, string `$text`): bool

Output a text one line below the last line. The line spacing is taken from the value "leading" which must be set with ps_set_value(). The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text to output.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_show() - Output text
- ps_show_xy() - Output text at given position
- ps_show_boxed() - Output text in a box

# ps_curveto

(PECL ps >= 1.1.0)

ps_curveto — Draws a curve

### Description

ps_curveto(
resource `$psdoc`,
float `$x1`,
float `$y1`,
float `$x2`,
float `$y2`,
float `$x3`,
float `$y3`
): bool

Add a section of a cubic Bézier curve described by the three given control points to the current path.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x1`

  x-coordinate of first control point.

`y1`

  y-coordinate of first control point.

`x2`

  x-coordinate of second control point.

`y2`

  y-coordinate of second control point.

`x3`

  x-coordinate of third control point.

`y3`

  y-coordinate of third control point.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_lineto() - Draws a line

# ps_delete

(PECL ps >= 1.1.0)

ps_delete — Deletes all resources of a PostScript document

### Description

ps_delete(resource `$psdoc`): bool

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a trailor containing PostScript comments like the number of pages in the document and adding the bookmark hierarchy.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_close() - Closes a PostScript document

# ps_end_page

(PECL ps >= 1.1.0)

ps_end_page — End a page

### Description

ps_end_page(resource `$psdoc`): bool

Ends a page which was started with ps_begin_page(). Ending a page will leave the current drawing context, which e.g. requires to reload fonts if they were loading within the page, and to set many other drawing parameters like the line width, or color.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_begin_page() - Start a new page

# ps_end_pattern

(PECL ps >= 1.2.0)

ps_end_pattern — End a pattern

### Description

ps_end_pattern(resource `$psdoc`): bool

Ends a pattern which was started with ps_begin_pattern(). Once a pattern has been ended, it can be used like a color to fill areas.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_begin_pattern() - Start a new pattern

# ps_end_template

(PECL ps >= 1.2.0)

ps_end_template — End a template

### Description

ps_end_template(resource `$psdoc`): bool

Ends a template which was started with ps_begin_template(). Once a template has been ended, it can be used like an image.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_begin_template() - Start a new template

# ps_fill

(PECL ps >= 1.1.0)

ps_fill — Fills the current path

### Description

ps_fill(resource `$psdoc`): bool

Fills the path constructed with previously called drawing functions like ps_lineto().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_fill_stroke() - Fills and strokes the current path
- ps_stroke() - Draws the current path

# ps_fill_stroke

(PECL ps >= 1.1.0)

ps_fill_stroke — Fills and strokes the current path

### Description

ps_fill_stroke(resource `$psdoc`): bool

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_fill() - Fills the current path
- ps_stroke() - Draws the current path

# ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

### Description

ps_findfont(
resource `$psdoc`,
string `$fontname`,
string `$encoding`,
bool `$embed` = `false`
): int

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

The name of the afm file must be `fontname``.afm`. If the font shall be embedded the file `fontname``.pfb` containing the font outline must be present as well.

Calling ps_findfont() before the first page requires to output the postscript header which includes the BoundingBox for the whole document. Usually the BoundingBox is set with the first call of ps_begin_page() which now comes after ps_findfont(). Consequently the BoundingBox has not been set and a warning will be issued when ps_findfont() is called. In order to prevent this situation, one should call ps_set_parameter() to set the BoundingBox before ps_findfont() is called.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`fontname`

  The name of the font.

`encoding`

  ps_findfont() will try to load the file passed in the parameter `encoding`. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

  `encoding` can be `null` or the empty string if the default encoding (TeXBase1) shall be used.

  If the encoding is set to `builtin` then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

`embed`

  If set to a value >0 the font will be embedded into the document. This requires the font outline (.pfb file) to be present.

### Return Values

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

### See Also

- ps_begin_page() - Start a new page
- ps_setfont() - Sets font to use for following output

# ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

### Description

ps_get_buffer(resource `$psdoc`): string

This function is not implemented yet. It will always return an empty string. The idea for a later implementation is to write the contents of the postscript file into an internal buffer if in memory creation is requested, and retrieve the buffer content with this function. Currently, documents created in memory are send to the browser without buffering.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### See Also

- ps_open_file() - Opens a file for output

# ps_get_parameter

(PECL ps >= 1.1.0)

ps_get_parameter — Gets certain parameters

### Description

ps_get_parameter(resource `$psdoc`, string `$name`, float `$modifier` = ?): string|false

Gets several parameters which were directly set by ps_set_parameter() or indirectly by one of the other functions. Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

The parameter `name` can have the following values.

`fontname`

  The name of the currently active font or the font whose identifier is passed in parameter `modifier`.

`fontencoding`

  The encoding of the currently active font.

`dottedversion`

  The version of the underlying pslib library in the format <major>.<minor>.<subminor>

`scope`

  The current drawing scope. Can be object, document, null, page, pattern, path, template, prolog, font, glyph.

`ligaturedisolvechar`

  The character which dissolves a ligature. If your are using a font which contains the ligature `ff' and `|' is the char to dissolve the ligature, then `f|f' will result in two `f' instead of the ligature `ff'.

`imageencoding`

  The encoding used for encoding images. Can be either `hex` or `85`. hex encoding uses two bytes in the postscript file each byte in the image. 85 stand for Ascii85 encoding.

`linenumbermode`

  Set to `paragraph` if lines are numbered within a paragraph or `box` if they are numbered within the surrounding box.

`linebreak`

  Only used if text is output with ps_show_boxed(). If set to `true` a carriage return will add a line break.

`parbreak`

  Only used if text is output with ps_show_boxed(). If set to `true` a carriage return will start a new paragraph.

`hyphenation`

  Only used if text is output with ps_show_boxed(). If set to `true` the paragraph will be hyphenated if a hypen dictionary is set and exists.

`hyphendict`

  Filename of the dictionary used for hyphenation pattern.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`name`

  Name of the parameter.

`modifier`

  An identifier needed if a parameter of a resource is requested, e.g. the size of an image. In such a case the resource id is passed.

### Return Values

Returns the value of the parameter or `false` on failure.

### See Also

- ps_set_parameter() - Sets certain parameters

# ps_get_value

(PECL ps >= 1.1.0)

ps_get_value — Gets certain values

### Description

ps_get_value(resource `$psdoc`, string `$name`, float `$modifier` = ?): float

Gets several values which were set by ps_set_value(). Values are by definition float values.

The parameter `name` can have the following values.

`fontsize`

  The size of the currently active font or the font whose identifier is passed in parameter `modifier`.

`font`

  The currently active font itself.

`imagewidth`

  The width of the image whose id is passed in the parameter `modifier`.

`imageheight`

  The height of the image whose id is passed in the parameter `modifier`.

`capheight`

  The height of a capital M in the currently active font or the font whose identifier is passed in parameter `modifier`.

`ascender`

  The ascender of the currently active font or the font whose identifier is passed in parameter `modifier`.

`descender`

  The descender of the currently active font or the font whose identifier is passed in parameter `modifier`.

`italicangle`

  The italicangle of the currently active font or the font whose identifier is passed in parameter `modifier`.

`underlineposition`

  The underlineposition of the currently active font or the font whose identifier is passed in parameter `modifier`.

`underlinethickness`

  The underlinethickness of the currently active font or the font whose identifier is passed in parameter `modifier`.

`textx`

  The current x-position for text output.

`texty`

  The current y-position for text output.

`textrendering`

  The current mode for text rendering.

`textrise`

  The space by which text is risen above the base line.

`leading`

  The distance between text lines in points.

`wordspacing`

  The space between words as a multiple of the width of a space char.

`charspacing`

  The space between chars. If charspacing is != 0.0 ligatures will always be dissolved.

`hyphenminchars`

  Minimum number of chars hyphenated at the end of a word.

`parindent`

  Indention of the first n line in a paragraph.

`numindentlines`

  Number of line in a paragraph to indent if parindent != 0.0.

`parskip`

  Distance between paragraphs.

`linenumberspace`

  Overall space in front of each line for the line number.

`linenumbersep`

  Space between the line and the line number.

`major`

  The major version number of pslib.

`minor`

  The minor version number of pslib.

`subminor`, `revision`

  The subminor version number of pslib.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`name`

  Name of the value.

`modifier`

  The parameter `modifier` specifies the resource for which the value is to be retrieved. This can be the id of a font or an image.

### Return Values

Returns the value of the parameter or `false`.

### See Also

- ps_set_value() - Sets certain values

# ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

### Description

ps_hyphenate(resource `$psdoc`, string `$text`): array|false

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars (set by ps_set_value()) and the parameter hyphendict (set by ps_set_parameter()). hyphendict must be set before calling this function.

This function requires the locale category `LC_CTYPE` to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale for more information.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  `text` should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in `text` after which a hyphenation can take place.

### Return Values

An array of integers indicating the position of possible breaks in the text or `false` on failure.

### Examples

Example #1 Hyphennate a text

`<?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i<strlen($word); $i++) {
echo $word[$i];
if(in_array($i, $hyphens))
echo "-";
}
ps_delete($psdoc);
?>`

The above example will output:

    Ko-ordi-na-ten-sys-tem

### See Also

- ps_show_boxed() - Output text in a box
- locale(1)

# ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

### Description

ps_include_file(resource `$psdoc`, string `$file`): bool

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`file`

### Return Values

Returns `true` on success or `false` on failure.

# ps_lineto

(PECL ps >= 1.1.0)

ps_lineto — Draws a line

### Description

ps_lineto(resource `$psdoc`, float `$x`, float `$y`): bool

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  x-coordinate of the end point of the line.

`y`

  y-coordinate of the end point of the line.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Drawing a rectangle

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "rectangle.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Lineto example");
ps_begin_page($ps, 596, 842);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_stroke($ps);
ps_end_page($ps);
ps_delete($ps);
?>`

### See Also

- ps_moveto() - Sets current point

# ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

### Description

ps_makespotcolor(resource `$psdoc`, string `$name`, int `$reserved` = 0): int

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor(). When the document is not printed but displayed by an postscript viewer the given color in the specified color space is use.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`name`

  Name of the spot color, e.g. Pantone 5565.

### Return Values

The id of the new spot color or 0 in case of an error.

### Examples

Example #1 Creating and using a spot color

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");
ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);
ps_delete($ps);
?>`

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

### See Also

- ps_setcolor() - Sets current color

# ps_moveto

(PECL ps >= 1.1.0)

ps_moveto — Sets current point

### Description

ps_moveto(resource `$psdoc`, float `$x`, float `$y`): bool

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  x-coordinate of the point to move to.

`y`

  y-coordinate of the point to move to.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_lineto() - Draws a line

# ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

### Description

ps_new(): resource|false

Creates a new document instance. It does not create the file on disk or in memory, it just sets up everything. ps_new() is usually followed by a call of ps_open_file() to actually create the postscript document.

### Parameters

This function has no parameters.

### Return Values

Resource of PostScript document or `false` on failure. The return value is passed to all other functions as the first argument.

### See Also

- ps_delete() - Deletes all resources of a PostScript document

# ps_open_file

(PECL ps >= 1.1.0)

ps_open_file — Opens a file for output

### Description

ps_open_file(resource `$psdoc`, string `$filename` = ?): bool

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`filename`

  The name of the postscript file. If `filename` is not passed the document will be created in memory and all output will go straight to the browser.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_close() - Closes a PostScript document

# ps_open_image

(PECL ps >= 1.1.0)

ps_open_image — Reads an image for later placement

### Description

ps_open_image(
resource `$psdoc`,
string `$type`,
string `$source`,
string `$data`,
int `$length`,
int `$width`,
int `$height`,
int `$components`,
int `$bpc`,
string `$params`
): int

Reads an image which is already available in memory. The parameter `source` is currently not evaluated and assumed to be `memory`. The image data is a sequence of pixels starting in th upper left corner and ending in the lower right corner. Each pixel consists of `components` color components, and each component has `bpc` bits.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The type of the image. Possible values are `png`, `jpeg`, or `eps`.

`source`

  Not used.

`data`

  The image data.

`length`

  The length of the image data.

`width`

  The width of the image.

`height`

  The height of the image.

`components`

  The number of components for each pixel. This can be 1 (gray scale images), 3 (rgb images), or 4 (cmyk, rgba images).

`bpc`

  Number of bits per component (quite often 8).

`params`

### Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

### See Also

- ps_open_image_file() - Opens image from file
- ps_place_image() - Places image on the page
- ps_close_image() - Closes image and frees memory

# ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

### Description

ps_open_image_file(
resource `$psdoc`,
string `$type`,
string `$filename`,
string `$stringparam` = ?,
int `$intparam` = 0
): int

Loads an image for later use.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The type of the image. Possible values are `png`, `jpeg`, or `eps`.

`filename`

  The name of the file containing the image data.

`stringparam`

  Not used.

`intparam`

  Not used.

### Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

### See Also

- ps_open_image() - Reads an image for later placement
- ps_place_image() - Places image on the page
- ps_close_image() - Closes image and frees memory

# ps_open_memory_image

(PECL ps >= 1.1.0)

ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document

### Description

ps_open_memory_image(resource `$psdoc`, int `$gd`): int
Warning

This function is currently not documented; only its argument list is available.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`gd`

# ps_place_image

(PECL ps >= 1.1.0)

ps_place_image — Places image on the page

### Description

ps_place_image(
resource `$psdoc`,
int `$imageid`,
float `$x`,
float `$y`,
float `$scale`
): bool

Places a formerly loaded image on the page. The image can be scaled. If the image shall be rotated as well, you will have to rotate the coordinate system before with ps_rotate().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`imageid`

  The resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

`x`

  x-coordinate of the lower left corner of the image.

`y`

  y-coordinate of the lower left corner of the image.

`scale`

  The scaling factor for the image. A scale of 1.0 will result in a resolution of 72 dpi, because each pixel is equivalent to 1 point.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_open_image() - Reads an image for later placement
- ps_open_image_file() - Opens image from file

# ps_rect

(PECL ps >= 1.1.0)

ps_rect — Draws a rectangle

### Description

ps_rect(
resource `$psdoc`,
float `$x`,
float `$y`,
float `$width`,
float `$height`
): bool

Draws a rectangle with its lower left corner at (`x`, `y`). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  x-coordinate of the lower left corner of the rectangle.

`y`

  y-coordinate of the lower left corner of the rectangle.

`width`

  The width of the image.

`height`

  The height of the image.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_arc() - Draws an arc counterclockwise
- ps_cirle()
- ps_lineto() - Draws a line

# ps_restore

(PECL ps >= 1.1.0)

ps_restore — Restore previously save context

### Description

ps_restore(resource `$psdoc`): bool

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore(). All coordinate transformations, line style settings, color settings, etc. are being restored to the state before the call of ps_save().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_save() - Save current context

# ps_rotate

(PECL ps >= 1.1.0)

ps_rotate — Sets rotation factor

### Description

ps_rotate(resource `$psdoc`, float `$rot`): bool

Sets the rotation of the coordinate system.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`rot`

  Angle of rotation in degree.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Rotation of the coordinate system

`<?php
function rectangle($ps) {
ps_moveto($ps, 0, 0);
ps_lineto($ps, 0, 50);
ps_lineto($ps, 50, 50);
ps_lineto($ps, 50, 0);
ps_lineto($ps, 0, 0);
ps_stroke($ps);
}
$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);
ps_delete($ps);
?>`

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

### See Also

- ps_scale() - Sets scaling factor
- ps_translate() - Sets translation

# ps_save

(PECL ps >= 1.1.0)

ps_save — Save current context

### Description

ps_save(resource `$psdoc`): bool

Saves the current graphics context, containing colors, translation and rotation settings and some more. A saved context can be restored with ps_restore().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_restore() - Restore previously save context

# ps_scale

(PECL ps >= 1.1.0)

ps_scale — Sets scaling factor

### Description

ps_scale(resource `$psdoc`, float `$x`, float `$y`): bool

Sets horizontal and vertical scaling of the coordinate system.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  Scaling factor in horizontal direction.

`y`

  Scaling factor in vertical direction.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_rotate() - Sets rotation factor
- ps_translate() - Sets translation

# ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

### Description

ps_set_border_color(
resource `$psdoc`,
float `$red`,
float `$green`,
float `$blue`
): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the color of the rectangle's border line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`red`

  The red component of the border color.

`green`

  The green component of the border color.

`blue`

  The blue component of the border color.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_set_border_dash() - Sets length of dashes for border of annotations
- ps_set_border_style() - Sets border style of annotations

# ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

### Description

ps_set_border_dash(resource `$psdoc`, float `$black`, float `$white`): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the length of the black and white portion of a dashed border line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`black`

  The length of the dash.

`white`

  The length of the gap between dashes.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_set_border_color() - Sets color of border for annotations
- ps_set_border_style() - Sets border style of annotations

# ps_set_border_style

(PECL ps >= 1.1.0)

ps_set_border_style — Sets border style of annotations

### Description

ps_set_border_style(resource `$psdoc`, string `$style`, float `$width`): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the appearance and width of the border line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`style`

  `style` can be `solid` or `dashed`.

`width`

  The line width of the border.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_set_border_color() - Sets color of border for annotations
- ps_set_border_dash() - Sets length of dashes for border of annotations

# ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

### Description

ps_set_info(resource `$psdoc`, string `$key`, string `$value`): bool

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. If the document is converted to pdf this fields will also be used for the document information.

The `BoundingBox` is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

This function will have no effect anymore when the header of the postscript file has been already written. It must be called before the first page or the first call of ps_findfont().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`key`

  The name of the information field to set. The values which can be set are `Keywords`, `Subject`, `Title`, `Creator`, `Author`, `BoundingBox`, and `Orientation`. Be aware that some of them has a meaning to PostScript viewers.

`value`

  The value of the information field. The field `Orientation` can be set to either `Portrait` or `Landscape`. The `BoundingBox` is a string consisting of four numbers. The first two numbers are the coordinates of the lower left corner of the page. The last two numbers are the coordinates of the upper right corner.

  > Note:

  > Up to version 0.2.6 of pslib, the BoundingBox and Orientation will be overwritten by ps_begin_page(), unless ps_findfont() has been called before.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_findfont() - Loads a font
- ps_begin_page() - Start a new page

# ps_set_parameter

(PECL ps >= 1.1.0)

ps_set_parameter — Sets certain parameters

### Description

ps_set_parameter(resource `$psdoc`, string `$name`, string `$value`): bool

Sets several parameters which are used by many functions. Parameters are by definition string values.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`name`

  For a list of possible names see ps_get_parameter().

`value`

  The value of the parameter.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_get_parameters()
- ps_set_value() - Sets certain values

# ps_set_text_pos

(PECL ps >= 1.1.0)

ps_set_text_pos — Sets position for text output

### Description

ps_set_text_pos(resource `$psdoc`, float `$x`, float `$y`): bool

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing `textx` respectively `texty` as the value name.

If you want to output text at a certain position it is more convenient to use ps_show_xy() instead of setting the text position and calling ps_show().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  x-coordinate of the new text position.

`y`

  y-coordinate of the new text position.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Placing text at a given position

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "text.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Text placement example");
ps_begin_page($ps, 596, 842);
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_setfont($ps, $psfont, 8.0);
ps_show_xy($ps, "Some text at (100, 100)", 100, 100);
ps_set_value($ps, "textx", 100);
ps_set_value($ps, "texty", 120);
ps_show($ps, "Some text at (100, 120)");
ps_end_page($ps);
ps_delete($ps);
?>`

### See Also

- ps_set_value() - Sets certain values
- ps_show() - Output text

# ps_set_value

(PECL ps >= 1.1.0)

ps_set_value — Sets certain values

### Description

ps_set_value(resource `$psdoc`, string `$name`, float `$value`): bool

Sets several values which are used by many functions. Parameters are by definition float values.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`name`

  The `name` can be one of the following:

  textrendering

    The way how text is shown.

  textx

    The x coordinate for text output.

  texty

    The y coordinate for text output.

  wordspacing

    The distance between words relative to the width of a space.

  leading

    The distance between lines in pixels.

`value`

  The value of the parameter.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_get_value() - Gets certain values
- ps_set_parameter() - Sets certain parameters

# ps_setcolor

(PECL ps >= 1.1.0)

ps_setcolor — Sets current color

### Description

ps_setcolor(
resource `$psdoc`,
string `$type`,
string `$colorspace`,
float `$c1`,
float `$c2`,
float `$c3`,
float `$c4`
): bool

Sets the color for drawing, filling, or both.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The parameter `type` can be `both`, `fill`, or `fillstroke`.

`colorspace`

  The colorspace should be one of `gray`, `rgb`, `cmyk`, `spot`, `pattern`. Depending on the colorspace either only the first, the first three or all parameters will be used.

`c1`

  Depending on the colorspace this is either the red component (rgb), the cyan component (cmyk), the gray value (gray), the identifier of the spot color or the identifier of the pattern.

`c2`

  Depending on the colorspace this is either the green component (rgb), the magenta component (cmyk).

`c3`

  Depending on the colorspace this is either the blue component (rgb), the yellow component (cmyk).

`c4`

  This must only be set in cmyk colorspace and specifies the black component.

### Return Values

Returns `true` on success or `false` on failure.

### Notes

Caution

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if `fillstroke` were passed.

# ps_setdash

(PECL ps >= 1.1.0)

ps_setdash — Sets appearance of a dashed line

### Description

ps_setdash(resource `$psdoc`, float `$on`, float `$off`): bool

Sets the length of the black and white portions of a dashed line.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`on`

  The length of the dash.

`off`

  The length of the gap between dashes.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setpolydash() - Sets appearance of a dashed line

# ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

### Description

ps_setflat(resource `$psdoc`, float `$value`): bool

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`value`

  The `value` must be between 0.2 and 1.

### Return Values

Returns `true` on success or `false` on failure.

# ps_setfont

(PECL ps >= 1.1.0)

ps_setfont — Sets font to use for following output

### Description

ps_setfont(resource `$psdoc`, int `$fontid`, float `$size`): bool

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font results in an error.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`fontid`

  The font identifier as returned by ps_findfont().

`size`

  The size of the font.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_findfont() - Loads a font
- ps_set_text_pos() - Sets position for text output for an example.

# ps_setgray

(PECL ps >= 1.1.0)

ps_setgray — Sets gray value

### Description

ps_setgray(resource `$psdoc`, float `$gray`): bool

Sets the gray value for all following drawing operations.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`gray`

  The value must be between 0 (white) and 1 (black).

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setcolor() - Sets current color

# ps_setlinecap

(PECL ps >= 1.1.0)

ps_setlinecap — Sets appearance of line ends

### Description

ps_setlinecap(resource `$psdoc`, int `$type`): bool

Sets how line ends look like.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The type of line ends. Possible values are `PS_LINECAP_BUTT`, `PS_LINECAP_ROUND`, or `PS_LINECAP_SQUARED`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setlinejoin() - Sets how contected lines are joined
- ps_setlinewidth() - Sets width of a line
- ps_setmiterlimit() - Sets the miter limit

# ps_setlinejoin

(PECL ps >= 1.1.0)

ps_setlinejoin — Sets how contected lines are joined

### Description

ps_setlinejoin(resource `$psdoc`, int `$type`): bool

Sets how lines are joined.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The way lines are joined. Possible values are `PS_LINEJOIN_MITER`, `PS_LINEJOIN_ROUND`, or `PS_LINEJOIN_BEVEL`.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setlinecap() - Sets appearance of line ends
- ps_setlinewidth() - Sets width of a line
- ps_setmiterlimit() - Sets the miter limit

# ps_setlinewidth

(PECL ps >= 1.1.0)

ps_setlinewidth — Sets width of a line

### Description

ps_setlinewidth(resource `$psdoc`, float `$width`): bool

Sets the line width for all following drawing operations.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`width`

  The width of lines in points.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setlinecap() - Sets appearance of line ends
- ps_setlinejoin() - Sets how contected lines are joined
- ps_setmiterlimit() - Sets the miter limit

# ps_setmiterlimit

(PECL ps >= 1.1.0)

ps_setmiterlimit — Sets the miter limit

### Description

ps_setmiterlimit(resource `$psdoc`, float `$value`): bool

If two lines join in a small angle and the line join is set to `PS_LINEJOIN_MITER`, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`value`

  The maximum ratio between the miter length and the line width. Larger values (> 10) will result in very long spikes when two lines meet in a small angle. Keep the default unless you know what you are doing.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_setlinecap() - Sets appearance of line ends
- ps_setlinejoin() - Sets how contected lines are joined
- ps_setlinewidth() - Sets width of a line

# ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

### Description

ps_setoverprintmode(resource `$psdoc`, int `$mode`): bool

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`mode`

### Return Values

Returns `true` on success or `false` on failure.

# ps_setpolydash

(PECL ps >= 1.1.0)

ps_setpolydash — Sets appearance of a dashed line

### Description

ps_setpolydash(resource `$psdoc`, float `$arr`): bool

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`arr`

  `arr` is a list of length elements alternately for the black and white portion.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Drawing a dashed line

`<?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");
ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);
ps_delete($ps);
?>`

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

### See Also

- ps_setdash() - Sets appearance of a dashed line

# ps_shading

(PECL ps >= 1.3.0)

ps_shading — Creates a shading for later use

### Description

ps_shading(
resource `$psdoc`,
string `$type`,
float `$x0`,
float `$y0`,
float `$x1`,
float `$y1`,
float `$c1`,
float `$c2`,
float `$c3`,
float `$c4`,
string `$optlist`
): int|false

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for `pattern`.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`type`

  The type of shading can be either `radial` or `axial`. Each shading starts with the current fill color and ends with the given color values passed in the parameters `c1` to `c4` (see ps_setcolor() for their meaning).

`x0, x1, y0, y1`

  The coordinates `x0`, `y0`, `x1`, `y1` are the start and end point of the shading. If the type of shading is `radial` the two points are the middle points of a starting and ending circle.

`c1, c2, c3, c4`

  See ps_setcolor() for their meaning.

`optlist`

  If the shading is of type `radial` the `optlist` must also contain the parameters `r0` and `r1` with the radius of the start and end circle.

### Return Values

Returns the identifier of the pattern or `false` on failure.

### See Also

- ps_shading_pattern() - Creates a pattern based on a shading
- ps_shfill() - Fills an area with a shading

# ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

### Description

ps_shading_pattern(resource `$psdoc`, int `$shadingid`, string `$optlist`): int|false

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`shadingid`

  The identifier of a shading previously created with ps_shading().

`optlist`

  This argument is not currently used.

### Return Values

The identifier of the pattern or `false` on failure.

### See Also

- ps_shading() - Creates a shading for later use
- ps_shfill() - Fills an area with a shading

# ps_shfill

(PECL ps >= 1.3.0)

ps_shfill — Fills an area with a shading

### Description

ps_shfill(resource `$psdoc`, int `$shadingid`): bool

Fills an area with a shading, which has to be created before with ps_shading(). This is an alternative way to creating a pattern from a shading ps_shading_pattern() and using the pattern as the filling color.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`shadingid`

  The identifier of a shading previously created with ps_shading().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_shading() - Creates a shading for later use
- ps_shading_pattern() - Creates a pattern based on a shading

# ps_show

(PECL ps >= 1.1.0)

ps_show — Output text

### Description

ps_show(resource `$psdoc`, string `$text`): bool

Output a text at the current text position. The text position can be set by storing the x and y coordinates into the values `textx` and `texty` with the function ps_set_value(). The function will issue an error if a font was not set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

  Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

  Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

  Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

  Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

  Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

  Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text to be output.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_continue_text() - Continue text in next line
- ps_show_xy() - Output text at given position
- ps_setfont() - Sets font to use for following output

# ps_show_boxed

(PECL ps >= 1.1.0)

ps_show_boxed — Output text in a box

### Description

ps_show_boxed(
resource `$psdoc`,
string `$text`,
float `$left`,
float `$bottom`,
float `$width`,
float `$height`,
string `$hmode`,
string `$feature` = ?
): int

Outputs a text in a given box. The lower left corner of the box is at (`left`, `bottom`). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter `hyphenation` is set to `true` and the parameter `hyphendict` contains a valid filename for a hyphenation file. The line spacing is taken from the value `leading`. Paragraphs can be separated by an empty line just like in TeX. If the value `parindent` is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter `numindentlines`. In order to prevent indenting of the first m paragraphs set the value `parindentskip` to a positive number.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text to be output into the given box.

`left`

  x-coordinate of the lower left corner of the box.

`bottom`

  y-coordinate of the lower left corner of the box.

`width`

  Width of the box.

`height`

  Height of the box.

`hmode`

  The parameter `hmode` can be `justify`, `fulljustify`, `right`, `left`, or `center`. The difference of `justify` and `fulljustify` just affects the last line of the box. In `fulljustify` mode the last line will be left and right justified unless this is also the last line of paragraph. In `justify` mode it will always be left justified.

`feature`

#### Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output, the following parameters and values are evaluated.

leading (value)

  Distance between baselines of two consecutive lines.

linebreak (parameter)

  Set to `true` if you want a carriage return to start a new line instead of treating it as a space. Defaults to `false`.

parbreak (parameter)

  Set to `true` if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to `true`.

hyphenation (parameter)

  Set to `true` in order to turn hyphenation on. This requires a dictionary to be set with the parameter `hyphendict`. Defaults to `false`.

hyphendict (parameter)

  Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

  The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

  Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value `numindentlines`.

parskip (value)

  Set the amount of extra space in pixel between paragraphs. Defaults to `0` which will result in a normal line distance.

numindentlines (value)

  Number of lines from the start of the paragraph which will be indented. Defaults to `1`.

parindentskip (value)

  Number of paragraphs in the box whose first lines will not be indented. This defaults to `0`. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to `1`.

linenumbermode (parameter)

  Set how lines are to be numbered. Possible values are `box` for numbering lines in the whole box or `paragraph` to number lines within each paragraph.

linenumberspace (value)

  The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to `20`.

linenumbersep (value)

  The space between the column with line numbers and the line itself. Defaults to `5`.

#### Hyphenation

Text is hyphenated if the parameter `hyphenation` is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

- /usr/share/apps/koffice/hyphdicts/
- /usr/lib/scribus/dicts/
- /usr/lib/openoffice/share/dict/ooo/

Currently scribus appears to have the most complete hyphenation dictionaries.

### Return Values

Number of characters that could not be written.

### See Also

- ps_continue_text() - Continue text in next line

# ps_show_xy

(PECL ps >= 1.1.0)

ps_show_xy — Output text at given position

### Description

ps_show_xy(
resource `$psdoc`,
string `$text`,
float `$x`,
float `$y`
): bool

Output a text at the given text position.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text to be output.

`x`

  x-coordinate of the lower left corner of the box surrounding the text.

`y`

  y-coordinate of the lower left corner of the box surrounding the text.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_continue_text() - Continue text in next line
- ps_show() - Output text

# ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

### Description

ps_show_xy2(
resource `$psdoc`,
string `$text`,
int `$len`,
float `$xcoor`,
float `$ycoor`
): bool
Warning

This function is currently not documented; only its argument list is available.

### Return Values

Returns `true` on success or `false` on failure.

# ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

### Description

ps_show2(resource `$psdoc`, string `$text`, int `$len`): bool

Output text at the current position. Do not print more than `len` characters.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text to be output.

`len`

  The maximum number of characters to print.

### Return Values

Returns `true` on success or `false` on failure.

# ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

### Description

ps_string_geometry(
resource `$psdoc`,
string `$text`,
int `$fontid` = 0,
float `$size` = 0.0
): array

This function is similar to ps_stringwidth() but returns an array of dimensions containing the width, ascender, and descender of the text.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text for which the geometry is to be calculated.

`fontid`

  The identifier of the font to be used. If not font is specified the current font will be used.

`size`

  The size of the font. If no size is specified the current size is used.

### Return Values

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

### See Also

- ps_continue_text() - Continue text in next line
- ps_stringwidth() - Gets width of a string

# ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

### Description

ps_stringwidth(
resource `$psdoc`,
string `$text`,
int `$fontid` = 0,
float `$size` = 0.0
): float

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`text`

  The text for which the width is to be calculated.

`fontid`

  The identifier of the font to be used. If not font is specified the current font will be used.

`size`

  The size of the font. If no size is specified the current size is used.

### Return Values

Width of a string in points.

### See Also

- ps_string_geometry() - Gets geometry of a string

# ps_stroke

(PECL ps >= 1.1.0)

ps_stroke — Draws the current path

### Description

ps_stroke(resource `$psdoc`): bool

Draws the path constructed with previously called drawing functions like ps_lineto().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_closepath_stroke() - Closes and strokes path
- ps_fill() - Fills the current path
- ps_fill_stroke() - Fills and strokes the current path

# ps_symbol

(PECL ps >= 1.2.0)

ps_symbol — Output a glyph

### Description

ps_symbol(resource `$psdoc`, int `$ord`): bool

Output the glyph at position `ord` in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`ord`

  The position of the glyph in the font encoding vector.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- ps_symbol_name() - Gets name of a glyph
- ps_symbol_width() - Gets width of a glyph

# ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

### Description

ps_symbol_name(resource `$psdoc`, int `$ord`, int `$fontid` = 0): string

This function needs an Adobe font metrics file to know which glyphs are available.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`ord`

  The parameter `ord` is the position of the glyph in the font encoding vector.

`fontid`

  The identifier of the font to be used. If not font is specified the current font will be used.

### Return Values

The name of a glyph in the given font.

### See Also

- ps_symbol() - Output a glyph
- ps_symbol_width() - Gets width of a glyph

# ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

### Description

ps_symbol_width(
resource `$psdoc`,
int `$ord`,
int `$fontid` = 0,
float `$size` = 0.0
): float

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`ord`

  The position of the glyph in the font encoding vector.

`fontid`

  The identifier of the font to be used. If not font is specified the current font will be used.

`size`

  The size of the font. If no size is specified the current size is used.

### Return Values

The width of a glyph in points.

### See Also

- ps_symbol() - Output a glyph
- ps_symbol_name() - Gets name of a glyph

# ps_translate

(PECL ps >= 1.1.0)

ps_translate — Sets translation

### Description

ps_translate(resource `$psdoc`, float `$x`, float `$y`): bool

Sets a new initial point of the coordinate system.

### Parameters

`psdoc`

  Resource identifier of the postscript file as returned by ps_new().

`x`

  x-coordinate of the origin of the translated coordinate system.

`y`

  y-coordinate of the origin of the translated coordinate system.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 Translation of the coordinate system

`<?php
function rectangle($ps) {
ps_moveto($ps, 0, 0);
ps_lineto($ps, 0, 50);
ps_lineto($ps, 50, 50);
ps_lineto($ps, 50, 0);
ps_lineto($ps, 0, 0);
ps_stroke($ps);
}
$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
print "Cannot open PostScript file\n";
exit;
}
ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);
ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);
ps_delete($ps);
?>`

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to be undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

### See Also

- ps_scale() - Sets scaling factor
- ps_rotate() - Sets rotation factor

## Table of Contents

- ps_add_bookmark — Add bookmark to current page
- ps_add_launchlink — Adds link which launches file
- ps_add_locallink — Adds link to a page in the same document
- ps_add_note — Adds note to current page
- ps_add_pdflink — Adds link to a page in a second pdf document
- ps_add_weblink — Adds link to a web location
- ps_arc — Draws an arc counterclockwise
- ps_arcn — Draws an arc clockwise
- ps_begin_page — Start a new page
- ps_begin_pattern — Start a new pattern
- ps_begin_template — Start a new template
- ps_circle — Draws a circle
- ps_clip — Clips drawing to current path
- ps_close — Closes a PostScript document
- ps_close_image — Closes image and frees memory
- ps_closepath — Closes path
- ps_closepath_stroke — Closes and strokes path
- ps_continue_text — Continue text in next line
- ps_curveto — Draws a curve
- ps_delete — Deletes all resources of a PostScript document
- ps_end_page — End a page
- ps_end_pattern — End a pattern
- ps_end_template — End a template
- ps_fill — Fills the current path
- ps_fill_stroke — Fills and strokes the current path
- ps_findfont — Loads a font
- ps_get_buffer — Fetches the full buffer containig the generated PS data
- ps_get_parameter — Gets certain parameters
- ps_get_value — Gets certain values
- ps_hyphenate — Hyphenates a word
- ps_include_file — Reads an external file with raw PostScript code
- ps_lineto — Draws a line
- ps_makespotcolor — Create spot color
- ps_moveto — Sets current point
- ps_new — Creates a new PostScript document object
- ps_open_file — Opens a file for output
- ps_open_image — Reads an image for later placement
- ps_open_image_file — Opens image from file
- ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
- ps_place_image — Places image on the page
- ps_rect — Draws a rectangle
- ps_restore — Restore previously save context
- ps_rotate — Sets rotation factor
- ps_save — Save current context
- ps_scale — Sets scaling factor
- ps_set_border_color — Sets color of border for annotations
- ps_set_border_dash — Sets length of dashes for border of annotations
- ps_set_border_style — Sets border style of annotations
- ps_set_info — Sets information fields of document
- ps_set_parameter — Sets certain parameters
- ps_set_text_pos — Sets position for text output
- ps_set_value — Sets certain values
- ps_setcolor — Sets current color
- ps_setdash — Sets appearance of a dashed line
- ps_setflat — Sets flatness
- ps_setfont — Sets font to use for following output
- ps_setgray — Sets gray value
- ps_setlinecap — Sets appearance of line ends
- ps_setlinejoin — Sets how contected lines are joined
- ps_setlinewidth — Sets width of a line
- ps_setmiterlimit — Sets the miter limit
- ps_setoverprintmode — Sets overprint mode
- ps_setpolydash — Sets appearance of a dashed line
- ps_shading — Creates a shading for later use
- ps_shading_pattern — Creates a pattern based on a shading
- ps_shfill — Fills an area with a shading
- ps_show — Output text
- ps_show_boxed — Output text in a box
- ps_show_xy — Output text at given position
- ps_show_xy2 — Output text at position
- ps_show2 — Output a text at current position
- ps_string_geometry — Gets geometry of a string
- ps_stringwidth — Gets width of a string
- ps_stroke — Draws the current path
- ps_symbol — Output a glyph
- ps_symbol_name — Gets name of a glyph
- ps_symbol_width — Gets width of a glyph
- ps_translate — Sets translation

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- PS Functions
  - ps_add_bookmark — Add bookmark to current page
  - ps_add_launchlink — Adds link which launches file
  - ps_add_locallink — Adds link to a page in the same document
  - ps_add_note — Adds note to current page
  - ps_add_pdflink — Adds link to a page in a second pdf document
  - ps_add_weblink — Adds link to a web location
  - ps_arc — Draws an arc counterclockwise
  - ps_arcn — Draws an arc clockwise
  - ps_begin_page — Start a new page
  - ps_begin_pattern — Start a new pattern
  - ps_begin_template — Start a new template
  - ps_circle — Draws a circle
  - ps_clip — Clips drawing to current path
  - ps_close — Closes a PostScript document
  - ps_close_image — Closes image and frees memory
  - ps_closepath — Closes path
  - ps_closepath_stroke — Closes and strokes path
  - ps_continue_text — Continue text in next line
  - ps_curveto — Draws a curve
  - ps_delete — Deletes all resources of a PostScript document
  - ps_end_page — End a page
  - ps_end_pattern — End a pattern
  - ps_end_template — End a template
  - ps_fill — Fills the current path
  - ps_fill_stroke — Fills and strokes the current path
  - ps_findfont — Loads a font
  - ps_get_buffer — Fetches the full buffer containig the generated PS data
  - ps_get_parameter — Gets certain parameters
  - ps_get_value — Gets certain values
  - ps_hyphenate — Hyphenates a word
  - ps_include_file — Reads an external file with raw PostScript code
  - ps_lineto — Draws a line
  - ps_makespotcolor — Create spot color
  - ps_moveto — Sets current point
  - ps_new — Creates a new PostScript document object
  - ps_open_file — Opens a file for output
  - ps_open_image — Reads an image for later placement
  - ps_open_image_file — Opens image from file
  - ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
  - ps_place_image — Places image on the page
  - ps_rect — Draws a rectangle
  - ps_restore — Restore previously save context
  - ps_rotate — Sets rotation factor
  - ps_save — Save current context
  - ps_scale — Sets scaling factor
  - ps_set_border_color — Sets color of border for annotations
  - ps_set_border_dash — Sets length of dashes for border of annotations
  - ps_set_border_style — Sets border style of annotations
  - ps_set_info — Sets information fields of document
  - ps_set_parameter — Sets certain parameters
  - ps_set_text_pos — Sets position for text output
  - ps_set_value — Sets certain values
  - ps_setcolor — Sets current color
  - ps_setdash — Sets appearance of a dashed line
  - ps_setflat — Sets flatness
  - ps_setfont — Sets font to use for following output
  - ps_setgray — Sets gray value
  - ps_setlinecap — Sets appearance of line ends
  - ps_setlinejoin — Sets how contected lines are joined
  - ps_setlinewidth — Sets width of a line
  - ps_setmiterlimit — Sets the miter limit
  - ps_setoverprintmode — Sets overprint mode
  - ps_setpolydash — Sets appearance of a dashed line
  - ps_shading — Creates a shading for later use
  - ps_shading_pattern — Creates a pattern based on a shading
  - ps_shfill — Fills an area with a shading
  - ps_show — Output text
  - ps_show_boxed — Output text in a box
  - ps_show_xy — Output text at given position
  - ps_show_xy2 — Output text at position
  - ps_show2 — Output a text at current position
  - ps_string_geometry — Gets geometry of a string
  - ps_stringwidth — Gets width of a string
  - ps_stroke — Draws the current path
  - ps_symbol — Output a glyph
  - ps_symbol_name — Gets name of a glyph
  - ps_symbol_width — Gets width of a glyph
  - ps_translate — Sets translation

# RpmInfo

# Introduction

This extension enables you to retrieve information from RPM files or from the installed RPMs database.

It also provides a `rpm` stream wrapper to retrieve RPM content (since version 1.0.0 with librpm >= 4.13).

# Installing/Configuring

## Table of Contents

- Requirements
- Installation via PECL

## Requirements

This extension requires » librpm version 4.11.3 or higher.

## Installation via PECL

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: » https://pecl.php.net/package/rpminfo.

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

Miscellaneous constants
`RPMVERSION` (string)
  System librpm version.

RPM Senses
`RPMSENSE_ANY` (int)
`RPMSENSE_LESS` (int)
`RPMSENSE_GREATER` (int)
`RPMSENSE_EQUAL` (int)
`RPMSENSE_POSTTRANS` (int)
`RPMSENSE_PREREQ` (int)
`RPMSENSE_PRETRANS` (int)
`RPMSENSE_INTERP` (int)
`RPMSENSE_SCRIPT_PRE` (int)
`RPMSENSE_SCRIPT_POST` (int)
`RPMSENSE_SCRIPT_PREUN` (int)
`RPMSENSE_SCRIPT_POSTUN` (int)
`RPMSENSE_SCRIPT_VERIFY` (int)
`RPMSENSE_FIND_REQUIRES` (int)
`RPMSENSE_FIND_PROVIDES` (int)
`RPMSENSE_TRIGGERIN` (int)
`RPMSENSE_TRIGGERUN` (int)
`RPMSENSE_TRIGGERPOSTUN` (int)
`RPMSENSE_MISSINGOK` (int)
`RPMSENSE_RPMLIB` (int)
`RPMSENSE_TRIGGERPREIN` (int)
`RPMSENSE_KEYRING` (int)
`RPMSENSE_CONFIG` (int)

RPM Mire
`RPMMIRE_DEFAULT` (int)
  Search pattern is a regular expression with `\.`, `.*`, and `^...$` added.
`RPMMIRE_STRCMP` (int)
  Search pattern is a string, using `strcmp(3)`.
`RPMMIRE_REGEX` (int)
  Search pattern is a regular expression, using `regcomp(3)`.
`RPMMIRE_GLOB` (int)
  Search pattern is a glob expression, using `fnmatch(3)`.

RPM tags
`RPMTAG_ARCH` (int)
`RPMTAG_ARCHSUFFIX` (int)
  Requires librpm >= 4.18
`RPMTAG_ARCHIVESIZE` (int)
`RPMTAG_BASENAMES` (int)
  Name (not path) of files, with database index.
`RPMTAG_BUGURL` (int)
`RPMTAG_BUILDARCHS` (int)
`RPMTAG_BUILDHOST` (int)
`RPMTAG_BUILDTIME` (int)
`RPMTAG_C` (int)
`RPMTAG_CHANGELOGNAME` (int)
`RPMTAG_CHANGELOGTEXT` (int)
`RPMTAG_CHANGELOGTIME` (int)
`RPMTAG_CLASSDICT` (int)
`RPMTAG_CONFLICTFLAGS` (int)
`RPMTAG_CONFLICTNAME` (int)
  Conflicting dependencies, with database index.
`RPMTAG_CONFLICTNEVRS` (int)
`RPMTAG_CONFLICTS` (int)
`RPMTAG_CONFLICTVERSION` (int)
`RPMTAG_COOKIE` (int)
`RPMTAG_DBINSTANCE` (int)
`RPMTAG_DEPENDSDICT` (int)
`RPMTAG_DESCRIPTION` (int)
`RPMTAG_DIRINDEXES` (int)
`RPMTAG_DIRNAMES` (int)
  Directory of files, with database index.
`RPMTAG_DISTRIBUTION` (int)
`RPMTAG_DISTTAG` (int)
`RPMTAG_DISTURL` (int)
`RPMTAG_DSAHEADER` (int)
`RPMTAG_E` (int)
`RPMTAG_ENCODING` (int)
`RPMTAG_ENHANCEFLAGS` (int)
`RPMTAG_ENHANCENAME` (int)
  Weak dependencies, with database index, requires librpm >= 4.13.
`RPMTAG_ENHANCENEVRS` (int)
`RPMTAG_ENHANCES` (int)
`RPMTAG_ENHANCEVERSION` (int)
`RPMTAG_EPOCH` (int)
`RPMTAG_EPOCHNUM` (int)
`RPMTAG_EVR` (int)
`RPMTAG_EXCLUDEARCH` (int)
`RPMTAG_EXCLUDEOS` (int)
`RPMTAG_EXCLUSIVEARCH` (int)
`RPMTAG_EXCLUSIVEOS` (int)
`RPMTAG_FILECAPS` (int)
`RPMTAG_FILECLASS` (int)
`RPMTAG_FILECOLORS` (int)
`RPMTAG_FILECONTEXTS` (int)
`RPMTAG_FILEDEPENDSN` (int)
`RPMTAG_FILEDEPENDSX` (int)
`RPMTAG_FILEDEVICES` (int)
`RPMTAG_FILEDIGESTALGO` (int)
`RPMTAG_FILEDIGESTS` (int)
`RPMTAG_FILEFLAGS` (int)
`RPMTAG_FILEGROUPNAME` (int)
`RPMTAG_FILEINODES` (int)
`RPMTAG_FILELANGS` (int)
`RPMTAG_FILELINKTOS` (int)
`RPMTAG_FILEMD5S` (int)
`RPMTAG_FILEMODES` (int)
`RPMTAG_FILEMTIMES` (int)
`RPMTAG_FILENAMES` (int)
`RPMTAG_FILENLINKS` (int)
`RPMTAG_FILEPROVIDE` (int)
`RPMTAG_FILERDEVS` (int)
`RPMTAG_FILEREQUIRE` (int)
`RPMTAG_FILESIGNATURELENGTH` (int)
`RPMTAG_FILESIGNATURES` (int)
`RPMTAG_FILESIZES` (int)
`RPMTAG_FILESTATES` (int)
`RPMTAG_FILETRIGGERCONDS` (int)
`RPMTAG_FILETRIGGERFLAGS` (int)
`RPMTAG_FILETRIGGERINDEX` (int)
`RPMTAG_FILETRIGGERNAME` (int)
  File trigger name, with database index, requires librpm >= 4.13.
`RPMTAG_FILETRIGGERPRIORITIES` (int)
`RPMTAG_FILETRIGGERSCRIPTFLAGS` (int)
`RPMTAG_FILETRIGGERSCRIPTPROG` (int)
`RPMTAG_FILETRIGGERSCRIPTS` (int)
`RPMTAG_FILETRIGGERTYPE` (int)
`RPMTAG_FILETRIGGERVERSION` (int)
`RPMTAG_FILEUSERNAME` (int)
`RPMTAG_FILEVERIFYFLAGS` (int)
`RPMTAG_FSCONTEXTS` (int)
`RPMTAG_GIF` (int)
`RPMTAG_GROUP` (int)
  Group of the package, with database index.
`RPMTAG_HDRID` (int)
  Deprecated, use `RPMTAG_SHA1HEADER` instead. Removed in librpm 6.
`RPMTAG_HEADERCOLOR` (int)
`RPMTAG_HEADERI18NTABLE` (int)
`RPMTAG_HEADERIMAGE` (int)
`RPMTAG_HEADERIMMUTABLE` (int)
`RPMTAG_HEADERREGIONS` (int)
`RPMTAG_HEADERSIGNATURES` (int)
`RPMTAG_ICON` (int)
`RPMTAG_INSTALLCOLOR` (int)
`RPMTAG_INSTALLTID` (int)
  Installation transaction ID, with database index.
`RPMTAG_INSTALLTIME` (int)
`RPMTAG_INSTFILENAMES` (int)
  Path of files, with database index.
`RPMTAG_INSTPREFIXES` (int)
`RPMTAG_LICENSE` (int)
`RPMTAG_LONGARCHIVESIZE` (int)
`RPMTAG_LONGFILESIZES` (int)
`RPMTAG_LONGSIGSIZE` (int)
`RPMTAG_LONGSIZE` (int)
`RPMTAG_MODULARITYLABEL` (int)
`RPMTAG_N` (int)
`RPMTAG_NAME` (int)
  Package name, with database index.
`RPMTAG_NEVR` (int)
`RPMTAG_NEVRA` (int)
`RPMTAG_NOPATCH` (int)
`RPMTAG_NOSOURCE` (int)
`RPMTAG_NVR` (int)
`RPMTAG_NVRA` (int)
`RPMTAG_O` (int)
`RPMTAG_OBSOLETEFLAGS` (int)
`RPMTAG_OBSOLETENAME` (int)
  Obsoleted packages, with database index.
`RPMTAG_OBSOLETENEVRS` (int)
`RPMTAG_OBSOLETES` (int)
`RPMTAG_OBSOLETEVERSION` (int)
`RPMTAG_OLDENHANCES` (int)
`RPMTAG_OLDENHANCESFLAGS` (int)
`RPMTAG_OLDENHANCESNAME` (int)
`RPMTAG_OLDENHANCESVERSION` (int)
`RPMTAG_OLDFILENAMES` (int)
`RPMTAG_OLDSUGGESTS` (int)
`RPMTAG_OLDSUGGESTSFLAGS` (int)
`RPMTAG_OLDSUGGESTSNAME` (int)
`RPMTAG_OLDSUGGESTSVERSION` (int)
`RPMTAG_OPTFLAGS` (int)
`RPMTAG_ORDERFLAGS` (int)
`RPMTAG_ORDERNAME` (int)
`RPMTAG_ORDERVERSION` (int)
`RPMTAG_ORIGBASENAMES` (int)
`RPMTAG_ORIGDIRINDEXES` (int)
`RPMTAG_ORIGDIRNAMES` (int)
`RPMTAG_ORIGFILENAMES` (int)
`RPMTAG_OS` (int)
`RPMTAG_P` (int)
`RPMTAG_PACKAGER` (int)
`RPMTAG_PATCH` (int)
`RPMTAG_PATCHESFLAGS` (int)
`RPMTAG_PATCHESNAME` (int)
`RPMTAG_PATCHESVERSION` (int)
`RPMTAG_PAYLOADCOMPRESSOR` (int)
`RPMTAG_PAYLOADDIGEST` (int)
`RPMTAG_PAYLOADDIGESTALT` (int)
  With librpm >= 4.16.
`RPMTAG_PAYLOADDIGESTALGO` (int)
`RPMTAG_PAYLOADFLAGS` (int)
`RPMTAG_PAYLOADFORMAT` (int)
`RPMTAG_PKGID` (int)
  Deprecated, use `RPMTAG_SIGMD5` instead. Removed in librpm 6.
`RPMTAG_PLATFORM` (int)
`RPMTAG_POLICIES` (int)
`RPMTAG_POLICYFLAGS` (int)
`RPMTAG_POLICYNAMES` (int)
`RPMTAG_POLICYTYPES` (int)
`RPMTAG_POLICYTYPESINDEXES` (int)
`RPMTAG_POSTIN` (int)
`RPMTAG_POSTINFLAGS` (int)
`RPMTAG_POSTINPROG` (int)
`RPMTAG_POSTTRANS` (int)
`RPMTAG_POSTTRANSFLAGS` (int)
`RPMTAG_POSTTRANSPROG` (int)
`RPMTAG_POSTUN` (int)
`RPMTAG_POSTUNFLAGS` (int)
`RPMTAG_POSTUNPROG` (int)
`RPMTAG_POSTUNTRANS` (int)
  Requires librpm >= 4.19
`RPMTAG_POSTUNTRANSFLAGS` (int)
  Requires librpm >= 4.19
`RPMTAG_POSTUNTRANSPROG` (int)
  Requires librpm >= 4.19
`RPMTAG_PREFIXES` (int)
`RPMTAG_PREIN` (int)
`RPMTAG_PREINFLAGS` (int)
`RPMTAG_PREINPROG` (int)
`RPMTAG_PRETRANS` (int)
`RPMTAG_PRETRANSFLAGS` (int)
`RPMTAG_PRETRANSPROG` (int)
`RPMTAG_PREUN` (int)
`RPMTAG_PREUNFLAGS` (int)
`RPMTAG_PREUNPROG` (int)
`RPMTAG_PREUNTRANS` (int)
  Requires librpm >= 4.19
`RPMTAG_PREUNTRANSFLAGS` (int)
  Requires librpm >= 4.19
`RPMTAG_PREUNTRANSPROG` (int)
  Requires librpm >= 4.19
`RPMTAG_PROVIDEFLAGS` (int)
`RPMTAG_PROVIDENAME` (int)
  Provided dependencies, with database index.
`RPMTAG_PROVIDENEVRS` (int)
`RPMTAG_PROVIDES` (int)
`RPMTAG_PROVIDEVERSION` (int)
`RPMTAG_PUBKEYS` (int)
`RPMTAG_R` (int)
`RPMTAG_RECOMMENDFLAGS` (int)
`RPMTAG_RECOMMENDNAME` (int)
  Recommended weak dependencies, with database index, requires librpm >= 4.13.
`RPMTAG_RECOMMENDNEVRS` (int)
`RPMTAG_RECOMMENDS` (int)
`RPMTAG_RECOMMENDVERSION` (int)
`RPMTAG_RECONTEXTS` (int)
`RPMTAG_RELEASE` (int)
`RPMTAG_REMOVETID` (int)
`RPMTAG_REQUIREFLAGS` (int)
`RPMTAG_REQUIRENAME` (int)
  Required dependencies, with database index.
`RPMTAG_REQUIRENEVRS` (int)
`RPMTAG_REQUIRES` (int)
`RPMTAG_REQUIREVERSION` (int)
`RPMTAG_RPMVERSION` (int)
`RPMTAG_RSAHEADER` (int)
`RPMTAG_SHA1HEADER` (int)
  SHA1 signature, with database index.
`RPMTAG_SHA256HEADER` (int)
`RPMTAG_SIGGPG` (int)
`RPMTAG_SIGMD5` (int)
  MD5 signature, with database index.
`RPMTAG_SIGPGP` (int)
`RPMTAG_SIGSIZE` (int)
`RPMTAG_SIZE` (int)
`RPMTAG_SOURCE` (int)
`RPMTAG_SOURCEPACKAGE` (int)
`RPMTAG_SOURCEPKGID` (int)
`RPMTAG_SOURCERPM` (int)
`RPMTAG_SPEC` (int)
  Requires librpm >= 4.18
`RPMTAG_SUGGESTFLAGS` (int)
`RPMTAG_SUGGESTNAME` (int)
  Suggested weak dependencies, with database index, requires librpm >= 4.13.
`RPMTAG_SUGGESTNEVRS` (int)
`RPMTAG_SUGGESTS` (int)
`RPMTAG_SUGGESTVERSION` (int)
`RPMTAG_SUMMARY` (int)
`RPMTAG_SUPPLEMENTFLAGS` (int)
`RPMTAG_SUPPLEMENTNAME` (int)
  Weak dependencies, with database index, requires librpm >= 4.13.
`RPMTAG_SUPPLEMENTNEVRS` (int)
`RPMTAG_SUPPLEMENTS` (int)
`RPMTAG_SUPPLEMENTVERSION` (int)
`RPMTAG_SYSUSERS` (int)
  Requires librpm >= 4.19
`RPMTAG_TRANSFILETRIGGERCONDS` (int)
`RPMTAG_TRANSFILETRIGGERFLAGS` (int)
`RPMTAG_TRANSFILETRIGGERINDEX` (int)
`RPMTAG_TRANSFILETRIGGERNAME` (int)
  Transaction file trigger name, with database index, requires librpm >= 4.13.
`RPMTAG_TRANSFILETRIGGERPRIORITIES` (int)
`RPMTAG_TRANSFILETRIGGERSCRIPTFLAGS` (int)
`RPMTAG_TRANSFILETRIGGERSCRIPTPROG` (int)
`RPMTAG_TRANSFILETRIGGERSCRIPTS` (int)
`RPMTAG_TRANSFILETRIGGERTYPE` (int)
`RPMTAG_TRANSFILETRIGGERVERSION` (int)
`RPMTAG_TRANSLATIONURL` (int)
  Requires librpm >= 4.18
`RPMTAG_TRIGGERCONDS` (int)
`RPMTAG_TRIGGERFLAGS` (int)
`RPMTAG_TRIGGERINDEX` (int)
`RPMTAG_TRIGGERNAME` (int)
  Trigger name, with database index.
`RPMTAG_TRIGGERSCRIPTFLAGS` (int)
`RPMTAG_TRIGGERSCRIPTPROG` (int)
`RPMTAG_TRIGGERSCRIPTS` (int)
`RPMTAG_TRIGGERTYPE` (int)
`RPMTAG_TRIGGERVERSION` (int)
`RPMTAG_UPSTREAMRELEASES` (int)
  Requires librpm >= 4.18
`RPMTAG_URL` (int)
`RPMTAG_V` (int)
`RPMTAG_VCS` (int)
`RPMTAG_VENDOR` (int)
`RPMTAG_VERBOSE` (int)
`RPMTAG_VERIFYSCRIPT` (int)
`RPMTAG_VERIFYSCRIPTFLAGS` (int)
`RPMTAG_VERIFYSCRIPTPROG` (int)
`RPMTAG_VERITYSIGNATUREALGO` (int)
  With librpm >= 4.17.
`RPMTAG_VERITYSIGNATURES` (int)
  With librpm >= 4.17.
`RPMTAG_VERSION` (int)
`RPMTAG_XPM` (int)

# RpmInfo Functions

# rpmaddtag

(PECL rpminfo >= 0.5.0)

rpmaddtag — Add tag retrieved in query

### Description

rpmaddtag(int `$tag`): bool

Add an additional retrieved tag in subsequent queries.

### Parameters

`tag`
  One of `RPMTAG_*` constant.

### Return Values

Returns `true` on success or `false` on failure.

### See Also

- rpminfo() - Get information from a RPM file
- rpmdbinfo() - Get information from installed RPM
- rpmdbsearch() - Search RPM packages

# rpmdbinfo

(PECL rpminfo >= 0.2.0)

rpmdbinfo — Get information from installed RPM

### Description

rpmdbinfo(string `$nevr`, bool `$full` = `false`): ?array

Retrieve information about an installed package, from the system RPM database.

### Parameters

`nevr`
  Name with optional epoch, version and release.
`full`
  If `true` all information headers for the file are retrieved, else only a minimal set.

### Return Values

An array of array of information, or `null` on error.

### Examples

Example #1 A rpmdbinfo() example

`<?php
rpmaddtag(RPMTAG_INSTALLTIME);
$info = rpmdbinfo("php-pecl-rpminfo");
print_r($info);
?>`

The above example will output:

    Array
    (
        [0] => Array
            (
                [Name] => php-pecl-rpminfo
                [Version] => 0.4.2
                [Release] => 1.fc31
                [Summary] => RPM information
                [Installtime] => 1586244687
                [Arch] => x86_64
            )
    )

### See Also

- rpmaddtag() - Add tag retrieved in query

# rpmdbsearch

(PECL rpminfo >= 0.3.0)

rpmdbsearch — Search RPM packages

### Description

rpmdbsearch(
string `$pattern`,
int `$rpmtag` = RPMTAG_NAME,
int `$rpmmire` = -1,
bool `$full` = `false`
): ?array

Search packages in the system RPM database.

### Parameters

`pattern`
  Value to search for.
`rpmtag`
  Search criterion, which is one of the `RPMTAG_*` constants.
`rpmmire`
  Pattern type, which is one of the `RPMMIRE_*` constants. When < 0 the criterion must equal the value, and database index is used if possible.
`full`
  If `true` all information headers for the file are retrieved, else only a minimal set.

### Return Values

An array of array of information, or `null` on error.

### Examples

Example #1 Searching for the package owning a file

`<?php
$info = rpmdbsearch("/usr/bin/php", RPMTAG_INSTFILENAMES);
print_r($info);
?>`

The above example will output:

    Array
    (
        [0] => Array
            (
                [Name] => php-cli
                [Version] => 7.4.4
                [Release] => 1.fc32
                [Summary] => Command-line interface for PHP
                [Arch] => x86_64
            )

    )

### See Also

- rpmaddtag() - Add tag retrieved in query

# rpmdefine

(PECL rpminfo >= 1.2.0)

rpmdefine — Define or change a RPM macro value

### Description

rpmdefine(string `$text`): bool

Define or change a RPM macro value.

This can be used to select the database path and backend to use instead of system default one.

### Parameters

`text`
  Macro name, options, body.

### Return Values

Returns `true` on success or `false` on failure.

### Examples

Example #1 A rpmdefine() example

`<?php
// use an old database (bdb) from an EL-8 chroot
rpmdefine("_dbpath /var/lib/mock/almalinux-8-x86_64/root/var/lib/rpm");
rpmdefine("_db_backend bdb_ro");
print_r(rpmdbinfo("almalinux-release")[0]["Summary"]);
// use a new database (sqlite) from a Fedora-41 chroot
rpmdefine("_dbpath /var/lib/mock/fedora-41-x86_64/root/usr/lib/sysimage/rpm");
rpmdefine("_db_backend sqlite");
print_r(rpmdbinfo("fedora-release")[0]["Summary"]);
?>`

The above example will output:

    AlmaLinux release file
    Fedora release files

### See Also

- rpmexpand() - Retrieve expanded value of a RPM macro
- rpmdbinfo() - Get information from installed RPM

# rpmexpand

(PECL rpminfo >= 1.2.0)

rpmexpand — Retrieve expanded value of a RPM macro

### Description

rpmexpand(string `$text`): string

Retrieve expanded value of a RPM macro.

### Parameters

`text`
  Text with RPM macros to expand.

### Return Values

A string with concatenated macro expansions.

### Examples

Example #1 A rpmexpand() example

`<?php
$distro = rpmexpand("%{?fedora:Fedora %{fedora}}%{?rhel:Enterprise Linux %{rhel}}");
print_r($distro);
?>`

The above example will output:

    Fedora 41

### See Also

- rpmexpandnumeric() - Retrieve numerical value of a RPM macro

# rpmexpandnumeric

(PECL rpminfo >= 1.2.0)

rpmexpandnumeric — Retrieve numerical value of a RPM macro

### Description

rpmexpandnumeric(string `$text`): int

Retrieve numerical value of a RPM macro.

### Parameters

`text`
  Text with RPM macros to expand.

### Return Values

Macro expansion as a int. Boolean values (`Y` or `y` returns 1, `N` or `n` returns `0`) are permitted as well. An undefined macro returns `0`.

### Examples

Example #1 A rpmexpandnumeric() example

`<?php
$bits = rpmexpandnumeric("%__isa_bits");
print_r($bits);
?>`

The above example will output:

    64

### See Also

- rpmexpand() - Retrieve expanded value of a RPM macro

# rpmgetsymlink

(PECL rpminfo >= 1.1.0)

rpmgetsymlink — Get target of a symlink

### Description

rpmgetsymlink(string `$path`, string `$name`): ?string

Get target of a symlink.

### Parameters

`path`
  Path of the RPM file.
`name`
  Name of the symlink file.

### Return Values

A string with target of the symlink, `null` on error, or an empty string if not a symlink.

# rpminfo

(PECL rpminfo >= 0.1.0)

rpminfo — Get information from a RPM file

### Description

rpminfo(string `$path`, bool `$full` = `false`, string `&$error` = ?): ?array

Retrieve information about a local file, a RPM package.

### Parameters

`path`
  Path of the RPM file.
`full`
  If `true` all information headers for the file are retrieved, else only a minimal set.
`error`
  If provided, will receive the possible error message, and will avoid a runtime warning.

### Return Values

An array of information, or `null` on error.

### Examples

Example #1 A rpminfo() example

`<?php
rpmaddtag(RPMTAG_BUILDTIME);
$info = rpminfo("./php-pecl-rpminfo-0.4.2-1.el8.remi.7.4.x86_64.rpm");
print_r($info);
?>`

The above example will output:

    Array
    (
        [Name] => php-pecl-rpminfo
        [Version] => 0.4.2
        [Release] => 1.el8
        [Summary] => RPM information
        [Buildtime] => 1586244821
        [Arch] => x86_64
    )

### See Also

- rpmaddtag() - Add tag retrieved in query

# rpmvercmp

(PECL rpminfo >= 0.1.0)

rpmvercmp — RPM version comparison

### Description

rpmvercmp(string `$evr1`, string `$evr2`, ?string `$operator` = `null`): int|bool

Compare two RPM package versions.

### Parameters

`evr1`
  First `epoch:version-release` string.
`evr2`
  Second `epoch:version-release` string.
`operator`

  An optional operator. The possible operators are: `<`, `lt`, `<=`, `le`, `>`, `gt`, `>=`, `ge`, `==`, `=`, `eq`, `!=`, `<>`, `ne`.

  This parameter is case-sensitive, values should be lowercase.

### Return Values

Returns `-1` if `evr1` is less than `evr2`, `1` if `evr1` is greater than `evr2`, and `0` if they are equal.

When using the optional `operator` argument, the function will return `true` if the relationship is the one specified by the operator, `false` otherwise.

### Changelog

Version | Description
--- | ---
PECL rpminfo 0.7.0 | Optional `operator` was added.

## Table of Contents

- rpmaddtag — Add tag retrieved in query
- rpmdbinfo — Get information from installed RPM
- rpmdbsearch — Search RPM packages
- rpmdefine — Define or change a RPM macro value
- rpmexpand — Retrieve expanded value of a RPM macro
- rpmexpandnumeric — Retrieve numerical value of a RPM macro
- rpmgetsymlink — Get target of a symlink
- rpminfo — Get information from a RPM file
- rpmvercmp — RPM version comparison

- Installing/Configuring
  - Requirements
  - Installation via PECL
- Predefined Constants
- RpmInfo Functions
  - rpmaddtag — Add tag retrieved in query
  - rpmdbinfo — Get information from installed RPM
  - rpmdbsearch — Search RPM packages
  - rpmdefine — Define or change a RPM macro value
  - rpmexpand — Retrieve expanded value of a RPM macro
  - rpmexpandnumeric — Retrieve numerical value of a RPM macro
  - rpmgetsymlink — Get target of a symlink
  - rpminfo — Get information from a RPM file
  - rpmvercmp — RPM version comparison

# XLSWriter

# Introduction

An efficient and fast xlsx file export extension.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

XLSWriter requires PHP 7.0 and above.

## Installation

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: » https://pecl.php.net/package/xlswriter

## Resource Types

There is one resource used by the procedural version of the XLSWriter extension: returned by fileName() or \Vtiful\Kernel\Format.

# The Vtiful\Kernel\Excel class

(PECL xlswriter >= 1.2.1)

## Introduction

Create xlsx files and set cells and output xlsx files

## Class synopsis

class Vtiful\Kernel\Excel {
/* Methods */
public __construct(array `$config`)
public addSheet(string `$sheetName`)
public autoFilter(string `$scope`)
public constMemory(string `$fileName`, string `$sheetName` = ?)
public data(array `$data`)
public fileName(string `$fileName`, string `$sheetName` = ?)
public getHandle()
public header(array `$headerData`)
public insertFormula(int `$row`, int `$column`, string `$formula`)
public insertImage(int `$row`, int `$column`, string `$localImagePath`)
public insertText(
int `$row`,
int `$column`,
int|float|string `$data`,
string `$format` = ?
)
public mergeCells(string `$scope`, string `$data`)
public output()
public setColumn(string `$range`, float `$width`, resource `$format` = ?)
public setRow(string `$range`, float `$height`, resource `$format` = ?)
}

# Vtiful\Kernel\Excel::addSheet

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet

### Description

public Vtiful\Kernel\Excel::addSheet(string `$sheetName`)

Create a new worksheet in the xlsx file.

### Parameters

`sheetName`

  Worksheet name

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23]
]);
$file->addSheet('sheet_two')
->header(['name', 'age'])
->data([
['james', 33],
['king', 33]
]);
$file->output();
?>`

# Vtiful\Kernel\Excel::autoFilter

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter

### Description

public Vtiful\Kernel\Excel::autoFilter(string `$scope`)

Add autofilter to a worksheet.

### Parameters

`scope`

  Cell start and end coordinate string.

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $excel->fileName('test.xlsx')
->header(['name', 'age'])
->data($data)
->autoFilter('A1:B11') // auto filter
->output();
?>`

# Vtiful\Kernel\Excel::constMemory

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory

### Description

public Vtiful\Kernel\Excel::constMemory(string `$fileName`, string `$sheetName` = ?)

Write a large file with constant memory usage.

### Parameters

`fileName`

  XLSX file name

`sheetName`

  Worksheet name

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => '/home/viest'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $instance->constMemory('tutorial.xlsx', 'sheet');
?>`

# Vtiful\Kernel\Excel::__construct

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor

### Description

public Vtiful\Kernel\Excel::__construct(array `$config`)

Vtiful\Kernel\Excel constructor, create a class object.

### Parameters

`config`

  XLSX file export configuration

### Examples

Example #1 example

`<?php
$config = [
'path' => '/home/viest'
];
$excelObject = new \Vtiful\Kernel\Excel($config);
?>`

# Vtiful\Kernel\Excel::data

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data

### Description

public Vtiful\Kernel\Excel::data(array `$data`)

Write a data in the worksheet.

### Parameters

`data`

  worksheet data

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23],
]);
?>`

# Vtiful\Kernel\Excel::fileName

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName

### Description

public Vtiful\Kernel\Excel::fileName(string `$fileName`, string `$sheetName` = ?)

Create a brand new xlsx file and create a worksheet.

### Parameters

`fileName`

  XLSX file name

`sheetName`

  Worksheet name

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => '/home/viest'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $instance->fileName('tutorial.xlsx', 'sheet');
?>`

# Vtiful\Kernel\Excel::getHandle

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle

### Description

public Vtiful\Kernel\Excel::getHandle()

Get the xlsx text resource handle.

### Parameters

This function has no parameters.

### Return Values

Resource

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age']);
$handle = $file->getHandle();
?>`

# Vtiful\Kernel\Excel::header

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header

### Description

public Vtiful\Kernel\Excel::header(array `$headerData`)

Write a header in the worksheet.

### Parameters

`headerData`

  worksheet header data

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age']);
?>`

# Vtiful\Kernel\Excel::insertFormula

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula

### Description

public Vtiful\Kernel\Excel::insertFormula(int `$row`, int `$column`, string `$formula`)

Insert calculation formula.

### Parameters

`row`

  cell row

`column`

  cell column

`formula`

  formula string

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$file = $excel->fileName("free.xlsx")
->header(['name', 'money']);
for($index = 1; $index < 10; $index++) {
$file->insertText($index, 0, 'viest');
$file->insertText($index, 1, 10);
}
$file->insertText(12, 0, "Total");
$file->insertFormula(12, 1, '=SUM(B2:B11)'); // insert formula
$file->output();`

# Vtiful\Kernel\Excel::insertImage

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage

### Description

public Vtiful\Kernel\Excel::insertImage(int `$row`, int `$column`, string `$localImagePath`)

Insert a local image into the cell.

### Parameters

`row`

  cell row

`column`

  cell column

`localImagePath`

  local image path

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$file = $excel->fileName("free.xlsx");
$file->insertImage(5, 0, '/vagrant/ASW-G-66.jpg');
$file->output();`

# Vtiful\Kernel\Excel::insertText

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText

### Description

public Vtiful\Kernel\Excel::insertText(
int `$row`,
int `$column`,
int|float|string `$data`,
string `$format` = ?
)

Write text in a cell.

### Parameters

`row`

  cell row

`column`

  cell column

`data`

  data to be written

`format`

  String format

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$file = $excel->fileName("free.xlsx")
->header(['name', 'money']);
for ($index = 0; $index < 10; $index++) {
$file->insertText($index+1, 0, 'viest');
$file->insertText($index+1, 1, 10000, '#,##0');
}
$textFile->output();`

# Vtiful\Kernel\Excel::mergeCells

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells

### Description

public Vtiful\Kernel\Excel::mergeCells(string `$scope`, string `$data`)

Merge Cells.

### Parameters

`scope`

  cell start and end coordinate strings

`data`

  string data

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName("test.xlsx")
->mergeCells('A1:C1', 'Merge cells')
->output();`

# Vtiful\Kernel\Excel::output

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output

### Description

public Vtiful\Kernel\Excel::output()

Output xlsx file to disk.

### Parameters

This function has no parameters.

### Return Values

XLSX file path;

### Examples

Example #1 example

`<?php
$config = [
'path' => './tests'
];
$fileObject = new \Vtiful\Kernel\Excel($config);
$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23],
]);
$path = $file->output();
?>`

# Vtiful\Kernel\Excel::setColumn

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn

### Description

public Vtiful\Kernel\Excel::setColumn(string `$range`, float `$width`, resource `$format` = ?)

Set the format of the column.

### Parameters

`range`

  cell start and end coordinate strings

`width`

  column width

`format`

  cell format resource

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 setColumn example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$boldStyle = $format->bold()->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $boldStyle)
->output();`

# Vtiful\Kernel\Excel::setRow

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow

### Description

public Vtiful\Kernel\Excel::setRow(string `$range`, float `$height`, resource `$format` = ?)

Set the format of the row.

### Parameters

`range`

  cell start and end coordinate strings

`height`

  row height

`format`

  cell format resource

### Return Values

Vtiful\Kernel\Excel instance

### Examples

Example #1 setRow example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$boldStyle = $format->bold()->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setRow('A1', 20, $boldStyle)
->output();`

## Table of Contents

- Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet
- Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter
- Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory
- Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor
- Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data
- Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName
- Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle
- Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header
- Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula
- Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage
- Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText
- Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells
- Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output
- Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn
- Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow

# The Vtiful\Kernel\Format class

(PECL xlswriter >= 1.2.1)

## Introduction

Create a cell format object

## Class synopsis

class Vtiful\Kernel\Format {
/* Constants */
const int FORMAT_ALIGN_LEFT = 1;
const int FORMAT_ALIGN_CENTER = 2;
const int FORMAT_ALIGN_RIGHT = 3;
const int FORMAT_ALIGN_FILL = 4;
const int FORMAT_ALIGN_JUSTIFY = 5;
const int FORMAT_ALIGN_CENTER_ACROSS = 6;
const int FORMAT_ALIGN_DISTRIBUTED = 7;
const int FORMAT_ALIGN_VERTICAL_TOP = 8;
const int FORMAT_ALIGN_VERTICAL_BOTTOM = 9;
const int FORMAT_ALIGN_VERTICAL_CENTER = 10;
const int FORMAT_ALIGN_VERTICAL_JUSTIFY = 11;
const int FORMAT_ALIGN_VERTICAL_DISTRIBUTED = 12;
const int UNDERLINE_SINGLE = 1;
const int UNDERLINE_DOUBLE = 2;
const int UNDERLINE_SINGLE_ACCOUNTING = 3;
const int UNDERLINE_DOUBLE_ACCOUNTING = 4;
/* Methods */
public align(resource `$handle`, int `$style`)
public bold(resource `$handle`)
public italic(resource `$handle`)
public underline(resource `$handle`, int `$style`)
}

## Predefined Constants

`Vtiful\Kernel\Format::FORMAT_ALIGN_LEFT`

`Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER`

`Vtiful\Kernel\Format::FORMAT_ALIGN_RIGHT`

`Vtiful\Kernel\Format::FORMAT_ALIGN_FILL`

`Vtiful\Kernel\Format::FORMAT_ALIGN_JUSTIFY`

`Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER_ACROSS`

`Vtiful\Kernel\Format::FORMAT_ALIGN_DISTRIBUTED`

`Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_TOP`

`Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_BOTTOM`

`Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER`

`Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_JUSTIFY`

`Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_DISTRIBUTED`

`Vtiful\Kernel\Format::UNDERLINE_SINGLE`

`Vtiful\Kernel\Format::UNDERLINE_DOUBLE`

`Vtiful\Kernel\Format::UNDERLINE_SINGLE_ACCOUNTING`

`Vtiful\Kernel\Format::UNDERLINE_DOUBLE_ACCOUNTING`

# Vtiful\Kernel\Format::align

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align

### Description

public Vtiful\Kernel\Format::align(resource `$handle`, int `$style`)

set cell align

### Parameters

`handle`

  xlsx file handle

`style`

  Vtiful\Kernel\Format constant

### Return Values

Resource

### Examples

Example #1 Align style example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$alignStyle = $format->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_LEFT)->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $alignStyle)
->output();
?>`

# Vtiful\Kernel\Format::bold

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold

### Description

public Vtiful\Kernel\Format::bold(resource `$handle`)

Vtiful\Kernel\Format bold format

### Parameters

`handle`

  xlsx file handle

### Return Values

Resource

### Examples

Example #1 Bold style example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$boldStyle = $format->bold()->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $boldStyle)
->output();
?>`

# Vtiful\Kernel\Format::italic

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic

### Description

public Vtiful\Kernel\Format::italic(resource `$handle`)

Vtiful\Kernel\Format italic format

### Parameters

`handle`

  xlsx file handle

### Return Values

Resource

### Examples

Example #1 Italic style example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$italicStyle = $format->italic()->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $italicStyle)
->output();
?>`

# Vtiful\Kernel\Format::underline

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

### Description

public Vtiful\Kernel\Format::underline(resource `$handle`, int `$style`)

Vtiful\Kernel\Format underline format

### Parameters

`handle`

  xlsx file handle

`style`

  Vtiful\Kernel\Format constant

### Return Values

Resource

### Examples

Example #1 Underline style example

`<?php
$config = [
'path' => './tests'
];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx');
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$underlineStyle = $format->underline(\Vtiful\Kernel\Format::UNDERLINE_SINGLE)->toResource();
$excel->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $underlineStyle)
->output();
?>`

## Table of Contents

- Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align
- Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold
- Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic
- Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Vtiful\Kernel\Excel — The Vtiful\Kernel\Excel class
  - Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet
  - Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter
  - Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory
  - Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor
  - Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data
  - Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName
  - Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle
  - Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header
  - Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula
  - Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage
  - Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText
  - Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells
  - Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output
  - Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn
  - Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow
- Vtiful\Kernel\Format — The Vtiful\Kernel\Format class
  - Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align
  - Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold
  - Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic
  - Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

- FDF — Forms Data Format
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - FDF Functions
- GnuPG — GNU Privacy Guard
  - Installing/Configuring
  - Predefined Constants
  - Examples
  - GnuPG Functions
- wkhtmltox
  - Installing/Configuring
  - wkhtmltox\PDF\Converter — The wkhtmltox\PDF\Converter class
  - wkhtmltox\PDF\Object — The wkhtmltox\PDF\Object class
  - wkhtmltox\Image\Converter — The wkhtmltox\Image\Converter class
- PS — PostScript document creation
  - Installing/Configuring
  - Predefined Constants
  - PS Functions
- RpmInfo
  - Installing/Configuring
  - Predefined Constants
  - RpmInfo Functions
- XLSWriter
  - Installing/Configuring
  - Vtiful\Kernel\Excel — The Vtiful\Kernel\Excel class
  - Vtiful\Kernel\Format — The Vtiful\Kernel\Format class

# Process Control Extensions

# Eio

# Introduction

This extension provides asyncronous POSIX I/O by means of » libeio C library written by Marc Lehmann.

> Note: This extension is not available on Windows platforms.

Warning

It is important to be aware that each request is executed in a thread, and the order of execution of continuously queued requests basically is unpredictable. For instance, the following piece of code is incorrect.

Example #1 Incorrect requests

`<?php
// Request to create symlink of $filename to $link
eio_symlink($filename, $link);
// Request to move $filename to $new_filename
eio_rename($filename, $new_filename);
// Process requests
eio_event_loop();
?>`
In the example above eio_rename() request may finish before eio_symlink(). To fix it you might call eio_rename() in the callback of eio_symlink():

Example #2 Calling request from a request callback

`<?php
function my_symlink_done($filename, $result) {
// Request to move $filename to $new_filename
eio_rename($filename, "/path/to/new-name");
// Process requests
eio_event_loop();
}
// Request to create symlink of $filename to $link
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_done", $filename);
// Process requests
eio_event_loop();
?>`
Alternatively, you might want to create a request group:

Example #3 Calling request from a request callback

`<?php
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
// ...
}
function my_symlink_done($filename, $result) {
// Create eio_rename request and add it to the group
$req = eio_rename($filename, "/path/to/new-name");
eio_grp_add($grp, $req);
// You might want to add more requests...
}
// Create a request group
$grp = eio_grp("my_grp_done", "my_grp_data");
// Create eio_symlink request and add it to the group
// Pass $filename to the callback
$req = eio_symlink($filename, $link,
EIO_PRI_DEFAULT, "my_symlink_done", $filename);
eio_grp_add($grp, $req);
// Process requests
eio_event_loop();
?>`
Group is a special kind of request that could accumulate a set of regular eio requests. This could be used to create a complex request that opens, reads and closes a file.

Since version 0.3.0 alpha, a variable used in communications with libeio internally, could be retrieved with eio_get_event_stream(). The variable could be used to bind to an event loop supported by some other extension. You might organize a simple event loop where eio and libevent work together:

Example #4 Using eio with libevent

`<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}
function my_res_cb($d, $r) {
var_dump($r); var_dump($d);
}
$base = event_base_new();
$event = event_new();
// This stream is used to bind with libevent
$fd = eio_get_event_stream();
eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */
// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));
// set event base
event_base_set($event, $base);
// enable event
event_add($event);
// start event loop
event_base_loop($base);
/* The same will be available via buffered libevent interface */
?>`

# Installing/Configuring

## Table of Contents

- Requirements
- Installation
- Resource Types

## Requirements

This extension has » libeio library embedded. So you do NOT need to install libeio separately.

## Installation

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: » https://pecl.php.net/package/eio.

For information about manual installation, please read the file INSTALL included in the package.

## Resource Types

There are two resource types in this extension: request and request group.

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

Request priority constants:

`EIO_PRI_MIN` (int)
  Request minimal prioriry
`EIO_PRI_DEFAULT` (int)
  Request default prioriry
`EIO_PRI_MAX` (int)
  Request maximal prioriry

eio_seek() `whence` argument:

`EIO_SEEK_SET` (int)
  The offset is set to specified number of bytes(`offset`).
`EIO_SEEK_CUR` (int)
  The offset is set to its current location plus `offset` bytes.
`EIO_SEEK_END` (int)
  The offset is set to the size of the file plus `offset` bytes.

Flags used with eio_readdir():

`EIO_READDIR_DENTS` (int)
  eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: `'names'` - array of directory names `'dents'` - array of `struct eio_dirent`-like arrays having the following keys each: `'name'` - the directory name; `'type'` - one of EIO_DT_* constants; `'inode'` - the inode number, if available, otherwise unspecified;
`EIO_READDIR_DIRS_FIRST` (int)
  When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
`EIO_READDIR_STAT_ORDER` (int)
  When this flag is specified, then the names will be returned in an order suitable for `stat`'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
`EIO_READDIR_FOUND_UNKNOWN` (int)
`EIO_DT_UNKNOWN` (int)
  Unknown node type(very common). Further stat() needed.
`EIO_DT_FIFO` (int)
  FIFO node type
`EIO_DT_CHR` (int)
  Node type
`EIO_DT_MPC` (int)
  Multiplexed char device (v7+coherent) node type
`EIO_DT_DIR` (int)
  Directory node type
`EIO_DT_NAM` (int)
  Xenix special named file node type
`EIO_DT_BLK` (int)
  Node type
`EIO_DT_MPB` (int)
  Multiplexed block device (v7+coherent)
`EIO_DT_REG` (int)
  Node type
`EIO_DT_NWK` (int)
`EIO_DT_CMP` (int)
  HP-UX network special node type
`EIO_DT_LNK` (int)
  Link node type
`EIO_DT_SOCK` (int)
  Socket node type
`EIO_DT_DOOR` (int)
  Solaris door node type
`EIO_DT_WHT` (int)
  Node type
`EIO_DT_MAX` (int)
  Highest node type value

Access modes for eio_open() `flags` argument:

`EIO_O_RDONLY` (int)
`EIO_O_WRONLY` (int)
`EIO_O_RDWR` (int)
`EIO_O_NONBLOCK` (int)
`EIO_O_APPEND` (int)
`EIO_O_CREAT` (int)
`EIO_O_TRUNC` (int)
`EIO_O_EXCL` (int)
`EIO_O_FSYNC` (int)

`mode` argument flags for eio_open():

`EIO_S_IRUSR` (int)
`EIO_S_IWUSR` (int)
`EIO_S_IXUSR` (int)
`EIO_S_IRGRP` (int)
`EIO_S_IWGRP` (int)
`EIO_S_IXGRP` (int)
`EIO_S_IROTH` (int)
`EIO_S_IWOTH` (int)
`EIO_S_IXOTH` (int)
`EIO_S_IFREG` (int)
`EIO_S_IFCHR` (int)
`EIO_S_IFBLK` (int)
`EIO_S_IFIFO` (int)
`EIO_S_IFSOCK` (int)

eio_sync_file_range() flags:

`EIO_SYNC_FILE_RANGE_WAIT_BEFORE` (int)
`EIO_SYNC_FILE_RANGE_WRITE` (int)
`EIO_SYNC_FILE_RANGE_WAIT_AFTER` (int)

eio_fallocate() flags:

`EIO_FALLOC_FL_KEEP_SIZE` (int)

> Note: EIO_S_I* constants have the same meaning as their S_I* POSIX counterparts.

> Note: EIO_SYNC_FILE_* constants have the same meaning as their SYNC_FILE_** counterparts.

> Note: EIO_O_* constants have the same meaning as their O_* POSIX counterparts.

# Examples

Example #1 Cancelling a request

`<?php
/* Is called when eio_nop() finished */
function my_nop_cb($data, $result) {
echo "my_nop ", $data, "\n";
}
// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);
// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");
// Process requests
eio_event_loop();
?>`

The above example will output something similar to:

    resource(4) of type (EIO Request Descriptor)
    my_nop 2

Example #2 Calling eio_chmod()

`<?php
$temp_filename = dirname(__FILE__) ."/eio-temp-file.tmp";
touch($temp_filename);
/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
global $temp_filename;
if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
echo "eio_chmod_ok";
}
@unlink($temp_filename);
}
eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>`

The above example will output something similar to:

    eio_chmod_ok

Example #3 Making a custom request

`<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
var_dump($data);
var_dump(count($result));
var_dump($result['data_modified']);
var_dump($result['result']);
}
/* The custom request */
function my_custom($data) {
var_dump($data);
$result = array(
'result' => 1001,
'data_modified' => "my custom data",
);
return $result;
}
$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>`

The above example will output something similar to:

    resource(4) of type (EIO Request Descriptor)
    string(14) "my_custom_data"
    string(14) "my_custom_data"
    int(2)
    string(14) "my custom data"
    int(1001)

Example #4 Grouping requests

`<?php
/*
* Create a group request to open, read and close a file
*/
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
global $temp_filename;
var_dump($result == 0);
@unlink($temp_filename);
}
/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
global $my_file_fd, $grp;
$my_file_fd = $result;
var_dump($result > 0);
// Create eio_read() request and add it to the group
$req = eio_read($my_file_fd, 4, 0, EIO_PRI_DEFAULT, "my_grp_file_read_callback");
eio_grp_add($grp, $req);
}
/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
global $my_file_fd, $grp;
var_dump($result);
// Create eio_close() request and add it to the group
$req = eio_close($my_file_fd);
eio_grp_add($grp, $req);
}
$grp = eio_grp("my_grp_done", "my_grp_data");
// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);
var_dump($grp);
eio_event_loop();
?>`

The above example will output something similar to:

    resource(6) of type (EIO Group Descriptor)
    bool(true)
    string(4) "some"
    bool(true)

Example #5 Using eio with libevent extension

`<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}
function my_nop_cb($d, $r) {
var_dump($r); var_dump($d);
}
$base = event_base_new();
$event = event_new();
$fd = eio_get_event_stream();
var_dump($fd);
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
/* some other eio_* calls here ... */
// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));
// set event base
event_base_set($event, $base);
// enable event
event_add($event);
// start event loop
event_base_loop($base);
/* The same will be available via buffered libevent interface */
?>`

The above example will output something similar to:

    int(3)
    int(0)
    string(8) "nop data"
    int(0)
    string(10) "mkdir data"

Example #6 Using eio with event extension

`<?php
$base = new EventBase();
// Retrieve eio polling stream.
// Note, this variable should be alive as long as the event loop is running.
$eio_stream = eio_get_event_stream();
// Bind eio polling stream to the event loop.
$poll_event = new Event($base, $eio_stream, Event::READ, function () {
if (eio_nreqs()) {
eio_poll();
}
});
$poll_event->add();
// Add eio jobs
eio_nop(EIO_PRI_DEFAULT, function () {
echo "eio_nop\n";
});
// Add events
$timer = Event::timer($base, function () {
echo "2 seconds elapsed\n";
});
$timer->add(2);
// Dispatch events.
$base->dispatch();
?>`

The above example will output something similar to:

    eio_nop
    2 seconds elapsed

# Eio Functions

# eio_busy

(PECL eio >= 0.0.1dev)

eio_busy — Artificially increase load. Could be useful in tests, benchmarking

### Description

eio_busy(
int `$delay`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_busy() artificially increases load taking `delay` seconds to execute. May be used for debugging, or benchmarking.

### Parameters

`delay`
  Delay in seconds
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`
  This callback is called when all the group requests are done.
`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_busy() returns request resource on success, or `false` on failure.

### See Also

- eio_nop() - Does nothing, except go through the whole request cycle

# eio_cancel

(PECL eio >= 0.0.1dev)

eio_cancel — Cancels a request

### Description

eio_cancel(resource `$req`): void

eio_cancel() cancels a request specified by `req`

### Parameters

`req`
  The request resource
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

No value is returned.

### Examples

Example #1 eio_cancel() example

`<?php
/* Is called when eio_nop() finished */
function my_nop_cb($data, $result) {
echo "my_nop ", $data, "\n";
}
// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);
// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");
// Process requests
eio_event_loop();
?>`

The above example will output something similar to:

    resource(4) of type (EIO Request Descriptor)
    my_nop 2

### See Also

- eio_grp_cancel() - Cancels a request group

# eio_chmod

(PECL eio >= 0.0.1dev)

eio_chmod — Change file/directory permissions

### Description

eio_chmod(
string `$path`,
int `$mode`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_chmod() changes file, or directory permissions. The new permissions are specified by `mode`.

### Parameters

`path`
  Path to the target file or directory
  Warning

  Avoid relative paths

`mode`
  The new permissions. E.g. `0644`.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_chmod() returns request resource on success, or `false` on failure.

### See Also

- eio_chown() - Change file/directory permissions

# eio_chown

(PECL eio >= 0.0.1dev)

eio_chown — Change file/directory permissions

### Description

eio_chown(
string `$path`,
int `$uid`,
int `$gid` = -1,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

Changes file, or directory permissions.

### Parameters

`path`
  Path to file or directory.
  Warning

  Avoid relative paths

`uid`
  User ID. Is ignored when equal to -1.
`gid`
  Group ID. Is ignored when equal to -1.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_chown() returns request resource on success, or `false` on failure.

### See Also

- eio_chmod() - Change file/directory permissions

# eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

### Description

eio_close(
mixed `$fd`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_close() closes file specified by `fd`.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_close() returns request resource on success, or `false` on failure.

### See Also

- eio_open() - Opens a file

# eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call

### Description

eio_custom(
callable `$execute`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

eio_custom() executes custom function specified by `execute` processing it just like any other eio_* call.

### Parameters

`execute`

  Specifies the request function that should match the following prototype:

            mixed execute(mixed data);

  `callback` is event completion callback that should match the following prototype:

            void callback(mixed data, mixed result);

  `data` is the data passed to `execute` via `data` argument without modifications `result` value returned by `execute`
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_custom() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_custom() example

`<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
var_dump($data);
var_dump(count($result));
var_dump($result['data_modified']);
var_dump($result['result']);
}
/* The custom request */
function my_custom($data) {
var_dump($data);
$result = array(
'result' => 1001,
'data_modified' => "my custom data",
);
return $result;
}
$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>`

The above example will output something similar to:

    resource(4) of type (EIO Request Descriptor)
    string(14) "my_custom_data"
    string(14) "my_custom_data"
    int(2)
    string(14) "my custom data"
    int(1001)

# eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

### Description

eio_dup2(
mixed `$fd`,
mixed `$fd2`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_dup2() duplicates file descriptor.

### Parameters

`fd`
  Source stream, Socket resource, or numeric file descriptor
`fd2`
  Target stream, Socket resource, or numeric file descriptor
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_dup2() returns request resource on success, or `false` on failure.

# eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

### Description

eio_event_loop(): bool

eio_event_loop() polls libeio until all requests proceeded.

### Parameters

This function has no parameters.

### Return Values

eio_event_loop() returns `true` on success, or `false` on failure.

### Examples

Example #1 eio_event_loop() example

`<?php
$temp_filename = "eio-temp-file.tmp";
touch($temp_filename);
/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
global $temp_filename;
if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
echo "eio_chmod_ok";
}
@unlink($temp_filename);
}
eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>`

The above example will output something similar to:

    eio_chmod_ok

### See Also

- eio_poll() - Can be to be called whenever there are pending requests that need finishing

# eio_fallocate

(PECL eio >= 0.0.1dev)

eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file

### Description

eio_fallocate(
mixed `$fd`,
int `$mode`,
int `$offset`,
int `$length`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_fallocate() allows the caller to directly manipulate the allocated disk space for the file specified by `fd` file descriptor for the byte range starting at `offset` and continuing for `length` bytes.

> Note: File should be opened for writing
> `EIO_O_CREAT` should be logically OR'd with `EIO_O_WRONLY`, or `EIO_O_RDWR`

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().
`mode`
  Currently only one flag is supported for mode: `EIO_FALLOC_FL_KEEP_SIZE` (the same as POSIX constant `FALLOC_FL_KEEP_SIZE`).
`offset`
  Specifies start of the byte range.
`length`
  Specifies length the byte range.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_fallocate() returns request resource on success, or `false` on failure.

# eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions

### Description

eio_fchmod(
mixed `$fd`,
int `$mode`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_fchmod() changes permissions for the file specified by `fd` file descriptor.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().
`mode`
  The new permissions. E.g. 0644.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_fchmod() returns request resource on success, or `false` on failure.

### See Also

- eio_fchown() - Change file ownership

# eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

### Description

eio_fchown(
mixed `$fd`,
int `$uid`,
int `$gid` = -1,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_fchown() changes ownership of the file specified by `fd` file descriptor.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor.
`uid`
  User ID. Is ignored when equal to -1.
`gid`
  Group ID. Is ignored when equal to -1.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_chmod() returns request resource on success, or `false` on failure.

### See Also

- eio_fchmod() - Change file permissions

# eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device

### Description

eio_fdatasync(
mixed `$fd`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_fdatasync() synchronizes a file's in-core state with storage device.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_fdatasync() returns request resource on success, or `false` on failure.

# eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

### Description

eio_fstat(
mixed `$fd`,
int `$pri`,
callable `$callback`,
mixed `$data` = ?
): resource

eio_fstat() returns file status information in `result` argument of `callback`

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_busy() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_lstat() example

`<?php
// Create temporary file
$tmp_filename = dirname(__FILE__) ."/eio-file.tmp";
touch($tmp_filename);
/* Is called when eio_fstat() done */
function my_res_cb($data, $result) {
// Should output array with stat info
var_dump($result);
if ($data['fd']) {
// Close temporary file
eio_close($data['fd']);
eio_event_loop();
}
// Remove temporary file
@unlink($data['file']);
}
/* Is called when eio_open() done */
function my_open_cb($data, $result) {
// Prepare data for callback
$d = array(
'fd' => $result,
'file'=> $data
);
// Request stat info
eio_fstat($result, EIO_PRI_DEFAULT, "my_res_cb", $d);
// Process request(s)
eio_event_loop();
}
// Open temporary file
eio_open($tmp_filename, EIO_O_RDONLY, NULL, EIO_PRI_DEFAULT,
"my_open_cb", $tmp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    array(12) {
     ["st_dev"]=>
      int(2050)
      ["st_ino"]=>
      int(2489159)
      ["st_mode"]=>
      int(33188)
      ["st_nlink"]=>
      int(1)
      ["st_uid"]=>
      int(1000)
      ["st_gid"]=>
      int(100)
      ["st_rdev"]=>
      int(0)
      ["st_blksize"]=>
      int(4096)
      ["st_blocks"]=>
      int(0)
      ["st_atime"]=>
      int(1318239506)
      ["st_mtime"]=>
      int(1318239506)
      ["st_ctime"]=>
      int(1318239506)
    }

### See Also

- eio_lstat() - Get file status
- eio_stat() - Get file status

# eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

### Description

eio_fstatvfs(
mixed `$fd`,
int `$pri`,
callable `$callback`,
mixed `$data` = ?
): resource

eio_fstatvfs() returns file system statistics in `result` of `callback`.

### Parameters

`fd`
  A file descriptor of a file within the mounted file system.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_fstatvfs() returns request resource on success, or `false` on failure.

### See Also

- eio_statvfs() - Get file system statistics

# eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

### Description

eio_fsync(
mixed `$fd`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

Synchronize a file's in-core state with storage device

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_fsync() returns request resource on success, or `false` on failure.

### See Also

- eio_sync() - Commit buffer cache to disk

# eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

### Description

eio_ftruncate(
mixed `$fd`,
int `$offset` = 0,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_ftruncate() causes a regular file referenced by `fd` file descriptor to be truncated to precisely `length` bytes.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor.
`offset`
  Offset from beginning of the file
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_ftruncate() returns request resource on success, or `false` on failure.

### See Also

- eio_truncate() - Truncate a file

# eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

### Description

eio_futime(
mixed `$fd`,
float `$atime`,
float `$mtime`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_futime() changes file last access and modification times.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()
`atime`
  Access time
`mtime`
  Modification time
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_futime() returns request resource on success, or `false` on failure.

### See Also

- eio_utime() - Change file last access and modification times

# eio_get_event_stream

(PECL eio >= 0.3.1b)

eio_get_event_stream — Get stream representing a variable used in internal communications with libeio

### Description

eio_get_event_stream(): mixed

eio_get_event_stream() acquires stream representing a variable used in internal communications with libeio. Could be used to bind with some event loop provided by other PECL extension, for example libevent.

### Parameters

This function has no parameters.

### Return Values

eio_get_event_stream() returns stream on success; otherwise, `null`

### Examples

Example #1 Using eio with libevent

`<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}
function my_res_cb($d, $r) {
var_dump($r); var_dump($d);
}
$base = event_base_new();
$event = event_new();
$fd = eio_get_event_stream();
var_dump($fd);
eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */
// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));
// set event base
event_base_set($event, $base);
// enable event
event_add($event);
// start event loop
event_base_loop($base);
/* The same will be available via buffered libevent interface */
?>`

The above example will output something similar to:

    int(3)
    int(0)
    string(8) "nop data"
    int(0)
    string(10) "mkdir data"

# eio_get_last_error

(PECL eio >= 1.0.0)

eio_get_last_error — Returns string describing the last error associated with a request resource

### Description

eio_get_last_error(resource `$req`): string

eio_get_last_error() returns string describing the last error associated with `req`.

### Parameters

`req`
  The request resource.

### Return Values

eio_get_last_error() returns string describing the last error associated with the request resource specified by `req`.

Warning

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.

# eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Creates a request group

### Description

eio_grp(callable `$callback`, string `$data` = NULL): resource

eio_grp() creates a request group.

### Parameters

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_grp() returns request group resource on success, or `false` on failure.

### Examples

Example #1 eio_grp() example

`<?php
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
$my_file_fd = NULL;
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
// Remove the file, if it still exists
@unlink($data);
}
/* Is called when the temporary file is opened */
function my_grp_file_opened_callback($data, $result) {
global $my_file_fd, $grp;
$my_file_fd = $result;
$req = eio_read($my_file_fd, 4, 0,
EIO_PRI_DEFAULT, "my_grp_file_read_callback");
eio_grp_add($grp, $req);
}
/* Is called when the file is read */
function my_grp_file_read_callback($data, $result) {
global $my_file_fd, $grp;
var_dump($result);
// Create request to close the file
$req = eio_close($my_file_fd);
// Add request to the group
eio_grp_add($grp, $req);
}
// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
// Create request
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
// Add request to the group
eio_grp_add($grp, $req);
// Process requests
eio_event_loop();
?>`

The above example will output something similar to:

    string(4) "some"

### See Also

- eio_grp_cancel() - Cancels a request group
- eio_grp_add() - Adds a request to the request group

# eio_grp_add

(PECL eio >= 0.0.1dev)

eio_grp_add — Adds a request to the request group

### Description

eio_grp_add(resource `$grp`, resource `$req`): void

eio_grp_add() adds a request to the request group.

### Parameters

`grp`
  The request group resource returned by eio_grp()
`req`
  The request resource

### Return Values

No value is returned.

### Examples

Example #1 Grouping requests

`<?php
/*
* Create a group request to open, read and close a file
*/
// Create temporary file and write some bytes to it
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
var_dump($result == 0);
@unlink($data);
}
/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
global $grp;
// $result should contain the file descriptor
var_dump($result > 0);
// Create eio_read() request and add it to the group
// Pass file descriptor to the callback
$req = eio_read($result, 4, 0,
EIO_PRI_DEFAULT, "my_grp_file_read_callback", $result);
eio_grp_add($grp, $req);
}
/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
global $grp;
// Read bytes
var_dump($result);
// Create eio_close() request and add it to the group
// $data should contain the file descriptor
$req = eio_close($data);
eio_grp_add($grp, $req);
}
// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
var_dump($grp);
// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);
// Process requests
eio_event_loop();
?>`

The above example will output something similar to:

    resource(6) of type (EIO Group Descriptor)
    bool(true)
    string(4) "some"
    bool(true)

### See Also

- eio_grp() - Creates a request group
- eio_grp_cancel() - Cancels a request group
- eio_grp_limit() - Set group limit

# eio_grp_cancel

(PECL eio >= 0.0.1dev)

eio_grp_cancel — Cancels a request group

### Description

eio_grp_cancel(resource `$grp`): void

eio_grp_cancel() cancels a group request specified by `grp` request group resource.

### Parameters

`grp`
  The request group resource returned by eio_grp().

### Return Values

No value is returned.

### See Also

- eio_grp() - Creates a request group
- eio_grp_add() - Adds a request to the request group

# eio_grp_limit

(PECL eio >= 0.0.1dev)

eio_grp_limit — Set group limit

### Description

eio_grp_limit(resource `$grp`, int `$limit`): void

Limit number of requests in the request group.

### Parameters

`grp`
  The request group resource.
`limit`
  Number of requests in the group.

### Return Values

No value is returned.

### See Also

- eio_grp_add() - Adds a request to the request group

# eio_init

(PECL eio = 1.0.0)

eio_init — (Re-)initialize Eio

### Description

eio_init(): void

eio_init() (re-)initializes Eio. It allocates memory for internal structures of libeio and Eio itself. You may call eio_init() before using Eio functions. Otherwise it will be called internally first time you invoke an Eio function in a process.

> Note: This function was removed in version 3.0.0RC1 of the eio extension for PHP version 8 and higher.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# eio_link

(PECL eio >= 0.0.1dev)

eio_link — Create a hardlink for file

### Description

eio_link(
string `$path`,
string `$new_path`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_link() creates a hardlink `new_path` for a file specified by `path`.

### Parameters

`path`
  Source file path.
`new_path`
  Target file path.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

### Examples

Example #1 eio_link() example

`<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";
function my_hardlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && !is_link($data));
@unlink($data);
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}
function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));
if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}
function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);
@unlink($link);
@unlink($filename);
}
eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>`

The above example will output something similar to:

    bool(true)
    bool(true)
    string(%d) "%ssymlink.dat"

### See Also

- eio_symlink() - Create a symbolic link

# eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

### Description

eio_lstat(
string `$path`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

eio_lstat() returns file status information in `result` argument of `callback`

### Parameters

`path`
  The file path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_lstat() returns request resource on success or `false` on error.

### Examples

Example #1 eio_lstat() example

`<?php
$tmp_filename = dirname(__FILE__). "/eio-file.tmp";
touch($tmp_filename);
function my_res_cb($data, $result) {
var_dump($data);
var_dump($result);
}
function my_open_cb($data, $result) {
eio_close($result);
eio_event_loop();
@unlink($data);
}
eio_lstat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_lstat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    string(9) "eio_lstat"
    array(12) {
     ["st_dev"]=>
      int(2050)
      ["st_ino"]=>
      int(2099197)
      ["st_mode"]=>
      int(33188)
      ["st_nlink"]=>
      int(1)
      ["st_uid"]=>
      int(1000)
      ["st_gid"]=>
      int(100)
      ["st_rdev"]=>
      int(0)
      ["st_blksize"]=>
      int(4096)
      ["st_blocks"]=>
      int(0)
      ["st_atime"]=>
      int(1318235777)
      ["st_mtime"]=>
      int(1318235777)
      ["st_ctime"]=>
      int(1318235777)
    }

### See Also

- eio_stat() - Get file status
- eio_fstat() - Get file status

# eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

### Description

eio_mkdir(
string `$path`,
int `$mode`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_mkdir() creates directory with specified access `mode`.

### Parameters

`path`
  Path for the new directory.
`mode`
  Access mode, e.g. 0755
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_mkdir() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_mkdir() example

`<?php
$temp_dirname = "eio-temp-dir";
/* Is called when eio_mkdir() finishes */
function my_mkdir_callback($data, $result) {
if ($result == 0 && is_dir($temp_dirname)
&& !is_readable($temp_dirname)
&& is_writable($temp_dirname)) {
echo "eio_mkdir_ok";
}
// Remove directory
if (file_exists($data))
rmdir($temp_dirname);
}
// Create directory with access mode 0300
eio_mkdir($temp_dirname, 0300, EIO_PRI_DEFAULT, "my_mkdir_callback", $temp_dirname);
eio_event_loop();
?>`

The above example will output something similar to:

    eio_mkdir_ok

### See Also

- eio_rmdir() - Remove a directory

# eio_mknod

(PECL eio >= 0.0.1dev)

eio_mknod — Create a special or ordinary file

### Description

eio_mknod(
string `$path`,
int `$mode`,
int `$dev`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_mknod() creates ordinary or special(often) file.

Warning

This function is currently not documented; only its argument list is available.

### Parameters

`path`
  Path for the new node(file).
`mode`
  Specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node(e.g. 0640). Possible file types are: `EIO_S_IFREG`(regular file), `EIO_S_IFCHR`(character file), `EIO_S_IFBLK`(block special file), `EIO_S_IFIFO`(FIFO - named pipe) and `EIO_S_IFSOCK`(UNIX domain socket). To specify permissions EIO_S_I* constants could be used.
`dev`
  If the file type is `EIO_S_IFCHR` or `EIO_S_IFBLK` then dev specifies the major and minor numbers of the newly created device special file. Otherwise `dev` ignored. See mknod(2) man page for details.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_mknod() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_mknod() example

`<?php
// FIFO name
$temp_filename = "/tmp/eio-temp-fifo";
/* Is called when eio_mknod() finishes */
function my_mknod_callback($data, $result) {
$s = stat($data);
var_dump($s);
if ($result == 0) {
echo "eio_mknod_ok";
}
@unlink($data);
}
eio_mknod($temp_filename, EIO_S_IFIFO, 0,
EIO_PRI_DEFAULT, "my_mknod_callback", $temp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    array(26) {
      [0]=>
      int(17)
      [1]=>
      int(2337608)
      [2]=>
      int(4096)
      [3]=>
      int(1)
      [4]=>
      int(1000)
      [5]=>
      int(100)
      [6]=>
      int(0)
      [7]=>
      int(0)
      [8]=>
      int(1318241261)
      [9]=>
      int(1318241261)
      [10]=>
      int(1318241261)
      [11]=>
      int(4096)
      [12]=>
      int(0)
      ["dev"]=>
      int(17)
      ["ino"]=>
      int(2337608)
      ["mode"]=>
      int(4096)
      ["nlink"]=>
      int(1)
      ["uid"]=>
      int(1000)
      ["gid"]=>
      int(100)
      ["rdev"]=>
      int(0)
      ["size"]=>
      int(0)
      ["atime"]=>
      int(1318241261)
      ["mtime"]=>
      int(1318241261)
      ["ctime"]=>
      int(1318241261)
      ["blksize"]=>
      int(4096)
      ["blocks"]=>
      int(0)
    }
    eio_mknod_ok

### See Also

- eio_open() - Opens a file

# eio_nop

(PECL eio >= 0.0.1dev)

eio_nop — Does nothing, except go through the whole request cycle

### Description

eio_nop(int `$pri` = EIO_PRI_DEFAULT, callable `$callback` = NULL, mixed `$data` = NULL): resource

eio_nop() does nothing, except go through the whole request cycle. Could be useful in debugging.

### Parameters

`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_nop() returns request resource on success, or `false` on failure.

### See Also

- eio_busy() - Artificially increase load. Could be useful in tests, benchmarking

# eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

### Description

eio_npending(): int

eio_npending() returns number of finished, but unhandled requests

### Parameters

This function has no parameters.

### Return Values

eio_npending() returns number of finished, but unhandled requests.

### See Also

- eio_nreqs() - Returns number of requests to be processed
- eio_nready() - Returns number of not-yet handled requests
- eio_nthreads() - Returns number of threads currently in use

# eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

### Description

eio_nready(): int

### Parameters

This function has no parameters.

### Return Values

eio_nready() returns number of not-yet handled requests

### See Also

- eio_nreqs() - Returns number of requests to be processed
- eio_nready()
- eio_nthreads() - Returns number of threads currently in use

# eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

### Description

eio_nreqs(): int

eio_nreqs() could be called in a custom loop calling eio_poll().

### Parameters

This function has no parameters.

### Return Values

eio_nreqs() returns number of requests to be processed.

### Examples

Example #1 eio_nreqs() example

`<?php
function res_cb($data, $result) {
var_dump($data);
var_dump($result);
}
eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");
while (eio_nreqs()) {
eio_poll();
}
?>`

The above example will output something similar to:

    string(1) "1"
    int(0)
    string(1) "3"
    int(0)
    string(1) "2"
    int(0)

### See Also

- eio_poll() - Can be to be called whenever there are pending requests that need finishing
- eio_nready() - Returns number of not-yet handled requests

# eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

### Description

eio_nthreads(): int

### Parameters

This function has no parameters.

### Return Values

eio_nthreads() returns number of threads currently in use.

### See Also

- eio_npending() - Returns number of finished, but unhandled requests
- eio_nready() - Returns number of not-yet handled requests
- eio_nreqs() - Returns number of requests to be processed
- eio_set_max_idle() - Set maximum number of idle threads
- eio_set_max_parallel() - Set maximum parallel threads
- eio_set_min_parallel() - Set minimum parallel thread number

# eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

### Description

eio_open(
string `$path`,
int `$flags`,
int `$mode`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

eio_open() opens file specified by `path` in access mode `mode` with

### Parameters

`path`

  Path of the file to be opened.

  Warning

  In some SAPIs(e.g. PHP-FPM) it could fail, if you don't specify full path.

`flags`
  One of EIO_O_* constants, or their combinations. EIO_O_* constants have the same meaning, as their corresponding O_* counterparts defined in `fnctl.h` C header file. Default is `EIO_O_RDWR`.
`mode`
  One of EIO_S_I* constants, or their combination (via bitwise OR operator). The constants have the same meaning as their S_I* counterparts defined in » sys/stat.h C header file. Required, if a file is created. Otherwise ignored.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_open() returns file descriptor in `result` argument of `callback` on success; otherwise, `result` is equal to `-1`.

### Examples

Example #1 eio_open() example

`<?php
$temp_filename = "eio-temp-file.tmp";
/* Is called when eio_close() finishes */
function my_close_cb($data, $result) {
// Zero indicates success
var_dump($result == 0);
@unlink($data);
}
/* Is called when eio_open() finishes */
function my_file_opened_callback($data, $result) {
// $result should contain the file descriptor
var_dump($result > 0);
if ($result > 0) {
// Close the file
eio_close($result, EIO_PRI_DEFAULT, "my_close_cb", $data);
eio_event_loop();
}
}
// Create new file for reading and writing
// Deny group and others to do anything with that file
eio_open($temp_filename, EIO_O_CREAT | EIO_O_RDWR, EIO_S_IRUSR | EIO_S_IWUSR,
EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    bool(true)
    bool(true)

### See Also

- eio_mknod() - Create a special or ordinary file

# eio_poll

(PECL eio >= 0.0.1dev)

eio_poll — Can be to be called whenever there are pending requests that need finishing

### Description

eio_poll(): int

eio_poll() can be used to implement special event loop. For this eio_nreqs() could be used to test if there are unprocessed requests.

> Note: Applicable only when implementing userspace event loop.

### Parameters

This function has no parameters.

### Return Values

If any request invocation returns a non-zero value, returns that value. Otherwise, it returns `0`.

### Examples

Example #1 eio_poll() example

`<?php
function res_cb($data, $result) {
var_dump($data);
var_dump($result);
}
eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");
while (eio_nreqs()) {
// Some specific IPC or so
eio_poll();
}
?>`

The above example will output something similar to:

    string(1) "1"
    int(0)
    string(1) "3"
    int(0)
    string(1) "2"
    int(0)

### See Also

- eio_nreqs() - Returns number of requests to be processed

# eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset

### Description

eio_read(
mixed `$fd`,
int `$length`,
int `$offset`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

eio_read() reads up to `length` bytes from `fd` file descriptor at `offset`. The read bytes are stored in `result` argument of `callback`.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor
`length`
  Maximum number of bytes to read.
`offset`
  Offset within the file.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_read() stores read bytes in `result` argument of `callback` function.

### Examples

Example #1 eio_read() example

`<?php
// Open a temporary file and write some bytes there
$temp_filename = "eio-temp-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "1234567890");
fclose($fp);
/* Is called when eio_read() is done */
function my_read_cb($data, $result) {
global $temp_filename;
// Output read bytes
var_dump($result);
// Close file
eio_close($data);
eio_event_loop();
// Remove temporary file
@unlink($temp_filename);
}
/* Is called when eio_open() is done */
function my_file_opened_callback($data, $result) {
// $result should contain the file descriptor
if ($result > 0) {
// Read 5 bytes starting from third
eio_read($result, 5, 2, EIO_PRI_DEFAULT, "my_read_cb", $result);
eio_event_loop();
} else {
// eio_open() failed
unlink($data);
}
}
// Open the file for reading and writing
eio_open($temp_filename, EIO_O_RDWR, NULL,
EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    string(5) "34567"

### See Also

- eio_open() - Opens a file
- eio_write() - Write to file
- eio_close() - Close file
- eio_event_loop() - Polls libeio until all requests proceeded

# eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

### Description

eio_readahead(
mixed `$fd`,
int `$offset`,
int `$length`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_readahead() populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. See `READAHEAD(2)` man page for details.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor
`offset`
  Starting point from which data is to be read.
`length`
  Number of bytes to be read.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_readahead() returns request resource on success, or `false` on failure.

# eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

### Description

eio_readdir(
string `$path`,
int `$flags`,
int `$pri`,
callable `$callback`,
string `$data` = NULL
): resource

Reads through a whole directory(via the `opendir`, `readdir` and `closedir` system calls) and returns either the names or an array in `result` argument of `callback` function, depending on the `flags` argument.

### Parameters

`path`
  Directory path.
`flags`
  Combination of EIO_READDIR_* constants.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_readdir() returns request resource on success, or `false` on failure. Sets `result` argument of `callback` function according to `flags`:

`EIO_READDIR_DENTS` (int)
  eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: `'names'` - array of directory names `'dents'` - array of `struct eio_dirent`-like arrays having the following keys each: `'name'` - the directory name; `'type'` - one of EIO_DT_* constants; `'inode'` - the inode number, if available, otherwise unspecified;
`EIO_READDIR_DIRS_FIRST` (int)
  When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
`EIO_READDIR_STAT_ORDER` (int)
  When this flag is specified, then the names will be returned in an order suitable for `stat`'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
`EIO_READDIR_FOUND_UNKNOWN` (int)

Node types:

`EIO_DT_UNKNOWN` (int)
  Unknown node type(very common). Further stat() needed.
`EIO_DT_FIFO` (int)
  FIFO node type
`EIO_DT_CHR` (int)
  Node type
`EIO_DT_MPC` (int)
  Multiplexed char device (v7+coherent) node type
`EIO_DT_DIR` (int)
  Directory node type
`EIO_DT_NAM` (int)
  Xenix special named file node type
`EIO_DT_BLK` (int)
  Node type
`EIO_DT_MPB` (int)
  Multiplexed block device (v7+coherent)
`EIO_DT_REG` (int)
  Node type
`EIO_DT_NWK` (int)
`EIO_DT_CMP` (int)
  HP-UX network special node type
`EIO_DT_LNK` (int)
  Link node type
`EIO_DT_SOCK` (int)
  Socket node type
`EIO_DT_DOOR` (int)
  Solaris door node type
`EIO_DT_WHT` (int)
  Node type
`EIO_DT_MAX` (int)
  Highest node type value

### Examples

Example #1 eio_readdir() example

`<?php
/* Is called when eio_readdir() finishes */
function my_readdir_callback($data, $result) {
echo __FUNCTION__, " called\n";
echo "data: "; var_dump($data);
echo "result: "; var_dump($result);
echo "\n";
}
eio_readdir("/var/spool/news", EIO_READDIR_STAT_ORDER | EIO_READDIR_DIRS_FIRST,
EIO_PRI_DEFAULT, "my_readdir_callback");
eio_event_loop();
?>`

The above example will output something similar to:

    my_readdir_callback called
    data: NULL
    result: array(2) {
     ["names"]=>
      array(7) {
       [0]=>
        string(7) "archive"
        [1]=>
        string(8) "articles"
        [2]=>
        string(8) "incoming"
        [3]=>
        string(7) "innfeed"
        [4]=>
        string(8) "outgoing"
        [5]=>
        string(8) "overview"
        [6]=>
        string(3) "tmp"
      }
     ["dents"]=>
      array(7) {
       [0]=>
        array(3)
        {
         ["name"]=>
          string(7)
          "archive"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393265)
        }
       [1]=>
        array(3)
        {
         ["name"]=>
          string(8)
          "articles"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393266)
        }
       [2]=>
        array(3)
        {
         ["name"]=>
          string(8)
          "incoming"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393267)
        }
       [3]=>
        array(3)
        {
         ["name"]=>
          string(7)
          "innfeed"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393269)
        }
       [4]=>
        array(3)
        {
         ["name"]=>
          string(8)
          "outgoing"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393270)
        }
       [5]=>
        array(3)
        {
         ["name"]=>
          string(8)
          "overview"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393271)
        }
       [6]=>
        array(3)
        {
         ["name"]=>
          string(3)
          "tmp"
          ["type"]=>
          int(4)
          ["inode"]=>
          int(393272)
        }
      }
    }

# eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link

### Description

eio_readlink(
string `$path`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

### Parameters

`path`
  Source symbolic link path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_readlink() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_readlink() example

`<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";
function my_hardlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && !is_link($data));
@unlink($data);
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}
function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));
if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}
function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);
@unlink($link);
@unlink($filename);
}
eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>`

The above example will output something similar to:

    bool(true)
    bool(true)
    string(16) "/tmp/symlink.dat"

### See Also

- eio_symlink() - Create a symbolic link

# eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname

### Description

eio_realpath(
string `$path`,
int `$pri`,
callable `$callback`,
string `$data` = NULL
): resource

eio_realpath() returns the canonicalized absolute pathname in `result` argument of `callback` function.

### Parameters

`path`
  Short pathname
`pri`
`callback`
`data`

### Return Values

### Examples

Example #1 eio_realpath() example

`<?php
var_dump(getcwd());
function my_realpath_allback($data, $result) {
var_dump($result);
}
eio_realpath("../", EIO_PRI_DEFAULT, "my_realpath_allback");
eio_event_loop();
?>`

The above example will output something similar to:

    string(12) "/home/ruslan"
    string(5) "/home"

# eio_rename

(PECL eio >= 0.0.1dev)

eio_rename — Change the name or location of a file

### Description

eio_rename(
string `$path`,
string `$new_path`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_rename() renames or moves a file to new location.

### Parameters

`path`
  Source path
`new_path`
  Target path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_rename() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_rename() example

`<?php
$filename = dirname(__FILE__)."/eio-temp-file.dat";
touch($filename);
$new_filename = dirname(__FILE__)."/eio-temp-file-new.dat";
function my_rename_cb($data, $result) {
global $filename, $new_filename;
if ($result == 0 && !file_exists($filename) && file_exists($new_filename)) {
@unlink($new_filename);
echo "eio_rename_ok";
} else {
@unlink($filename);
}
}
eio_rename($filename, $new_filename, EIO_PRI_DEFAULT, "my_rename_cb", $filename);
eio_event_loop();
?>`

The above example will output something similar to:

    eio_rename_ok

# eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

### Description

eio_rmdir(
string `$path`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_rmdir() removes a directory.

### Parameters

`path`
  Directory path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_rmdir() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_rmdir() example

`<?php
$temp_dirname = "eio-temp-dir";
mkdir($temp_dirname);
function my_rmdir_callback($data, $result) {
if ($result == 0 && !file_exists($data)) {
echo "eio_rmdir_ok";
} else if (file_exists($data)) {
rmdir($data);
}
}
eio_rmdir($temp_dirname, EIO_PRI_DEFAULT, "my_rmdir_callback", $temp_dirname);
eio_event_loop();
?>`

The above example will output something similar to:

    eio_rmdir_ok

### See Also

- eio_mkdir() - Create directory

# eio_seek

(PECL eio >= 0.5.0b)

eio_seek — Seek to a position

### Description

eio_seek(
mixed `$fd`,
int `$offset`,
int `$whence`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_seek() repositions the offset of the open file associated with stream, Socket instance, or file descriptor specified by `fd` to the argument `offset` according to the directive `whence`.

### Parameters

`fd`
  Stream, Socket instance, or numeric file descriptor.
`offset`
  Starting point from which data is to be read.
`whence`

  `whence` values are:

  - `EIO_SEEK_SET` - Set position equal to `offset` bytes.
  - `EIO_SEEK_CUR` - Set position to current location plus `offset`.
  - `EIO_SEEK_END` - Set position to end-of-file plus `offset`.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_seek() returns request resource on success, or `false` on failure.

# eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

### Description

eio_sendfile(
mixed `$out_fd`,
mixed `$in_fd`,
int `$offset`,
int `$length`,
int `$pri` = ?,
callable `$callback` = ?,
string `$data` = ?
): resource

eio_sendfile() copies data between one file descriptor and another. See `SENDFILE(2)` man page for details.

### Parameters

`out_fd`
  Output stream, Socket resource, or file descriptor. Should be opened for writing.
`in_fd`
  Input stream, Socket resource, or file descriptor. Should be opened for reading.
`offset`
  Offset within the source file.
`length`
  Number of bytes to copy.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_sendfile() returns request resource on success, or `false` on failure.

# eio_set_max_idle

(PECL eio >= 0.0.1dev)

eio_set_max_idle — Set maximum number of idle threads

### Description

eio_set_max_idle(int `$nthreads`): void

### Parameters

`nthreads`
  Number of idle threads.

### Return Values

No value is returned.

### See Also

- eio_nthreads() - Returns number of threads currently in use
- eio_set_min_parallel() - Set minimum parallel thread number
- eio_set_max_parallel() - Set maximum parallel threads

# eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

### Description

eio_set_max_parallel(int `$nthreads`): void

### Parameters

`nthreads`
  Number of parallel threads

### Return Values

No value is returned.

### See Also

- eio_nthreads() - Returns number of threads currently in use
- eio_set_max_idle() - Set maximum number of idle threads
- eio_set_min_parallel() - Set minimum parallel thread number

# eio_set_max_poll_reqs

(PECL eio >= 0.0.1dev)

eio_set_max_poll_reqs — Set maximum number of requests processed in a poll

### Description

eio_set_max_poll_reqs(int `$nreqs`): void

### Parameters

`nreqs`
  Number of requests

### Return Values

No value is returned.

# eio_set_max_poll_time

(PECL eio >= 0.0.1dev)

eio_set_max_poll_time — Set maximum poll time

### Description

eio_set_max_poll_time(float `$nseconds`): void

Polling stops, if poll took longer than `nseconds` seconds.

### Parameters

`nseconds`
  Number of seconds

### Return Values

No value is returned.

# eio_set_min_parallel

(PECL eio >= 0.0.1dev)

eio_set_min_parallel — Set minimum parallel thread number

### Description

eio_set_min_parallel(string `$nthreads`): void

### Parameters

`nthreads`
  Number of parallel threads.

### Return Values

No value is returned.

### See Also

- eio_nthreads() - Returns number of threads currently in use
- eio_set_max_idle() - Set maximum number of idle threads
- eio_set_max_parallel() - Set maximum parallel threads

# eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

### Description

eio_stat(
string `$path`,
int `$pri`,
callable `$callback`,
mixed `$data` = NULL
): resource

eio_stat() returns file status information in `result` argument of `callback`

### Parameters

`path`
  The file path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_stat() returns request resource on success or `false` on error. On success assigns `result` argument of `callback` to an array.

### Examples

Example #1 eio_stat() example

`<?php
$tmp_filename = "eio-file.tmp";
touch($tmp_filename);
function my_res_cb($data, $result) {
var_dump($data);
var_dump($result);
}
function my_open_cb($data, $result) {
eio_close($result);
eio_event_loop();
@unlink($data);
}
eio_stat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_stat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    string(8) "eio_stat"
    array(12) {
      ["st_dev"]=>
      int(2050)
      ["st_ino"]=>
      int(2489173)
      ["st_mode"]=>
      int(33188)
      ["st_nlink"]=>
      int(1)
      ["st_uid"]=>
      int(1000)
      ["st_gid"]=>
      int(100)
      ["st_rdev"]=>
      int(0)
      ["st_blksize"]=>
      int(4096)
      ["st_blocks"]=>
      int(0)
      ["st_atime"]=>
      int(1318250380)
      ["st_mtime"]=>
      int(1318250380)
      ["st_ctime"]=>
      int(1318250380)
    }

### See Also

- eio_lstat() - Get file status
- eio_fstat() - Get file status

# eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

### Description

eio_statvfs(
string `$path`,
int `$pri`,
callable `$callback`,
mixed `$data` = ?
): resource

eio_statvfs() returns file system statistics information in `result` argument of `callback`

### Parameters

`path`
  Pathname of any file within the mounted file system
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_statvfs() returns request resource on success, or `false` on failure. On success assigns `result` argument of `callback` to an array.

### Examples

Example #1 eio_statvfs() example

`<?php
$tmp_filename = '/tmp/eio-file.tmp';
touch($tmp_filename);
function my_statvfs_callback($data, $result) {
var_dump($data);
var_dump($result);
@unlink($data);
}
eio_statvfs($tmp_filename, EIO_PRI_DEFAULT, "my_statvfs_callback", $tmp_filename);
eio_event_loop();
?>`

The above example will output something similar to:

    string(17) "/tmp/eio-file.tmp"
    array(11) {
      ["f_bsize"]=>
      int(4096)
      ["f_frsize"]=>
      int(4096)
      ["f_blocks"]=>
      int(262144)
      ["f_bfree"]=>
      int(262111)
      ["f_bavail"]=>
      int(262111)
      ["f_files"]=>
      int(1540815)
      ["f_ffree"]=>
      int(1540743)
      ["f_favail"]=>
      int(1540743)
      ["f_fsid"]=>
      int(0)
      ["f_flag"]=>
      int(4102)
      ["f_namemax"]=>
      int(255)
    }

# eio_symlink

(PECL eio >= 0.0.1dev)

eio_symlink — Create a symbolic link

### Description

eio_symlink(
string `$path`,
string `$new_path`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_symlink() creates a symbolic link `new_path` to `path`.

### Parameters

`path`
  Source path
`new_path`
  Target path
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_symlink() returns request resource on success, or `false` on failure.

### Examples

Example #1 eio_symlink() example

`<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));
if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}
function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);
@unlink($link);
@unlink($filename);
}
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
eio_event_loop();
?>`

The above example will output something similar to:

    bool(true)
    string(16) "/tmp/symlink.dat"

### See Also

- eio_link() - Create a hardlink for file

# eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

### Description

eio_sync(int `$pri` = EIO_PRI_DEFAULT, callable `$callback` = NULL, mixed `$data` = NULL): resource

### Parameters

This function has no parameters.

### Return Values

eio_sync() returns request resource on success, or `false` on failure.

# eio_sync_file_range

(PECL eio >= 0.0.1dev)

eio_sync_file_range — Sync a file segment with disk

### Description

eio_sync_file_range(
mixed `$fd`,
int `$offset`,
int `$nbytes`,
int `$flags`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_sync_file_range() permits fine control when synchronizing the open file referred to by the file descriptor `fd` with disk.

### Parameters

`fd`
  File descriptor
`offset`
  The starting byte of the file range to be synchronized
`nbytes`
  Specifies the length of the range to be synchronized, in bytes. If `nbytes` is zero, then all bytes from `offset` through to the end of file are synchronized.
`flags`
  A bit-mask. Can include any of the following values: `EIO_SYNC_FILE_RANGE_WAIT_BEFORE`, `EIO_SYNC_FILE_RANGE_WRITE`, `EIO_SYNC_FILE_RANGE_WAIT_AFTER`. These flags have the same meaning as their SYNC_FILE_RANGE_* counterparts(see `SYNC_FILE_RANGE(2)` man page).
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_sync_file_range() returns request resource on success, or `false` on failure.

# eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

### Description

eio_syncfs(
mixed `$fd`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

### Parameters

`fd`
  File descriptor
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_syncfs() returns request resource on success, or `false` on failure.

# eio_truncate

(PECL eio >= 0.0.1dev)

eio_truncate — Truncate a file

### Description

eio_truncate(
string `$path`,
int `$offset` = 0,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_truncate() causes the regular file named by `path` to be truncated to a size of precisely `length` bytes

### Parameters

`path`
  File path
`offset`
  Offset from beginning of the file.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_busy() returns request resource on success, or `false` on failure.

### See Also

- eio_ftruncate() - Truncate a file

# eio_unlink

(PECL eio >= 0.0.1dev)

eio_unlink — Delete a name and possibly the file it refers to

### Description

eio_unlink(
string `$path`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_unlink() deletes a name from the file system.

### Parameters

`path`
  Path to file
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_unlink() returns request resource on success, or `false` on failure.

# eio_utime

(PECL eio >= 0.0.1dev)

eio_utime — Change file last access and modification times

### Description

eio_utime(
string `$path`,
float `$atime`,
float `$mtime`,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

### Parameters

`path`
  Path to the file.
`atime`
  Access time
`mtime`
  Modification time
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_utime() returns request resource on success, or `false` on failure.

### See Also

- eio_futime() - Change file last access and modification times

# eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

### Description

eio_write(
mixed `$fd`,
string `$str`,
int `$length` = 0,
int `$offset` = 0,
int `$pri` = EIO_PRI_DEFAULT,
callable `$callback` = NULL,
mixed `$data` = NULL
): resource

eio_write() writes up to `length` bytes from `str` at `offset` offset from the beginning of the file.

### Parameters

`fd`
  Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()
`str`
  Source string
`length`
  Maximum number of bytes to write.
`offset`
  Offset from the beginning of file.
`pri`

  The request priority: `EIO_PRI_DEFAULT`, `EIO_PRI_MIN`, `EIO_PRI_MAX`, or `null`. If `null` passed, `pri` internally is set to `EIO_PRI_DEFAULT`.

`callback`

  `callback` function is called when the request is done. It should match the following prototype:

  `void callback(mixed $data, int $result[, resource $req]);`
  `data`

    is custom data passed to the request.

  `result`

    request-specific result value; basically, the value returned by corresponding system call.

  `req`

    is optional request resource which can be used with functions like eio_get_last_error().

`data`
  Arbitrary variable passed to `callback`.

### Return Values

eio_write() returns request resource on success, or `false` on failure.

### See Also

- eio_open() - Opens a file

## Table of Contents

- eio_busy — Artificially increase load. Could be useful in tests, benchmarking
- eio_cancel — Cancels a request
- eio_chmod — Change file/directory permissions
- eio_chown — Change file/directory permissions
- eio_close — Close file
- eio_custom — Execute custom request like any other eio_* call
- eio_dup2 — Duplicate a file descriptor
- eio_event_loop — Polls libeio until all requests proceeded
- eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
- eio_fchmod — Change file permissions
- eio_fchown — Change file ownership
- eio_fdatasync — Synchronize a file's in-core state with storage device
- eio_fstat — Get file status
- eio_fstatvfs — Get file system statistics
- eio_fsync — Synchronize a file's in-core state with storage device
- eio_ftruncate — Truncate a file
- eio_futime — Change file last access and modification times
- eio_get_event_stream — Get stream representing a variable used in internal communications with libeio
- eio_get_last_error — Returns string describing the last error associated with a request resource
- eio_grp — Creates a request group
- eio_grp_add — Adds a request to the request group
- eio_grp_cancel — Cancels a request group
- eio_grp_limit — Set group limit
- eio_init — (Re-)initialize Eio
- eio_link — Create a hardlink for file
- eio_lstat — Get file status
- eio_mkdir — Create directory
- eio_mknod — Create a special or ordinary file
- eio_nop — Does nothing, except go through the whole request cycle
- eio_npending — Returns number of finished, but unhandled requests
- eio_nready — Returns number of not-yet handled requests
- eio_nreqs — Returns number of requests to be processed
- eio_nthreads — Returns number of threads currently in use
- eio_open — Opens a file
- eio_poll — Can be to be called whenever there are pending requests that need finishing
- eio_read — Read from a file descriptor at given offset
- eio_readahead — Perform file readahead into page cache
- eio_readdir — Reads through a whole directory
- eio_readlink — Read value of a symbolic link
- eio_realpath — Get the canonicalized absolute pathname
- eio_rename — Change the name or location of a file
- eio_rmdir — Remove a directory
- eio_seek — Seek to a position
- eio_sendfile — Transfer data between file descriptors
- eio_set_max_idle — Set maximum number of idle threads
- eio_set_max_parallel — Set maximum parallel threads
- eio_set_max_poll_reqs — Set maximum number of requests processed in a poll
- eio_set_max_poll_time — Set maximum poll time
- eio_set_min_parallel — Set minimum parallel thread number
- eio_stat — Get file status
- eio_statvfs — Get file system statistics
- eio_symlink — Create a symbolic link
- eio_sync — Commit buffer cache to disk
- eio_sync_file_range — Sync a file segment with disk
- eio_syncfs — Calls Linux' syncfs syscall, if available
- eio_truncate — Truncate a file
- eio_unlink — Delete a name and possibly the file it refers to
- eio_utime — Change file last access and modification times
- eio_write — Write to file

- Installing/Configuring
  - Requirements
  - Installation
  - Resource Types
- Predefined Constants
- Examples
- Eio Functions
  - eio_busy — Artificially increase load. Could be useful in tests, benchmarking
  - eio_cancel — Cancels a request
  - eio_chmod — Change file/directory permissions
  - eio_chown — Change file/directory permissions
  - eio_close — Close file
  - eio_custom — Execute custom request like any other eio_* call
  - eio_dup2 — Duplicate a file descriptor
  - eio_event_loop — Polls libeio until all requests proceeded
  - eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
  - eio_fchmod — Change file permissions
  - eio_fchown — Change file ownership
  - eio_fdatasync — Synchronize a file's in-core state with storage device
  - eio_fstat — Get file status
  - eio_fstatvfs — Get file system statistics
  - eio_fsync — Synchronize a file's in-core state with storage device
  - eio_ftruncate — Truncate a file
  - eio_futime — Change file last access and modification times
  - eio_get_event_stream — Get stream representing a variable used in internal communications with libeio
  - eio_get_last_error — Returns string describing the last error associated with a request resource
  - eio_grp — Creates a request group
  - eio_grp_add — Adds a request to the request group
  - eio_grp_cancel — Cancels a request group
  - eio_grp_limit — Set group limit
  - eio_init — (Re-)initialize Eio
  - eio_link — Create a hardlink for file
  - eio_lstat — Get file status
  - eio_mkdir — Create directory
  - eio_mknod — Create a special or ordinary file
  - eio_nop — Does nothing, except go through the whole request cycle
  - eio_npending — Returns number of finished, but unhandled requests
  - eio_nready — Returns number of not-yet handled requests
  - eio_nreqs — Returns number of requests to be processed
  - eio_nthreads — Returns number of threads currently in use
  - eio_open — Opens a file
  - eio_poll — Can be to be called whenever there are pending requests that need finishing
  - eio_read — Read from a file descriptor at given offset
  - eio_readahead — Perform file readahead into page cache
  - eio_readdir — Reads through a whole directory
  - eio_readlink — Read value of a symbolic link
  - eio_realpath — Get the canonicalized absolute pathname
  - eio_rename — Change the name or location of a file
  - eio_rmdir — Remove a directory
  - eio_seek — Seek to a position
  - eio_sendfile — Transfer data between file descriptors
  - eio_set_max_idle — Set maximum number of idle threads
  - eio_set_max_parallel — Set maximum parallel threads
  - eio_set_max_poll_reqs — Set maximum number of requests processed in a poll
  - eio_set_max_poll_time — Set maximum poll time
  - eio_set_min_parallel — Set minimum parallel thread number
  - eio_stat — Get file status
  - eio_statvfs — Get file system statistics
  - eio_symlink — Create a symbolic link
  - eio_sync — Commit buffer cache to disk
  - eio_sync_file_range — Sync a file segment with disk
  - eio_syncfs — Calls Linux' syncfs syscall, if available
  - eio_truncate — Truncate a file
  - eio_unlink — Delete a name and possibly the file it refers to
  - eio_utime — Change file last access and modification times
  - eio_write — Write to file

# Ev

# Introduction

This extension provides interface to » libev library - a high performance full-featured event loop written in C.

> Note: This extension is not available on Windows platforms.

Libev is an event loop: one registers interest in certain events (such as a file descriptor being readable or a timeout occurring), and it will manage these event sources and provide the program with events.

To do this, it must take more or less complete control over the process (or thread) by executing the event loop handler, and will then communicate events via a callback mechanism.

You register interest in certain events by registering so-called event watchers, and then hand it over to libev by starting the watcher.

For details refer to the » documentation of libev.

# Installing/Configuring

## Table of Contents

- Requirements
- Installation

## Requirements

`libev` library is embedded into this extension. You don't need to install it separately.

## Installation

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: » https://pecl.php.net/package/ev.

# Examples

Example #1 Simple timers

`<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
echo "2 seconds elapsed\n";
});
// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo "Callback of a timer created as stopped\n";
// Stop the watcher after 2 iterations
Ev::iteration() >= 2 and $w->stop();
});
// Loop until Ev::stop() is called or all of watchers stop
Ev::run();
// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);
echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);
$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>`

The above example will output something similar to:

    2 seconds elapsed
    is called every second, is launched after 2 seconds
    iteration = 1
    is called every second, is launched after 2 seconds
    iteration = 2
    is called every second, is launched after 2 seconds
    iteration = 3
    is called every second, is launched after 2 seconds
    iteration = 4
    is called every second, is launched after 2 seconds
    iteration = 5
    Run single iteration
    Callback of a timer created as stopped
    Restart the second watcher and try to handle the same events, but don't block
    Running a blocking loop
    is called every second, is launched after 2 seconds
    iteration = 8
    is called every second, is launched after 2 seconds
    iteration = 9
    is called every second, is launched after 2 seconds
    iteration = 10
    END

Example #2 Periodic timer. Tick each 10.5 seconds

`<?php
$w = new EvPeriodic(0., 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>`

Example #3 Periodic timer. Use reschedule callback

`<?php
// Tick each 10.5 seconds
function reschedule_cb ($watcher, $now) {
return $now + (10.5. - fmod($now, 10.5));
}
$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>`

Example #4 Periodic timer. Tick every 10.5 seconds starting at now

`<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>`

Example #5 Wait until STDIN is readable

`<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
echo "STDIN is readable\n";
});
Ev::run(Ev::RUN_ONCE);
?>`

Example #6 Use some async I/O to access a socket

`<?php
/* Use some async I/O to access a socket */
// `sockets' extension still logs warnings
// for EINPROGRESS, EAGAIN/EWOULDBLOCK etc.
error_reporting(E_ERROR);
$e_nonblocking = array (/*EAGAIN or EWOULDBLOCK*/11, /*EINPROGRESS*/115);
// Get the port for the WWW service
$service_port = getservbyname('www', 'tcp');
// Get the IP address for the target host
$address = gethostbyname('google.co.uk');
// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === FALSE) {
echo "socket_create() failed: reason: "
.socket_strerror(socket_last_error()) . "\n";
}
// Set O_NONBLOCK flag
socket_set_nonblock($socket);
// Abort on timeout
$timeout_watcher = new EvTimer(10.0, 0., function () use ($socket) {
socket_close($socket);
Ev::stop(Ev::BREAK_ALL);
});
// Make HEAD request when the socket is writable
$write_watcher = new EvIo($socket, Ev::WRITE, function ($w)
use ($socket, $timeout_watcher, $e_nonblocking)
{
// Stop timeout watcher
$timeout_watcher->stop();
// Stop write watcher
$w->stop();
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: google.co.uk\r\n";
$in .= "Connection: Close\r\n\r\n";
if (!socket_write($socket, $in, strlen($in))) {
trigger_error("Failed writing $in to socket", E_USER_ERROR);
}
$read_watcher = new EvIo($socket, Ev::READ, function ($w, $re)
use ($socket, $e_nonblocking)
{
// Socket is readable. recv() 20 bytes using non-blocking mode
$ret = socket_recv($socket, $out, 20, MSG_DONTWAIT);
if ($ret) {
echo $out;
} elseif ($ret === 0) {
// All read
$w->stop();
socket_close($socket);
return;
}
// Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
if (in_array(socket_last_error(), $e_nonblocking)) {
return;
}
$w->stop();
socket_close($socket);
});
Ev::run();
});
$result = socket_connect($socket, $address, $service_port);
Ev::run();
?>`

The above example will output something similar to:

    HTTP/1.1 301 Moved Permanently
    Location: http://www.google.co.uk/
    Content-Type: text/html; charset=UTF-8
    Date: Sun, 23 Dec 2012 16:08:27 GMT
    Expires: Tue, 22 Jan 2013 16:08:27 GMT
    Cache-Control: public, max-age=2592000
    Server: gws
    Content-Length: 221
    X-XSS-Protection: 1; mode=block
    X-Frame-Options: SAMEORIGIN
    Connection: close

Example #7 Embedding one loop into another

`<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed = NULL;
/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
: 0;
if ($loop_lo) {
$embed = new EvEmbed($loop_lo, function () {});
} else {
$loop_lo = $loop_hi;
}
?>`

Example #8 Embedding loop created with kqueue backend into the default loop

`<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;
if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}
if (!$socket_loop) {
$socket_loop = $loop;
}
// Now use $socket_loop for all sockets, and $loop for anything else
?>`

Example #9 Handle SIGTERM signal

`<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
echo "SIGTERM received\n";
$watcher->stop();
});
Ev::run();
?>`

Example #10 Monitor changes of /var/log/messages

`<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
echo "/var/log/messages changed\n";
$attr = $w->attr();
if ($attr['nlink']) {
printf("Current size: %ld\n", $attr['size']);
printf("Current atime: %ld\n", $attr['atime']);
printf("Current mtime: %ld\n", $attr['mtime']);
} else {
fprintf(STDERR, "`messages` file is not there!");
$w->stop();
}
});
Ev::run();
?>`

Example #11 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

`<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
$w->stop();
$stat = $w->data;
// 1 second after the most recent change of the file
printf("Current size: %ld\n", $stat->attr()['size']);
});
$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
// Reset timer watcher
$timer->again();
});
$timer->data = $stat;
Ev::run();
?>`

Example #12 Process status changes

`<?php
$pid = pcntl_fork();
if ($pid == -1) {
fprintf(STDERR, "pcntl_fork failed\n");
} elseif ($pid) {
$w = new EvChild($pid, FALSE, function ($w, $revents) {
$w->stop();
printf("Process %d exited with status %d\n", $w->rpid, $w->rstatus);
});
Ev::run();
// Protect against Zombies
pcntl_wait($status);
} else {
//Forked child
exit(2);
}
?>`

# Watchers

A watcher is an object that gets created to record interest in some event. For instance, the following code waits for `STDIN` to become readable:

`<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
echo "STDIN is readable\n";
});
Ev::run(Ev::RUN_ONCE);
?>`

All the watcher constructors automatically start the watchers. `createStopped` methods create stopped watchers(e.g. EvIo::createStopped())

Note that a watcher will automatically be stopped when the watcher object is destroyed. Therefore, the watcher objects returned by the constructors or factory methods should be kept.

Note also that all methods changing some watcher property( set, priority etc.) automatically stop and start it again if it is active, which means pending events get lost.

See also: Watcher callbacks.

# Watcher callbacks

All watchers can be active(waiting for events) or inactive(paused). Only active watchers will have their callbacks invoked. All callbacks will be called with at least two arguments: `watcher` - the watcher, and `revents` a bitmask of received events.

Watcher callbacks are passed to the watcher constructors (the classes derived from EvWatcher - EvCheck::__construct(), EvChild::__construct() etc.). A watcher callback should match the following prototype:

callback( object `$watcher` = NULL , int `$revents` = NULL ): void

`watcher`
  The watcher instance(of a class extending EvWatcher ).
`revents`
  Watcher received events.

Each watcher type has its associated bit in `revents`, so one can use the same callback for multiple watchers. The event mask is named after the type, i.e. EvChild (or EvLoop::child()) sets `EV::CHILD`, EvPrepare (or EvLoop::prepare()) sets `Ev::PREPARE`, EvPeriodic (or EvLoop::periodic()) sets `Ev::PERIODIC` and so on, with the exception of I/O events (which can set both `Ev::READ` and `Ev::WRITE` bits).

# Periodic watcher operation modes

EvPeriodic watcher works in different modes depending on the `offset`, `interval` and `reschedule_cb` parameters.

1. Absolute timer. In this mode `interval` = `0`, `reschedule_cb` = `null`. This time simply fires at the wallclock time `offset` and doesn't repeat. It will not adjust when a time jump occurs, that is, if it is to be run at January 1st 2014 then it will run when the system time reaches or surpasses this time.
2. Repeating interval timer. In this mode `interval` > `0`, `reschedule_cb` = `null`; the watcher will always be scheduled to timeout at the next `offset` + `N` * `interval` time(for some integer `N`) and then repeat, regardless of any time jumps.

   This can be used to create timers that do not drift with respect to system time:

   `<?php
   $hourly = EvPeriodic(0, 3600, NULL, function () {
   echo "once per hour\n";
   });
   ?>`
   That doesn't mean there will always be `3600` seconds in between triggers, but only that the callback will be called when the system time shows a full hour( UTC ). EvPeriodic will try to run the callback in this mode at the next possible time where time = `offset` ( `mod` `interval` ), regardless of any time jumps.
3. Manual reschedule mode. In this mode `reschedule_cb` is a callable. `interval` and `offset` are both being ignored. Instead, each time the periodic watcher gets scheduled, the reschedule callback ( `reschedule_cb`) will be called with the watcher as first, and the current time as second argument. This callback must not stop or destroy this or any other periodic watchers, ever, and must not call any event loop functions or methods. To stop it return `1e30` and stop it afterwards. An EvPrepare watcher may be used for this task. It must return the next time to trigger, based on the passed time value (that is, the lowest time value larger than or equal to the second argument). It will usually be called just before the callback will be triggered, but might be called at other times, too.

   Example #1 Using reschedule callback

   `<?php
   // Tick each 10.5 seconds
   function reschedule_cb ($watcher, $now) {
   return $now + (10.5. - fmod($now, 10.5));
   }
   $w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
   echo time(), PHP_EOL;
   });
   Ev::run();
   ?>`

# The Ev class

(PECL ev >= 0.2.0)

## Introduction

Ev is a static class providing access to the default loop and to some common operations.

## Class synopsis

final class Ev {
/* Constants */
const int FLAG_AUTO = 0;
const int FLAG_NOENV = 16777216;
const int FLAG_FORKCHECK = 33554432;
const int FLAG_NOINOTIFY = 1048576;
const int FLAG_SIGNALFD = 2097152;
const int FLAG_NOSIGMASK = 4194304;
const int RUN_NOWAIT = 1;
const int RUN_ONCE = 2;
const int BREAK_CANCEL = 0;
const int BREAK_ONE = 1;
const int BREAK_ALL = 2;
const int MINPRI = -2;
const int MAXPRI = 2;
const int READ = 1;
const int WRITE = 2;
const int TIMER = 256;
const int PERIODIC = 512;
const int SIGNAL = 1024;
const int CHILD = 2048;
const int STAT = 4096;
const int IDLE = 8192;
const int PREPARE = 16384;
const int CHECK = 32768;
const int EMBED = 65536;
const int CUSTOM = 16777216;
const int ERROR = 2147483648;
const int BACKEND_SELECT = 1;
const int BACKEND_POLL = 2;
const int BACKEND_EPOLL = 4;
const int BACKEND_KQUEUE = 8;
const int BACKEND_DEVPOLL = 16;
const int BACKEND_PORT = 32;
const int BACKEND_ALL = 63;
const int BACKEND_MASK = 65535;
/* Methods */
final public static backend(): int
final public static depth(): int
final public static embeddableBackends(): int
final public static feedSignal( int `$signum` ): void
final public static feedSignalEvent( int `$signum` ): void
final public static iteration(): int
final public static now(): float
final public static nowUpdate(): void
final public static recommendedBackends(): int
final public static resume(): void
final public static run( int `$flags` = ?): void
final public static sleep( float `$seconds` ): void
final public static stop( int `$how` = ?): void
final public static supportedBackends(): int
final public static suspend(): void
final public static time(): float
final public static verify(): void
}

## Predefined Constants

Flags passed to create a loop:

`Ev::FLAG_AUTO`
  The default flags value
`Ev::FLAG_NOENV`
  If this flag used(or the program runs setuid or setgid), `libev` won't look at the environment variable LIBEV_FLAGS. Otherwise(by default), LIBEV_FLAGS will override the flags completely if it is found. Useful for performance tests and searching for bugs.
`Ev::FLAG_FORKCHECK`
  Makes libev check for a fork in each iteration, instead of calling EvLoop::fork() manually. This works by calling `getpid()` on every iteration of the loop, and thus this might slow down the event loop with lots of loop iterations, but usually is not noticeable. This flag setting cannot be overridden or specified in the LIBEV_FLAGS environment variable.
`Ev::FLAG_NOINOTIFY`
  When this flag is specified, `libev` won't attempt to use the `inotify` API for its » ev_stat watchers. The flag can be useful to conserve inotify file descriptors, as otherwise each loop using `ev_stat` watchers consumes one `inotify` handle.
`Ev::FLAG_SIGNALFD`
  When this flag is specified, `libev` will attempt to use the `signalfd` API for its » ev_signal (and » ev_child) watchers. This API delivers signals synchronously, which makes it both faster and might make it possible to get the queued signal data. It can also simplify signal handling with threads, as long as signals are properly blocked in threads. `Signalfd` will not be used by default.
`Ev::FLAG_NOSIGMASK`
  When this flag is specified, `libev` will avoid to modify the signal mask. Specifically, this means having to make sure signals are unblocked before receiving them. This behaviour is useful for custom signal handling, or handling signals only in specific threads.

Flags passed to Ev::run(), or EvLoop::run()

`Ev::RUN_NOWAIT`
  Means that event loop will look for new events, will handle those events and any already outstanding ones, but will not wait and block the process in case there are no events and will return after one iteration of the loop. This is sometimes useful to poll and handle new events while doing lengthy calculations, to keep the program responsive.
`Ev::RUN_ONCE`
  Means that event loop will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block the process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop.

Flags passed to Ev::stop(), or EvLoop::stop()

`Ev::BREAK_CANCEL`
  Cancel the break operation.
`Ev::BREAK_ONE`
  Makes the innermost Ev::run() (or EvLoop::run()) call return.
`Ev::BREAK_ALL`
  Makes all nested Ev::run() (or EvLoop::run()) calls return.

Watcher priorities:

`Ev::MINPRI`
  Minimum allowed watcher priority.
`Ev::MAXPRI`
  Maximum allowed watcher priority.

Bit masks of (received) events:

`Ev::READ`
  The file descriptor in the EvIo watcher has become readable.
`Ev::WRITE`
  The file descriptor in the EvIo watcher has become writable.
`Ev::TIMER`
  EvTimer watcher has been timed out.
`Ev::PERIODIC`
  EvPeriodic watcher has been timed out.
`Ev::SIGNAL`
  A signal specified in EvSignal::__construct() has been received.
`Ev::CHILD`
  The `pid` specified in EvChild::__construct() has received a status change.
`Ev::STAT`
  The path specified in EvStat watcher changed its attributes.
`Ev::IDLE`
  EvIdle watcher works when there is nothing to do with other watchers.
`Ev::PREPARE`
  All EvPrepare watchers are invoked just before Ev::run() starts. Thus, EvPrepare watchers are the last watchers invoked before the event loop sleeps or polls for new events.
`Ev::CHECK`
  All EvCheck watchers are queued just after Ev::run() has gathered the new events, but before it queues any callbacks for any received events. Thus, EvCheck watchers will be invoked before any other watchers of the same or lower priority within an event loop iteration.
`Ev::EMBED`
  The embedded event loop specified in the EvEmbed watcher needs attention.
`Ev::CUSTOM`
  Not ever sent(or otherwise used) by `libev` itself, but can be freely used by `libev` users to signal watchers (e.g. via EvWatcher::feed() ).
`Ev::ERROR`
  An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because `libev` ran out of memory, a file descriptor was found to be closed or any other problem. `Libev` considers these application bugs. See also » ANATOMY OF A WATCHER

Backend flags:

`Ev::BACKEND_SELECT`
  `select(2) backend`
`Ev::BACKEND_POLL`
  `poll(2) backend`
`Ev::BACKEND_EPOLL`
  Linux-specific `epoll(7)` backend for both pre- and post-2.6.9 kernels
`Ev::BACKEND_KQUEUE`
  `kqueue` backend used on most BSD systems. EvEmbed watcher could be used to embed one loop(with kqueue backend) into another. For instance, one can try to create an event loop with `kqueue` backend and use it for sockets only.
`Ev::BACKEND_DEVPOLL`
  Solaris 8 backend. This is not implemented yet.
`Ev::BACKEND_PORT`
  Solaris 10 event port mechanism with a good scaling.
`Ev::BACKEND_ALL`
  Try all backends(even currupted ones). It's not recommended to use it explicitly. Bitwise operators should be applied here(e.g. `Ev::BACKEND_ALL` & ~ `Ev::BACKEND_KQUEUE`) Use Ev::recommendedBackends(), or don't specify any backends at all.
`Ev::BACKEND_MASK`
  Not a backend, but a mask to select all backend bits from `flags` value to mask out any backends(e.g. when modifying the LIBEV_FLAGS environment variable).

> Note: For the default loop during module initialization phase `Ev` registers » ev_loop_fork call by means of `pthread_atfork` (if available).

> Note: There are methods providing access to the default event loop in Ev class(e.g. Ev::iteration(), Ev::depth() etc.) For custom loops (created with EvLoop::__construct()) these values may be accessed via corresponding properties and methods of the EvLoop class. The instance of the default event loop itself can be fetched by means of EvLoop::defaultLoop() method.

# Ev::backend

(PECL ev >= 0.2.0)

Ev::backend — Returns an integer describing the backend used by libev

### Description

final public static Ev::backend(): int

Returns an integer describing the backend used by libev. See Backend flags

### Parameters

This function has no parameters.

### Return Values

Returns an integer(bit mask) describing the backend used by libev.

### See Also

- EvEmbed
- Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
- Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
- Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
- Backend flags

# Ev::depth

(PECL ev >= 0.2.0)

Ev::depth — Returns recursion depth

### Description

final public static Ev::depth(): int

The number of times Ev::run() was entered minus the number of times Ev::run() was exited normally, in other words, the recursion depth. Outside Ev::run(), this number is `0`. In a callback, this number is `1`, unless Ev::run() was invoked recursively (or from another thread), in which case it is higher.

### Parameters

This function has no parameters.

### Return Values

ev_depth() returns recursion depth of the default loop.

### See Also

- Ev::iteration() - Return the number of times the default event loop has polled for new events

# Ev::embeddableBackends

(PECL ev >= 0.2.0)

Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops

### Description

final public static Ev::embeddableBackends(): int

Returns the set of backends that are embeddable in other event loops.

### Parameters

This function has no parameters.

### Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

### Examples

Example #1 Embedding loop created with kqueue backend into the default loop

`<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;
if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}
if (!$socket_loop) {
$socket_loop = $loop;
}
// Now use $socket_loop for all sockets, and $loop for anything else
?>`

### See Also

- EvEmbed
- Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
- Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
- Backend flags
- Examples

# Ev::feedSignal

(PECL ev >= 0.2.0)

Ev::feedSignal — Feed a signal event info Ev

### Description

final public static Ev::feedSignal( int `$signum` ): void

Simulates a signal receive. It is safe to call this function at any time, from any context, including signal handlers or random threads. Its main use is to customise signal handling in the process.

Unlike Ev::feedSignalEvent(), this works regardless of which loop has registered the signal.

### Parameters

`signum`
  Signal number. See `signal(7)` man page for detals. You can use constants exported by `pcntl` extension.

### Return Values

No value is returned.

### See Also

- Ev::feedSignalEvent() - Feed signal event into the default loop

# Ev::feedSignalEvent

(No version information available, might only be in Git)

Ev::feedSignalEvent — Feed signal event into the default loop

### Description

final public static Ev::feedSignalEvent( int `$signum` ): void

Feed signal event into the default loop. Ev will react to this call as if the signal specified by `signal` had occurred.

### Parameters

`signum`
  Signal number. See `signal(7)` man page for detals. See also constants exported by `pcntl` extension.

### Return Values

No value is returned.

### See Also

- Ev::feedSignal() - Feed a signal event info Ev

# Ev::iteration

(PECL ev >= 0.2.0)

Ev::iteration — Return the number of times the default event loop has polled for new events

### Description

final public static Ev::iteration(): int

Return the number of times the event loop has polled for new events. Sometimes useful as a generation counter.

### Parameters

This function has no parameters.

### Return Values

Returns number of polls of the default event loop.

### See Also

- Ev::depth() - Returns recursion depth

# Ev::now

(PECL ev >= 0.2.0)

Ev::now — Returns the time when the last iteration of the default event loop has started

### Description

final public static Ev::now(): float

Returns the time when the last iteration of the default event loop has started. This is the time that timers( EvTimer and EvPeriodic) are based on, and referring to it is usually faster then calling Ev::time().

### Parameters

This function has no parameters.

### Return Values

Returns number of seconds(fractional) representing the time when the last iteration of the default event loop has started.

### See Also

- Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

# Ev::nowUpdate

(PECL ev >= 0.2.0)

Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

### Description

final public static Ev::nowUpdate(): void

Establishes the current time by querying the kernel, updating the time returned by Ev::now() in the progress. This is a costly operation and is usually done automatically within Ev::run().

This method is rarely useful, but when some event callback runs for a very long time without entering the event loop, updating libev 's consideration of the current time is a good idea.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Ev::now() - Returns the time when the last iteration of the default event loop has started

# Ev::recommendedBackends

(PECL ev >= 0.2.0)

Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform

### Description

final public static Ev::recommendedBackends(): int

Returns the set of all backends compiled into this binary of `libev` and also recommended for this platform, meaning it will work for most file descriptor types. This set is often smaller than the one returned by ev_supported_backends(), as for example `kqueue` is broken on most `BSD` systems and will not be auto-detected unless it is requested explicitly. This is the set of backends that `libev` will probe no backends specified explicitly.

### Parameters

This function has no parameters.

### Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

### Examples

Example #1 Embedding one loop into another

`<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed = NULL;
/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
: 0;
if ($loop_lo) {
$embed = new EvEmbed($loop_lo, function () {});
} else {
$loop_lo = $loop_hi;
}
?>`

### See Also

- EvEmbed
- Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
- Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
- Backend flags
- Examples

# Ev::resume

(PECL ev >= 0.2.0)

Ev::resume — Resume previously suspended default event loop

### Description

final public static Ev::resume(): void

Ev::suspend() and Ev::resume() methods suspend and resume a loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume, and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume(). Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend().

Calling suspend / resume has the side effect of updating the event loop time(see Ev::nowUpdate() ).

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Ev::suspend() - Suspend the default event loop

# Ev::run

(PECL ev >= 0.2.0)

Ev::run — Begin checking for events and calling callbacks for the default loop

### Description

final public static Ev::run( int `$flags` = ?): void

Begin checking for events and calling callbacks for the default loop. Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is `true`), in which case the return value will be `false`. The return value can generally be interpreted as if `true`, there is more work left to do.

### Parameters

`flags`

  Optional parameter `flags` can be one of the following:

  List for possible values of `flags`
  `flags` | Description
  --- | ---
  `0` | The default behavior described above
  `Ev::RUN_ONCE` | Block at most one(wait, but don't loop)
  `Ev::RUN_NOWAIT` | Don't block at all(fetch/handle events, but don't wait)

  See the run flag constants.

### Return Values

No value is returned.

### See Also

- Ev::stop() - Stops the default event loop
- EvLoop::run() - Begin checking for events and calling callbacks for the loop

# Ev::sleep

(PECL ev >= 0.2.0)

Ev::sleep — Block the process for the given number of seconds

### Description

final public static Ev::sleep( float `$seconds` ): void

Block the process for the given number of seconds.

### Parameters

`seconds`
  Fractional number of seconds

### Return Values

No value is returned.

# Ev::stop

(PECL ev >= 0.2.0)

Ev::stop — Stops the default event loop

### Description

final public static Ev::stop( int `$how` = ?): void

Stops the default event loop

### Parameters

`how`
  One of Ev::BREAK_* constants.

### Return Values

No value is returned.

### See Also

- Ev::run() - Begin checking for events and calling callbacks for the default loop

# Ev::supportedBackends

(PECL ev >= 0.2.0)

Ev::supportedBackends — Returns the set of backends supported by current libev configuration

### Description

final public static Ev::supportedBackends(): int

Returns the set of backends supported by current libev configuration.

### Parameters

This function has no parameters.

### Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

### Examples

Example #1 Embedding loop created with kqueue backend into the default loop

`<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;
if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}
if (!$socket_loop) {
$socket_loop = $loop;
}
// Now use $socket_loop for all sockets, and $loop for anything else
?>`

### See Also

- EvEmbed
- Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
- Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
- Backend flags
- Examples

# Ev::suspend

(PECL ev >= 0.2.0)

Ev::suspend — Suspend the default event loop

### Description

final public static Ev::suspend(): void

Ev::suspend() and Ev::resume() methods suspend and resume the default loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume, and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume(). Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend().

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Ev::resume() - Resume previously suspended default event loop

# Ev::time

(PECL ev >= 0.2.0)

Ev::time — Returns the current time in fractional seconds since the epoch

### Description

final public static Ev::time(): float

Returns the current time in fractional seconds since the epoch. Consider using Ev::now()

### Parameters

This function has no parameters.

### Return Values

Returns the current time in fractional seconds since the epoch.

### See Also

- Ev::now() - Returns the time when the last iteration of the default event loop has started

# Ev::verify

(PECL ev >= 0.2.0)

Ev::verify — Performs internal consistency checks(for debugging)

### Description

final public static Ev::verify(): void

Performs internal consistency checks(for debugging libev) and abort the program if any data structures were found to be corrupted.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

## Table of Contents

- Ev::backend — Returns an integer describing the backend used by libev
- Ev::depth — Returns recursion depth
- Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops
- Ev::feedSignal — Feed a signal event info Ev
- Ev::feedSignalEvent — Feed signal event into the default loop
- Ev::iteration — Return the number of times the default event loop has polled for new events
- Ev::now — Returns the time when the last iteration of the default event loop has started
- Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
- Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform
- Ev::resume — Resume previously suspended default event loop
- Ev::run — Begin checking for events and calling callbacks for the default loop
- Ev::sleep — Block the process for the given number of seconds
- Ev::stop — Stops the default event loop
- Ev::supportedBackends — Returns the set of backends supported by current libev configuration
- Ev::suspend — Suspend the default event loop
- Ev::time — Returns the current time in fractional seconds since the epoch
- Ev::verify — Performs internal consistency checks(for debugging)

# The EvCheck class

(PECL ev >= 0.2.0)

## Introduction

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck, so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( `Ev::MAXPRI`) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

## Class synopsis

class EvCheck extends EvWatcher {
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct( callable `$callback` , mixed `$data` = ?, int `$priority` = ?)
final public static createStopped( string `$callback` , string `$data` = ?, string `$priority` = ?): object
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

# EvCheck::__construct

(PECL ev >= 0.2.0)

EvCheck::__construct — Constructs the EvCheck watcher object

### Description

public EvCheck::__construct( callable `$callback` , mixed `$data` = ?, int `$priority` = ?)

Constructs the EvCheck watcher object.

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvPrepare
- EvLoop::check() - Creates EvCheck object associated with the current event loop instance

# EvCheck::createStopped

(PECL ev >= 0.2.0)

EvCheck::createStopped — Create instance of a stopped EvCheck watcher

### Description

final public static EvCheck::createStopped( string `$callback` , string `$data` = ?, string `$priority` = ?): object

Create instance of a stopped EvCheck watcher

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns EvCheck object on success.

### See Also

- EvPrepare

## Table of Contents

- EvCheck::__construct — Constructs the EvCheck watcher object
- EvCheck::createStopped — Create instance of a stopped EvCheck watcher

# The EvChild class

(PECL ev >= 0.2.0)

## Introduction

EvChild watchers trigger when the process receives a `SIGCHLD` in response to some child status changes (most typically when a child dies or exits). It is permissible to install an `EvChild` watcher after the child has been forked(which implies it might have already exited), as long as the event loop isn't entered(or is continued from a watcher), i.e. forking and then immediately registering a watcher for the child is fine, but forking and registering a watcher a few event loop iterations later or in the next callback invocation is not.

It is allowed to register EvChild watchers in the default loop only.

## Class synopsis

class EvChild extends EvWatcher {
/* Properties */
public $pid;
public $rpid;
public $rstatus;
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct(
int `$pid` ,
bool `$trace` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
)
final public static createStopped(
int `$pid` ,
bool `$trace` ,
callable `$callback` ,
mixed `$data` = ?,
int `$priority` = ?
): object
public set( int `$pid` , bool `$trace` ): void
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

## Properties

pid
  Readonly. The process ID this watcher watches out for, or `0`, meaning any process ID.
rpid
  Readonly .The process ID that detected a status change.
rstatus
  Readonly. The process exit status caused by rpid.

# EvChild::__construct

(PECL ev >= 0.2.0)

EvChild::__construct — Constructs the EvChild watcher object

### Description

public EvChild::__construct(
int `$pid` ,
bool `$trace` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
)

Constructs the EvChild watcher object.

Call the callback when a status change for process ID `pid` (or any PID if `pid` is `0`) has been received(a status change happens when the process terminates or is killed, or, when `trace` is `true`, additionally when it is stopped or continued). In other words, when the process receives a `SIGCHLD`, Ev will fetch the outstanding exit/wait status for all changed/zombie children and call the callback.

It is valid to install a child watcher after an EvChild has exited but before the event loop has started its next iteration. For example, first one calls `fork`, then the new child process might exit, and only then an EvChild watcher is installed in the parent for the new PID.

You can access both exit/tracing status and `pid` by using the rstatus and rpid properties of the watcher object.

The number of PID watchers per PID is unlimited. All of them will be called.

The EvChild::createStopped() method doesn't start(activate) the newly created watcher.

### Parameters

`pid`
  Wait for status changes of process PID(or any process if PID is specified as `0` ).
`trace`
  If `false`, only activate the watcher when the process terminates. Otherwise(`true`) additionally activate the watcher when the process is stopped or continued.
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvLoop::child() - Creates EvChild object associated with the current event loop

# EvChild::createStopped

(PECL ev >= 0.2.0)

EvChild::createStopped — Create instance of a stopped EvCheck watcher

### Description

final public static EvChild::createStopped(
int `$pid` ,
bool `$trace` ,
callable `$callback` ,
mixed `$data` = ?,
int `$priority` = ?
): object

The same as EvChild::__construct(), but doesn't start the watcher automatically.

### Parameters

`pid`
  The same as for EvChild::__construct()
`trace`
  The same as for EvChild::__construct()
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

### See Also

- EvChild::__construct() - Constructs the EvChild watcher object
- EvLoop::child() - Creates EvChild object associated with the current event loop

# EvChild::set

(PECL ev >= 0.2.0)

EvChild::set — Configures the watcher

### Description

public EvChild::set( int `$pid` , bool `$trace` ): void

### Parameters

`pid`
  The same as for EvChild::__construct()
`trace`
  The same as for EvChild::__construct()

### Return Values

No value is returned.

### See Also

- EvChild::__construct() - Constructs the EvChild watcher object

## Table of Contents

- EvChild::__construct — Constructs the EvChild watcher object
- EvChild::createStopped — Create instance of a stopped EvCheck watcher
- EvChild::set — Configures the watcher

# The EvEmbed class

(PECL ev >= 0.2.0)

## Introduction

Used to embed one event loop into another.

## Class synopsis

class EvEmbed extends EvWatcher {
/* Properties */
public $embed;
/* Methods */
public __construct(
object `$other` ,
callable `$callback` = ?,
mixed `$data` = ?,
int `$priority` = ?
)
final public static createStopped(
object `$other` ,
callable `$callback` = ?,
mixed `$data` = ?,
int `$priority` = ?
): void
public set( object `$other` ): void
public sweep(): void
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

## Properties

is_active
data
is_pending
priority
embed

# EvEmbed::__construct

(PECL ev >= 0.2.0)

EvEmbed::__construct — Constructs the EvEmbed object

### Description

public EvEmbed::__construct(
object `$other` ,
callable `$callback` = ?,
mixed `$data` = ?,
int `$priority` = ?
)

This is a rather advanced watcher type that lets to embed one event loop into another(currently only IO events are supported in the embedded loop, other types of watchers might be handled in a delayed or incorrect fashion and must not be used).

See » the libev documentation for details.

This watcher is most useful on BSD systems without working `kqueue` to still be able to handle a large number of sockets. See example below.

### Parameters

`other`
  Instance of EvLoop. The loop to embed, this loop must be embeddable(see Ev::embeddableBackends() ).
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Examples

Example #1 Embedding loop created with kqueue backend into the default loop

`<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;
if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}
if (!$socket_loop) {
$socket_loop = $loop;
}
// Now use $socket_loop for all sockets, and $loop for anything else
?>`

### See Also

- Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops

# EvEmbed::createStopped

(PECL ev >= 0.2.0)

EvEmbed::createStopped — Create stopped EvEmbed watcher object

### Description

final public static EvEmbed::createStopped(
object `$other` ,
callable `$callback` = ?,
mixed `$data` = ?,
int `$priority` = ?
): void

The same as EvEmbed::__construct(), but doesn't start the watcher automatically.

### Parameters

`other`
  The same as for EvEmbed::__construct()
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns stopped EvEmbed object on success.

### See Also

- EvEmbed::__construct() - Constructs the EvEmbed object
- Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops

# EvEmbed::set

(PECL ev >= 0.2.0)

EvEmbed::set — Configures the watcher

### Description

public EvEmbed::set( object `$other` ): void

Configures the watcher to use `other` event loop object.

### Parameters

`other`
  The same as for EvEmbed::__construct()

### Return Values

No value is returned.

# EvEmbed::sweep

(PECL ev >= 0.2.0)

EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop

### Description

public EvEmbed::sweep(): void

Make a single, non-blocking sweep over the embedded loop. Works similarly to the following, but in the most appropriate way for embedded loops:

`<?php
$other->start(Ev::RUN_NOWAIT);
?>`

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- EvWatcher::start() - Starts the watcher

## Table of Contents

- EvEmbed::__construct — Constructs the EvEmbed object
- EvEmbed::createStopped — Create stopped EvEmbed watcher object
- EvEmbed::set — Configures the watcher
- EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop

# The EvFork class

(PECL ev >= 0.2.0)

## Introduction

Fork watchers are called when a `fork()` was detected (usually because whoever signalled libev about it by calling EvLoop::fork() ). The invocation is done before the event loop blocks next and before EvCheck watchers are being called, and only in the child after the fork. Note, that if whoever calling EvLoop::fork() calls it in the wrong process, the fork handlers will be invoked, too.

## Class synopsis

class EvFork extends EvWatcher {
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 )
final public static createStopped( string `$callback` , string `$data` = ?, string `$priority` = ?): object
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

# EvFork::__construct

(PECL ev >= 0.2.0)

EvFork::__construct — Constructs the EvFork watcher object

### Description

public EvFork::__construct( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 )

Constructs the EvFork watcher object and starts the watcher automatically.

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvLoop::fork() - Creates EvFork watcher object associated with the current event loop instance
- EvCheck

# EvFork::createStopped

(PECL ev >= 0.2.0)

EvFork::createStopped — Creates a stopped instance of EvFork watcher class

### Description

final public static EvFork::createStopped( string `$callback` , string `$data` = ?, string `$priority` = ?): object

The same as EvFork::__construct(), but doesn't start the watcher automatically.

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns EvFork(stopped) object on success.

### See Also

- EvFork::__construct() - Constructs the EvFork watcher object

## Table of Contents

- EvFork::__construct — Constructs the EvFork watcher object
- EvFork::createStopped — Creates a stopped instance of EvFork watcher class

# The EvIdle class

(PECL ev >= 0.2.0)

## Introduction

EvIdle watchers trigger events when no other events of the same or higher priority are pending ( EvPrepare, EvCheck and other EvIdle watchers do not count as receiving events ).

Thus, as long as the process is busy handling sockets or timeouts(or even signals) of the same or higher priority it will not be triggered. But when the process is in idle(or only lower-priority watchers are pending), the EvIdle watchers are being called once per event loop iteration - until stopped, that is, or the process receives more events and becomes busy again with higher priority stuff.

Apart from keeping the process non-blocking(which is a useful on its own sometimes), EvIdle watchers are a good place to do "pseudo-background processing", or delay processing stuff to after the event loop has handled all outstanding events.

The most noticeable effect is that as long as any idle watchers are active, the process will not block when waiting for new events.

## Class synopsis

class EvIdle extends EvWatcher {
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct( callable `$callback` , mixed `$data` = ?, int `$priority` = ?)
final public static createStopped( string `$callback` , mixed `$data` = ?, int `$priority` = ?): object
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

# EvIdle::__construct

(PECL ev >= 0.2.0)

EvIdle::__construct — Constructs the EvIdle watcher object

### Description

public EvIdle::__construct( callable `$callback` , mixed `$data` = ?, int `$priority` = ?)

Constructs the EvIdle watcher object and starts the watcher automatically.

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvIdle::createStopped() - Creates instance of a stopped EvIdle watcher object
- EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

# EvIdle::createStopped

(PECL ev >= 0.2.0)

EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

### Description

final public static EvIdle::createStopped( string `$callback` , mixed `$data` = ?, int `$priority` = ?): object

The same as EvIdle::__construct(), but doesn't start the watcher automatically.

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns EvIdle object on success.

### See Also

- EvIdle::__construct() - Constructs the EvIdle watcher object
- EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

## Table of Contents

- EvIdle::__construct — Constructs the EvIdle watcher object
- EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

# The EvIo class

(PECL ev >= 0.2.0)

## Introduction

EvIo watchers check whether a file descriptor(or socket, or a stream castable to numeric file descriptor) is readable or writable in each iteration of the event loop, or, more precisely, when reading would not block the process and writing would at least be able to write some data. This behaviour is called level-triggering because events are kept receiving as long as the condition persists. To stop receiving events just stop the watcher.

The number of read and/or write event watchers per `fd` is unlimited. Setting all file descriptors to non-blocking mode is also usually a good idea(but not required).

Another thing to watch out for is that it is quite easy to receive false readiness notifications, i.e. the callback might be called with `Ev::READ` but a subsequent read() will actually block because there is no data. It is very easy to get into this situation. Thus it is best to always use non-blocking I/O: An extra read() returning `EAGAIN` (or similar) is far preferable to a program hanging until some data arrives.

If for some reason it is impossible to run the `fd` in non-blocking mode, then separately re-test whether a file descriptor is really ready. Some people additionally use `SIGALRM` and an interval timer, just to be sure thry won't block infinitely.

Always consider using non-blocking mode.

## Class synopsis

class EvIo extends EvWatcher {
/* Properties */
public $fd;
public $events;
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = ?,
int `$priority` = ?
)
final public static createStopped(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvIo
public set( mixed `$fd` , int `$events` ): void
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

## Properties

fd
events

# EvIo::__construct

(PECL ev >= 0.2.0)

EvIo::__construct — Constructs EvIo watcher object

### Description

public EvIo::__construct(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = ?,
int `$priority` = ?
)

Constructs EvIo watcher object and starts the watcher automatically.

### Parameters

`fd`
  Can be a stream opened with fopen() or similar functions, numeric file descriptor, or socket.
`events`
  `Ev::READ` and/or `Ev::WRITE`. See the bit masks.
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvIo::createStopped() - Create stopped EvIo watcher object
- EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

# EvIo::createStopped

(PECL ev >= 0.2.0)

EvIo::createStopped — Create stopped EvIo watcher object

### Description

final public static EvIo::createStopped(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvIo

The same as EvIo::__construct(), but doesn't start the watcher automatically.

### Parameters

`fd`
  The same as for EvIo::__construct()
`events`
  The same as for EvIo::__construct()
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns EvIo object on success.

### See Also

- EvIo::__construct() - Constructs EvIo watcher object
- EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

# EvIo::set

(PECL ev >= 0.2.0)

EvIo::set — Configures the watcher

### Description

public EvIo::set( mixed `$fd` , int `$events` ): void

Configures the EvIo watcher

### Parameters

`fd`
  The same as for EvIo::__construct()
`events`
  The same as for EvIo::__construct()

### Return Values

No value is returned.

## Table of Contents

- EvIo::__construct — Constructs EvIo watcher object
- EvIo::createStopped — Create stopped EvIo watcher object
- EvIo::set — Configures the watcher

# The EvLoop class

(PECL ev >= 0.2.0)

## Introduction

Represents an event loop that is always distinct from the default loop. Unlike the default loop, it cannot handle EvChild watchers.

Having threads we have to create a loop per thread, and use the default loop in the parent thread.

The default event loop is initialized automatically by Ev. It is accessible via methods of the Ev class, or via EvLoop::defaultLoop() method.

## Class synopsis

final class EvLoop {
/* Properties */
public $data;
public $backend;
public $is_default_loop;
public $iteration;
public $pending;
public $io_interval;
public $timeout_interval;
public $depth;
/* Methods */
public __construct(
int `$flags` = ?,
mixed `$data` = NULL ,
float `$io_interval` = 0.0 ,
float `$timeout_interval` = 0.0
)
public backend(): int
final public check( string `$callback` , string `$data` = ?, string `$priority` = ?): EvCheck
final public child(
string `$pid` ,
string `$trace` ,
string `$callback` ,
string `$data` = ?,
string `$priority` = ?
): EvChild
public static defaultLoop(
int `$flags` = Ev::FLAG_AUTO ,
mixed `$data` = NULL ,
float `$io_interval` = 0. ,
float `$timeout_interval` = 0.
): EvLoop
final public embed(
string `$other` ,
string `$callback` = ?,
string `$data` = ?,
string `$priority` = ?
): EvEmbed
final public fork( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvFork
final public idle( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvIdle
public invokePending(): void
final public io(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvIo
public loopFork(): void
public now(): float
public nowUpdate(): void
final public periodic(
float `$offset` ,
float `$interval` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvPeriodic
final public prepare( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvPrepare
public resume(): void
public run( int `$flags` = 0 ): void
final public signal(
int `$signum` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvSignal
final public stat(
string `$path` ,
float `$interval` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvStat
public stop( int `$how` = ?): void
public suspend(): void
final public timer(
float `$after` ,
float `$repeat` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvTimer
public verify(): void
}

## Properties

data
  Custom data attached to loop
backend
  Readonly. The backend flags indicating the event backend in use.
is_default_loop
  Readonly. `true` if it is the default event loop.
iteration
  The current iteration count of the loop. See Ev::iteration()
pending
  The number of pending watchers. `0` indicates that there are no watchers pending.
io_interval
  Higher io_interval allows libev to spend more time collecting EvIo events, so more events can be handled per iteration, at the cost of increasing latency. Timeouts (both EvPeriodic and EvTimer) will not be affected. Setting this to a non-zero value will introduce an additional `sleep()` call into most loop iterations. The sleep time ensures that libev will not poll for EvIo events more often than once per this interval, on average. Many programs can usually benefit by setting the io_interval to a value near `0.1`, which is often enough for interactive servers(not for games). It usually doesn't make much sense to set it to a lower value than `0.01`, as this approaches the timing granularity of most systems. See also » FUNCTIONS CONTROLLING EVENT LOOPS.
timeout_interval
  Higher timeout_interval allows libev to spend more time collecting timeouts, at the expense of increased latency/jitter/inexactness(the watcher callback will be called later). EvIo watchers will not be affected. Setting this to a non-null value will not introduce any overhead in libev. See also » FUNCTIONS CONTROLLING EVENT LOOPS.
depth
  The recursion depth. See Ev::depth().

# EvLoop::backend

(PECL ev >= 0.2.0)

EvLoop::backend — Returns an integer describing the backend used by libev

### Description

public EvLoop::backend(): int

The same as Ev::backend(), but for the loop instance.

### Parameters

This function has no parameters.

### Return Values

Returns an integer describing the backend used by libev. See Ev::backend().

### See Also

- Ev::backend() - Returns an integer describing the backend used by libev

# EvLoop::check

(PECL ev >= 0.2.0)

EvLoop::check — Creates EvCheck object associated with the current event loop instance

### Description

final public EvLoop::check( string `$callback` , string `$data` = ?, string `$priority` = ?): EvCheck

Creates EvCheck object associated with the current event loop instance.

### Parameters

All parameters have the same meaning as for EvCheck::__construct()

### Return Values

Returns EvCheck object on success.

### See Also

- EvCheck::__construct() - Constructs the EvCheck watcher object

# EvLoop::child

(PECL ev >= 0.2.0)

EvLoop::child — Creates EvChild object associated with the current event loop

### Description

final public EvLoop::child(
string `$pid` ,
string `$trace` ,
string `$callback` ,
string `$data` = ?,
string `$priority` = ?
): EvChild

Creates EvChild object associated with the current event loop.

### Parameters

All parameters have the same meaning as for EvChild::__construct()

### Return Values

Returns EvChild object on success.

### See Also

- EvChild::__construct() - Constructs the EvChild watcher object

# EvLoop::__construct

(PECL ev >= 0.2.0)

EvLoop::__construct — Constructs the event loop object

### Description

public EvLoop::__construct(
int `$flags` = ?,
mixed `$data` = NULL ,
float `$io_interval` = 0.0 ,
float `$timeout_interval` = 0.0
)

Constructs the event loop object.

### Parameters

`flags`
  One of the event loop flags
`data`
  Custom data associated with the loop.
`io_interval`
  See io_interval
`timeout_interval`
  See timeout_interval

### See Also

- EvLoop::defaultLoop() - Returns or creates the default event loop

# EvLoop::defaultLoop

(PECL ev >= 0.2.0)

EvLoop::defaultLoop — Returns or creates the default event loop

### Description

public static EvLoop::defaultLoop(
int `$flags` = Ev::FLAG_AUTO ,
mixed `$data` = NULL ,
float `$io_interval` = 0. ,
float `$timeout_interval` = 0.
): EvLoop

If the default event loop is not created, EvLoop::defaultLoop() creates it with the specified parameters. Otherwise, it just returns the object representing previously created instance ignoring all the parameters.

### Parameters

`flags`
  One of the event loop flags
`data`
  Custom data to associate with the loop.
`io_collect_interval`
  See io_interval
`timeout_collect_interval`
  See timeout_interval

### Return Values

Returns EvLoop object on success.

### See Also

- EvLoop::__construct() - Constructs the event loop object

# EvLoop::embed

(PECL ev >= 0.2.0)

EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object

### Description

final public EvLoop::embed(
string `$other` ,
string `$callback` = ?,
string `$data` = ?,
string `$priority` = ?
): EvEmbed

Creates an instance of EvEmbed watcher associated with the current EvLoop object.

### Parameters

All parameters have the same meaning as for EvEmbed::__construct().

### Return Values

Returns EvEmbed object on success.

### See Also

- EvEmbed::__construct() - Constructs the EvEmbed object

# EvLoop::fork

(PECL ev >= 0.2.0)

EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance

### Description

final public EvLoop::fork( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvFork

Creates EvFork watcher object associated with the current event loop instance

### Parameters

All parameters have the same meaning as for EvFork::__construct()

### Return Values

Returns EvFork object on success.

### See Also

- EvFork::__construct() - Constructs the EvFork watcher object

# EvLoop::idle

(PECL ev >= 0.2.0)

EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance

### Description

final public EvLoop::idle( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvIdle

Creates EvIdle watcher object associated with the current event loop instance

### Parameters

All the parameters have the same meaning as for EvIdle::__construct()

### Return Values

Returns EvIdle object on success.

### See Also

- EvIdle::__construct() - Constructs the EvIdle watcher object

# EvLoop::invokePending

(PECL ev >= 0.2.0)

EvLoop::invokePending — Invoke all pending watchers while resetting their pending state

### Description

public EvLoop::invokePending(): void

Invoke all pending watchers while resetting their pending state.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# EvLoop::io

(PECL ev >= 0.2.0)

EvLoop::io — Create EvIo watcher object associated with the current event loop instance

### Description

final public EvLoop::io(
mixed `$fd` ,
int `$events` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvIo

Create EvIo watcher object associated with the current event loop instance.

### Parameters

All parameters have the same meaning as for EvIo::__construct()

### Return Values

Returns EvIo object on success.

### See Also

- EvIo::__construct() - Constructs EvIo watcher object

# EvLoop::loopFork

(PECL ev >= 0.2.0)

EvLoop::loopFork — Must be called after a fork

### Description

public EvLoop::loopFork(): void

Must be called after a fork in the child, before entering or continuing the event loop. An alternative is to use `Ev::FLAG_FORKCHECK` which calls this function automatically, at some performance loss (refer to the » libev documentation ).

### Parameters

This function has no parameters.

### Return Values

No value is returned.

# EvLoop::now

(PECL ev >= 0.2.0)

EvLoop::now — Returns the current "event loop time"

### Description

public EvLoop::now(): float

Returns the current "event loop time", which is the time the event loop received events and started processing them. This timestamp does not change as long as callbacks are being processed, and this is also the base time used for relative timers. You can treat it as the timestamp of the event occurring(or more correctly, libev finding out about it).

### Parameters

This function has no parameters.

### Return Values

Returns time of the event loop in (fractional) seconds.

### See Also

- Ev::now() - Returns the time when the last iteration of the default event loop has started

# EvLoop::nowUpdate

(PECL ev >= 0.2.0)

EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

### Description

public EvLoop::nowUpdate(): void

Establishes the current time by querying the kernel, updating the time returned by EvLoop::now() in the progress. This is a costly operation and is usually done automatically within EvLoop::run().

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- EvLoop::now() - Returns the current "event loop time"
- Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

# EvLoop::periodic

(PECL ev >= 0.2.0)

EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance

### Description

final public EvLoop::periodic(
float `$offset` ,
float `$interval` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvPeriodic

Creates EvPeriodic watcher object associated with the current event loop instance

### Parameters

All parameters have the same maening as for EvPeriodic::__construct()

### Return Values

Returns EvPeriodic object on success.

### See Also

- EvPeriodic::__construct() - Constructs EvPeriodic watcher object

# EvLoop::prepare

(PECL ev >= 0.2.0)

EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance

### Description

final public EvLoop::prepare( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvPrepare

Creates EvPrepare watcher object associated with the current event loop instance

### Parameters

All parameters have the same maening as for EvPrepare()

### Return Values

Returns EvPrepare object on success

### See Also

- EvPrepare::__construct() - Constructs EvPrepare watcher object

# EvLoop::resume

(PECL ev >= 0.2.0)

EvLoop::resume — Resume previously suspended default event loop

### Description

public EvLoop::resume(): void

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- EvLoop::suspend() - Suspend the loop
- Ev::resume() - Resume previously suspended default event loop

# EvLoop::run

(PECL ev >= 0.2.0)

EvLoop::run — Begin checking for events and calling callbacks for the loop

### Description

public EvLoop::run( int `$flags` = 0 ): void

Begin checking for events and calling callbacks for the current event loop. Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is `true`), in which case the return value will be `false`. The return value can generally be interpreted as if `true`, there is more work left to do.

### Parameters

`flags`

  Optional parameter `flags` can be one of the following:

  List for possible values of `flags`
  `flags` | Description
  --- | ---
  `0` | The default behavior described above
  `Ev::RUN_ONCE` | Block at most one(wait, but don't loop)
  `Ev::RUN_NOWAIT` | Don't block at all(fetch/handle events, but don't wait)

  See the run flag constants.

### Return Values

No value is returned.

### See Also

- EvLoop::stop() - Stops the event loop
- Ev::run() - Begin checking for events and calling callbacks for the default loop

# EvLoop::signal

(PECL ev >= 0.2.0)

EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance

### Description

final public EvLoop::signal(
int `$signum` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvSignal

Creates EvSignal watcher object associated with the current event loop instance

### Parameters

All parameters have the same meaning as for EvSignal::__construct()

### Return Values

Returns EvSignal object on success

### See Also

- EvSignal::__construct() - Constructs EvSignal watcher object

# EvLoop::stat

(PECL ev >= 0.2.0)

EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance

### Description

final public EvLoop::stat(
string `$path` ,
float `$interval` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvStat

Creates EvStat watcher object associated with the current event loop instance

### Parameters

All parameters have the same meaning as for EvSignal::__construct()

### Return Values

Returns EvStat object on success

### See Also

- EvSignal::__construct() - Constructs EvSignal watcher object

# EvLoop::stop

(PECL ev >= 0.2.0)

EvLoop::stop — Stops the event loop

### Description

public EvLoop::stop( int `$how` = ?): void

Stops the event loop

### Parameters

`how`
  One of Ev::BREAK_* constants.

### Return Values

No value is returned.

### See Also

- EvLoop::run() - Begin checking for events and calling callbacks for the loop
- Ev::stop() - Stops the default event loop

# EvLoop::suspend

(PECL ev >= 0.2.0)

EvLoop::suspend — Suspend the loop

### Description

public EvLoop::suspend(): void

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- EvLoop::resume() - Resume previously suspended default event loop
- Ev::suspend() - Suspend the default event loop

# EvLoop::timer

(PECL ev >= 0.2.0)

EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance

### Description

final public EvLoop::timer(
float `$after` ,
float `$repeat` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvTimer

Creates EvTimer watcher object associated with the current event loop instance

### Parameters

All parameters have the same meaning as for EvTimer::__construct()

### Return Values

Returns EvTimer object on success

### See Also

- EvTimer::__construct() - Constructs an EvTimer watcher object

# EvLoop::verify

(PECL ev >= 0.2.0)

EvLoop::verify — Performs internal consistency checks(for debugging)

### Description

public EvLoop::verify(): void

Performs internal consistency checks(for debugging libev) and abort the program if any data structures were found to be corrupted.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- Ev::verify() - Performs internal consistency checks(for debugging)

## Table of Contents

- EvLoop::backend — Returns an integer describing the backend used by libev
- EvLoop::check — Creates EvCheck object associated with the current event loop instance
- EvLoop::child — Creates EvChild object associated with the current event loop
- EvLoop::__construct — Constructs the event loop object
- EvLoop::defaultLoop — Returns or creates the default event loop
- EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object
- EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
- EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
- EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
- EvLoop::io — Create EvIo watcher object associated with the current event loop instance
- EvLoop::loopFork — Must be called after a fork
- EvLoop::now — Returns the current "event loop time"
- EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
- EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
- EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
- EvLoop::resume — Resume previously suspended default event loop
- EvLoop::run — Begin checking for events and calling callbacks for the loop
- EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
- EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
- EvLoop::stop — Stops the event loop
- EvLoop::suspend — Suspend the loop
- EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
- EvLoop::verify — Performs internal consistency checks(for debugging)

# The EvPeriodic class

(PECL ev >= 0.2.0)

## Introduction

Periodic watchers are also timers of a kind, but they are very versatile.

Unlike EvTimer, EvPeriodic watchers are not based on real time(or relative time, the physical time that passes) but on wall clock time(absolute time, calendar or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon(e.g. when adjusting it).

EvPeriodic watcher can be configured to trigger after some specific point in time. For example, if an EvPeriodic watcher is configured to trigger "in 10 seconds" (e.g. EvLoop::now() + `10.0`, i.e. an absolute time, not a delay), and the system clock is reset to January of the previous year, then it will take a year or more to trigger the event (unlike an EvTimer, which would still trigger roughly `10` seconds after starting it as it uses a relative timeout).

As with timers, the callback is guaranteed to be invoked only when the point in time where it is supposed to trigger has passed. If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

## Class synopsis

class EvPeriodic extends EvWatcher {
/* Properties */
public $offset;
public $interval;
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct(
float `$offset` ,
string `$interval` ,
callable `$reschedule_cb` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
)
public again(): void
public at(): float
final public static createStopped(
float `$offset` ,
float `$interval` ,
callable `$reschedule_cb` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvPeriodic
public set( float `$offset` , float `$interval` ): void
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

## Properties

offset
  When repeating, this contains the offset value, otherwise this is the absolute point in time(the offset value passed to EvPeriodic::set(), although libev might modify this value for better numerical stability).
interval
  The current interval value. Can be modified any time, but changes only take effect when the periodic timer fires or EvPeriodic::again() is being called.

# EvPeriodic::again

(PECL ev >= 0.2.0)

EvPeriodic::again — Simply stops and restarts the periodic watcher again

### Description

public EvPeriodic::again(): void

Simply stops and restarts the periodic watcher again. This is only useful when attributes are changed.

### Parameters

This function has no parameters.

### Return Values

No value is returned.

### See Also

- EvTimer::again() - Restarts the timer watcher

# EvPeriodic::at

(PECL ev >= 0.2.0)

EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next

### Description

public EvPeriodic::at(): float

When the watcher is active, returns the absolute time that this watcher is supposed to trigger next. This is not the same as the offset argument to EvPeriodic::set() or EvPeriodic::__construct(), but indeed works even in interval mode.

### Parameters

This function has no parameters.

### Return Values

Returns the absolute time this watcher is supposed to trigger next in seconds.

# EvPeriodic::__construct

(PECL ev >= 0.2.0)

EvPeriodic::__construct — Constructs EvPeriodic watcher object

### Description

public EvPeriodic::__construct(
float `$offset` ,
string `$interval` ,
callable `$reschedule_cb` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
)

Constructs EvPeriodic watcher object and starts it automatically. EvPeriodic::createStopped() method creates stopped periodic watcher.

### Parameters

`offset`
  See Periodic watcher operation modes
`interval`
  See Periodic watcher operation modes
`reschedule_cb`
  Reschedule callback. You can pass `null`. See Periodic watcher operation modes
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Examples

Example #1 Periodic timer. Use reschedule callback

`<?php
// Tick each 10.5 seconds
function reschedule_cb ($watcher, $now) {
return $now + (10.5. - fmod($now, 10.5));
}
$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>`

Example #2 Periodic timer. Tick every 10.5 seconds starting at now

`<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>`

Example #3 Hourly watcher

`<?php
$hourly = EvPeriodic(0, 3600, NULL, function () {
echo "once per hour\n";
});
?>`

### See Also

- Periodic watcher operation modes
- EvTimer
- EvPeriodic::createStopped() - Create a stopped EvPeriodic watcher

# EvPeriodic::createStopped

(PECL ev >= 0.2.0)

EvPeriodic::createStopped — Create a stopped EvPeriodic watcher

### Description

final public static EvPeriodic::createStopped(
float `$offset` ,
float `$interval` ,
callable `$reschedule_cb` ,
callable `$callback` ,
mixed `$data` = `null` ,
int `$priority` = 0
): EvPeriodic

Create EvPeriodic object. Unlike EvPeriodic::__construct() this method doesn't start the watcher automatically.

### Parameters

`offset`
  See Periodic watcher operation modes
`interval`
  See Periodic watcher operation modes
`reschedule_cb`
  Reschedule callback. You can pass `null`. See Periodic watcher operation modes
`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### Return Values

Returns EvPeriodic watcher object on success.

### See Also

- EvPeriodic::__construct() - Constructs EvPeriodic watcher object
- EvTimer::createStopped() - Creates EvTimer stopped watcher object

# EvPeriodic::set

(PECL ev >= 0.2.0)

EvPeriodic::set — Configures the watcher

### Description

public EvPeriodic::set( float `$offset` , float `$interval` ): void

(Re-)Configures EvPeriodic watcher

### Parameters

`offset`
  The same meaning as for EvPeriodic::__construct(). See Periodic watcher operation modes
`interval`
  The same meaning as for EvPeriodic::__construct(). See Periodic watcher operation modes

### Return Values

No value is returned.

## Table of Contents

- EvPeriodic::again — Simply stops and restarts the periodic watcher again
- EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
- EvPeriodic::__construct — Constructs EvPeriodic watcher object
- EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
- EvPeriodic::set — Configures the watcher

# The EvPrepare class

(PECL ev >= 0.2.0)

## Introduction

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck, so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( `Ev::MAXPRI`) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

## Class synopsis

class EvPrepare extends EvWatcher {
/* Inherited properties */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* Methods */
public __construct( string `$callback` , string `$data` = ?, string `$priority` = ?)
final public static createStopped( callable `$callback` , mixed `$data` = `null` , int `$priority` = 0 ): EvPrepare
/* Inherited methods */
public EvWatcher::clear(): int
public EvWatcher::feed( int `$revents` ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int `$revents` ): void
public EvWatcher::keepalive( bool `$value` = ?): bool
public EvWatcher::setCallback( callable `$callback` ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

# EvPrepare::__construct

(PECL ev >= 0.2.0)

EvPrepare::__construct — Constructs EvPrepare watcher object

### Description

public EvPrepare::__construct( string `$callback` , string `$data` = ?, string `$priority` = ?)

Constructs EvPrepare watcher object. And starts the watcher automatically. If need a stopped watcher consider using EvPrepare::createStopped()

### Parameters

`callback`
  See Watcher callbacks.
`data`
  Custom data associated with the watcher.
`priority`
  Watcher priority

### See Also

- EvCheck

# EvPrepare::createStopped

(PECL ev >= 0.2.0)

EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

### Description

final public static EvPrepare::createStopped(
[file cut: first 33554432 bytes kept]
